Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(swagger-ui): add support for oauth config #134

Merged
merged 3 commits into from
May 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions utoipa-swagger-ui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ mime_guess = { version = "2.0" }
actix-web = { version = "4", optional = true }
rocket = { version = "0.5.0-rc.1", features = ["json"], optional = true }
utoipa = { version = "1", path = "..", default-features = false, features = [] }
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0" }

[package.metadata.docs.rs]
features = ["actix-web", "rocket"]
Expand Down
86 changes: 84 additions & 2 deletions utoipa-swagger-ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@
//! [^rocket]: **rocket** feature need to be enabled.
use std::{borrow::Cow, error::Error, sync::Arc};

pub mod oauth;

#[cfg(feature = "actix-web")]
use actix_web::{
dev::HttpServiceFactory, guard::Get, web, web::Data, HttpResponse, Resource,
Expand Down Expand Up @@ -125,6 +127,7 @@ struct SwaggerUiDist;
pub struct SwaggerUi {
path: Cow<'static, str>,
urls: Vec<(Url<'static>, OpenApi)>,
oauth: Option<oauth::Config>,
}

#[cfg(any(feature = "actix-web", feature = "rocket"))]
Expand All @@ -146,6 +149,7 @@ impl SwaggerUi {
Self {
path: path.into(),
urls: Vec::new(),
oauth: None,
}
}

Expand Down Expand Up @@ -216,6 +220,33 @@ impl SwaggerUi {

self
}

/// Add oauth [`oauth::Config`] into [`SwaggerUi`].
///
/// Method takes one argument which exposes the [`oauth::Config`] to the user.
///
/// # Examples
///
/// Enable pkce with default client_id.
/// ```rust
/// # use utoipa_swagger_ui::{SwaggerUi, oauth};
/// # use utoipa::OpenApi;
/// # #[derive(OpenApi)]
/// # #[openapi(handlers())]
/// # struct ApiDoc;
/// let swagger = SwaggerUi::new("/swagger-ui/{_:.*}")
/// .url("/api-doc/openapi.json", ApiDoc::openapi())
/// .oauth(oauth::Config::new()
/// .client_id("client-id")
/// .scopes(vec![String::from("openid")])
/// .use_pkce_with_authorization_code_grant(true)
/// );
/// ```
pub fn oauth(mut self, oauth: oauth::Config) -> Self {
self.oauth = Some(oauth);

self
}
}

#[cfg(feature = "actix-web")]
Expand All @@ -233,7 +264,10 @@ impl HttpServiceFactory for SwaggerUi {

let swagger_resource = Resource::new(self.path.as_ref())
.guard(Get())
.app_data(Data::new(Config::new(urls)))
.app_data(Data::new(Config {
urls: urls,
oauth: self.oauth,
}))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block should also be added for rocket framework. Look at line 309 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

.to(serve_swagger_ui);

HttpServiceFactory::register(swagger_resource, config);
Expand Down Expand Up @@ -271,7 +305,13 @@ impl From<SwaggerUi> for Vec<Route> {
routes.push(Route::new(
rocket::http::Method::Get,
swagger_ui.path.as_ref(),
ServeSwagger(swagger_ui.path.clone(), Arc::new(Config::new(urls))),
ServeSwagger(
swagger_ui.path.clone(),
Arc::new(Config {
urls: urls.collect(),
oauth: swagger_ui.oauth,
}),
),
));
routes.extend(api_docs);

Expand Down Expand Up @@ -462,11 +502,22 @@ async fn serve_swagger_ui(path: web::Path<String>, data: web::Data<Config<'_>>)
/// Url::new("api2", "/api-doc/openapi2.json")
/// ]);
/// ```
///
/// With oauth config
/// ```rust
/// # use utoipa_swagger_ui::{Config, oauth};
/// let config = Config::with_oauth_config(
/// ["/api-doc/openapi1.json", "/api-doc/openapi2.json"],
/// oauth::Config::new(),
/// );
/// ```
#[non_exhaustive]
#[derive(Default, Clone)]
pub struct Config<'a> {
/// [`Url`]s the Swagger UI is serving.
urls: Vec<Url<'a>>,
/// [`oauth::Config`] the Swagger UI is using for auth flow.
oauth: Option<oauth::Config>,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could field could have a short doc comment on it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

}

impl<'a> Config<'a> {
Expand All @@ -481,6 +532,28 @@ impl<'a> Config<'a> {
pub fn new<I: IntoIterator<Item = U>, U: Into<Url<'a>>>(urls: I) -> Self {
Self {
urls: urls.into_iter().map(|url| url.into()).collect(),
oauth: None,
}
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add here a method with_oauth_config something like this.

pub fn with_oauth_config<I: IntoIterator<Item = U>, U: Into<Url<'a>>>(urls: I, 
   oauth_config: oauth::Config) -> Self {
        Self {
            urls: urls.into_iter().map(|url| url.into()).collect(),
            oauth: Some(oauth_config),
        }
}

This Config type is non_exhaustive for backwards compatibility purposes

Outside of the defining crate, types annotated with non_exhaustive have limitations that preserve backwards compatibility when new fields or variants are added.

Non-exhaustive types cannot be constructed outside of the defining crate:

Non-exhaustive variants (struct or enum variant) cannot be constructed with a StructExpression (including with functional update syntax).
enum instances can be constructed.
https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute

It is in Rust a good idea to define outside looking API with non_exhaustive and instead provide constructors new() or / and accessor fields or builder pattern to construct objects. This way the API implementator is at control and not every change to the API nor adding / changing / deleting one field will be a breaking change for API consumer.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


/// Constructs a new [`Config`] from [`Iterator`] of [`Url`]s.
///
/// # Examples
/// Create new config with oauth config
/// ```rust
/// # use utoipa_swagger_ui::{Config, oauth};
/// let config = Config::with_oauth_config(
/// ["/api-doc/openapi1.json", "/api-doc/openapi2.json"],
/// oauth::Config::new(),
/// );
/// ```
pub fn with_oauth_config<I: IntoIterator<Item = U>, U: Into<Url<'a>>>(
urls: I,
oauth_config: oauth::Config,
) -> Self {
Self {
urls: urls.into_iter().map(|url| url.into()).collect(),
oauth: Some(oauth_config),
}
}
}
Expand All @@ -489,6 +562,7 @@ impl<'a> From<&'a str> for Config<'a> {
fn from(s: &'a str) -> Self {
Self {
urls: vec![Url::from(s)],
oauth: None,
}
}
}
Expand All @@ -497,6 +571,7 @@ impl From<String> for Config<'_> {
fn from(s: String) -> Self {
Self {
urls: vec![Url::from(s)],
oauth: None,
}
}
}
Expand Down Expand Up @@ -573,6 +648,13 @@ pub fn serve<'a>(
};
file = format_swagger_config_urls(&mut config.urls.iter(), file);

if let Some(oauth) = &config.oauth {
match oauth::format_swagger_config(oauth, file) {
Ok(oauth_file) => file = oauth_file,
Err(error) => return Err(Box::new(error)),
}
}

bytes = Cow::Owned(file.as_bytes().to_vec())
};

Expand Down
Loading