use super::{ModeSpec, PermissionName, RoleName};
use crate::config::GarrisonConfig;
use crate::context::token_extract::strip_bearer_prefix;
use crate::error::GarrisonError;
use crate::stp::{with_current_token, GarrisonUtil};
use axum::extract::FromRequestParts;
use axum::http::header;
use axum::http::request::Parts;
use std::marker::PhantomData;
fn extract_token_from_parts(parts: &Parts, config: &GarrisonConfig) -> Option<String> {
if config.is_read_header {
if let Some(token) = extract_header_token(parts, config) {
return Some(token);
}
}
if config.is_read_cookie {
if let Some(token) = extract_cookie_token(parts, config) {
return Some(token);
}
}
None
}
fn extract_header_token(parts: &Parts, config: &GarrisonConfig) -> Option<String> {
if let Some(auth) = parts.headers.get(header::AUTHORIZATION) {
if let Some(token) = auth.to_str().ok().and_then(strip_bearer_prefix) {
return Some(token.to_string());
}
}
parts
.headers
.get(config.token_name.as_str())
.and_then(|token| token.to_str().ok())
.map(str::to_string)
}
fn extract_cookie_token(parts: &Parts, config: &GarrisonConfig) -> Option<String> {
let cookie_str = parts.headers.get(header::COOKIE)?.to_str().ok()?;
let cookie_prefix = format!("{}=", crate::context::token_cookie_name(config));
cookie_str
.split(';')
.map(str::trim)
.find_map(|c| c.strip_prefix(&cookie_prefix).map(str::to_string))
}
async fn enforce_login() -> Result<(), GarrisonError> {
let logged_in = GarrisonUtil::check_login().await?;
if !logged_in {
return Err(GarrisonError::NotLogin(
"annotation-not-login::".to_string(),
));
}
Ok(())
}
pub struct CheckLogin;
impl<S: Send + Sync> FromRequestParts<S> for CheckLogin {
type Rejection = GarrisonError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let config = GarrisonUtil::config()?;
if let Some(t) = extract_token_from_parts(parts, &config) {
with_current_token(t, enforce_login()).await?;
} else {
enforce_login().await?;
}
Ok(CheckLogin)
}
}
pub struct CheckRole<R: RoleName>(PhantomData<R>);
impl<R: RoleName, S: Send + Sync> FromRequestParts<S> for CheckRole<R> {
type Rejection = GarrisonError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let config = GarrisonUtil::config()?;
if let Some(t) = extract_token_from_parts(parts, &config) {
with_current_token(t, async {
GarrisonUtil::check_role(R::NAME).await?;
Ok::<(), GarrisonError>(())
})
.await?;
} else {
GarrisonUtil::check_role(R::NAME).await?;
}
Ok(CheckRole(PhantomData))
}
}
pub struct CheckPermission<P: PermissionName>(PhantomData<P>);
impl<P: PermissionName, S: Send + Sync> FromRequestParts<S> for CheckPermission<P> {
type Rejection = GarrisonError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let config = GarrisonUtil::config()?;
if let Some(t) = extract_token_from_parts(parts, &config) {
with_current_token(t, async {
GarrisonUtil::check_permission(P::NAME).await?;
Ok::<(), GarrisonError>(())
})
.await?;
} else {
GarrisonUtil::check_permission(P::NAME).await?;
}
Ok(CheckPermission(PhantomData))
}
}
pub struct Ignore;
impl<S: Send + Sync> FromRequestParts<S> for Ignore {
type Rejection = GarrisonError;
async fn from_request_parts(_parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
Ok(Ignore)
}
}
pub struct Mode<M: ModeSpec>(PhantomData<M>);
async fn enforce_mode<M: ModeSpec>() -> Result<(), GarrisonError> {
if M::STRICT {
enforce_login().await
} else {
let _ = GarrisonUtil::check_login().await;
Ok(())
}
}
impl<M: ModeSpec, S: Send + Sync> FromRequestParts<S> for Mode<M> {
type Rejection = GarrisonError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let config = GarrisonUtil::config()?;
if let Some(t) = extract_token_from_parts(parts, &config) {
with_current_token(t, enforce_mode::<M>()).await?;
} else {
enforce_mode::<M>().await?;
}
Ok(Mode(PhantomData))
}
}
impl<S: Send + Sync> FromRequestParts<S> for crate::context::GarrisonPrincipal {
type Rejection = GarrisonError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let config = GarrisonUtil::config()?;
let token = extract_token_from_parts(parts, &config)
.ok_or_else(|| GarrisonError::NotLogin("annotation-no-token::".to_string()))?;
let login_id = GarrisonUtil::get_login_id_by_token(&token)
.await?
.ok_or_else(|| GarrisonError::NotLogin("annotation-token-invalid::".to_string()))?;
Ok(crate::context::GarrisonPrincipal { login_id })
}
}
#[cfg(feature = "tenant-isolation")]
impl<S: Send + Sync> FromRequestParts<S> for crate::context::tenant::TenantContext {
type Rejection = GarrisonError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let raw = parts
.headers
.get("x-tenant-id")
.and_then(|v| v.to_str().ok())
.ok_or_else(|| GarrisonError::Config("ctx-tenant-id-missing::".into()))?;
let tenant_id: i64 = raw
.parse()
.map_err(|_| GarrisonError::Config(format!("annotation-tenant-id-invalid::{}", raw)))?;
Ok(crate::context::tenant::TenantContext {
tenant_id,
resolved_from: crate::context::tenant::TenantSource::Header,
})
}
}