Skip to content

Commit

Permalink
allow and defualt to None jwt_location
Browse files Browse the repository at this point in the history
  • Loading branch information
NexVeridian committed Jan 21, 2025
1 parent 06da6e9 commit 819b45e
Showing 1 changed file with 32 additions and 30 deletions.
62 changes: 32 additions & 30 deletions src/auth/openapi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use utoipa::{

use crate::{app::AppContext, config::JWTLocation};

static JWT_LOCATION: OnceLock<JWTLocation> = OnceLock::new();
static JWT_LOCATION: OnceLock<Option<JWTLocation>> = OnceLock::new();

pub fn get_jwt_location_from_ctx(ctx: &AppContext) -> JWTLocation {
ctx.config
Expand All @@ -19,47 +19,49 @@ pub fn get_jwt_location_from_ctx(ctx: &AppContext) -> JWTLocation {
.clone()
}

pub fn set_jwt_location_ctx(ctx: &AppContext) -> &'static JWTLocation {
pub fn set_jwt_location_ctx(ctx: &AppContext) -> &'static Option<JWTLocation> {
set_jwt_location(get_jwt_location_from_ctx(ctx))
}

pub fn set_jwt_location(jwt_location: JWTLocation) -> &'static JWTLocation {
JWT_LOCATION.get_or_init(|| jwt_location)
pub fn set_jwt_location(jwt_location: JWTLocation) -> &'static Option<JWTLocation> {
JWT_LOCATION.get_or_init(|| Some(jwt_location))
}

fn get_jwt_location() -> &'static JWTLocation {
JWT_LOCATION.get().unwrap_or(&JWTLocation::Bearer)
fn get_jwt_location() -> &'static Option<JWTLocation> {
JWT_LOCATION.get().unwrap_or(&None)
}

pub struct SecurityAddon;

/// Adds security to the OpenAPI doc, using the JWT location in the config
impl Modify for SecurityAddon {
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
if let Some(components) = openapi.components.as_mut() {
components.add_security_schemes_from_iter([
(
"jwt_token",
match get_jwt_location() {
JWTLocation::Bearer => SecurityScheme::Http(
HttpBuilder::new()
.scheme(HttpAuthScheme::Bearer)
.bearer_format("JWT")
.build(),
),
JWTLocation::Query { name } => {
SecurityScheme::ApiKey(ApiKey::Query(ApiKeyValue::new(name)))
}
JWTLocation::Cookie { name } => {
SecurityScheme::ApiKey(ApiKey::Cookie(ApiKeyValue::new(name)))
}
},
),
(
"api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::new("apikey"))),
),
]);
if let Some(jwt_location) = get_jwt_location() {
if let Some(components) = openapi.components.as_mut() {
components.add_security_schemes_from_iter([
(
"jwt_token",
match jwt_location {
JWTLocation::Bearer => SecurityScheme::Http(
HttpBuilder::new()
.scheme(HttpAuthScheme::Bearer)
.bearer_format("JWT")
.build(),
),
JWTLocation::Query { name } => {
SecurityScheme::ApiKey(ApiKey::Query(ApiKeyValue::new(name)))
}
JWTLocation::Cookie { name } => {
SecurityScheme::ApiKey(ApiKey::Cookie(ApiKeyValue::new(name)))
}
},
),
(
"api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::new("apikey"))),
),
]);
}
}
}
}

0 comments on commit 819b45e

Please sign in to comment.