beyondigital_auth_axum/
lib.rs1use std::sync::Arc;
5
6use axum::{
7 extract::{FromRequestParts, Request},
8 http::{request::Parts, StatusCode},
9 middleware::Next,
10 response::{IntoResponse, Response},
11 Json,
12};
13use beyondigital_auth_sdk::{AuthError, Verifier};
14use serde_json::json;
15
16#[derive(Clone)]
17pub struct AuthState {
18 pub verifier: Arc<Verifier>,
19 pub public_paths: Vec<String>,
20}
21
22impl AuthState {
23 pub fn new(verifier: Verifier) -> Self {
24 Self {
25 verifier: Arc::new(verifier),
26 public_paths: vec!["/health".to_string()],
27 }
28 }
29 pub fn with_public_paths(mut self, paths: Vec<String>) -> Self {
30 self.public_paths = paths;
31 self
32 }
33}
34
35fn is_public(path: &str, public_paths: &[String]) -> bool {
36 for p in public_paths {
37 if p.ends_with('*') {
38 if path.starts_with(&p[..p.len() - 1]) {
39 return true;
40 }
41 } else if path == p || path.trim_end_matches('/') == p.trim_end_matches('/') {
42 return true;
43 }
44 }
45 false
46}
47
48pub async fn auth_middleware(state: AuthState, mut req: Request, next: Next) -> Response {
50 let path = req.uri().path().to_string();
51 let token = req
52 .headers()
53 .get("authorization")
54 .and_then(|v| v.to_str().ok())
55 .and_then(|h| h.strip_prefix("Bearer "))
56 .map(str::to_string);
57
58 if is_public(&path, &state.public_paths) {
59 if let Some(t) = token {
60 if let Ok(user) = state.verifier.verify(&t).await {
61 req.extensions_mut().insert(Arc::new(user));
62 }
63 }
64 return next.run(req).await;
65 }
66
67 let Some(t) = token else {
68 return (
69 StatusCode::UNAUTHORIZED,
70 [(
71 axum::http::header::WWW_AUTHENTICATE,
72 "Bearer error=\"invalid_request\"",
73 )],
74 Json(json!({"detail":"Missing or invalid authorization header"})),
75 )
76 .into_response();
77 };
78 match state.verifier.verify(&t).await {
79 Ok(user) => {
80 req.extensions_mut().insert(Arc::new(user));
81 next.run(req).await
82 }
83 Err(e) => {
84 let msg = match e {
85 AuthError::Jwt { message, .. } => message,
86 _ => "Invalid or expired token".to_string(),
87 };
88 (
89 StatusCode::UNAUTHORIZED,
90 [(
91 axum::http::header::WWW_AUTHENTICATE,
92 format!("Bearer error=\"invalid_token\", error_description=\"{msg}\""),
93 )],
94 Json(json!({"detail":"Invalid or expired token"})),
95 )
96 .into_response()
97 }
98 }
99}
100
101pub struct AuthUser(pub Arc<beyondigital_auth_sdk::CurrentUser>);
103
104impl<S> FromRequestParts<S> for AuthUser
105where
106 S: Send + Sync,
107{
108 type Rejection = Response;
109 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
110 let user = parts
111 .extensions
112 .get::<Arc<beyondigital_auth_sdk::CurrentUser>>()
113 .cloned();
114 match user {
115 Some(u) => Ok(AuthUser(u)),
116 None => Err((
117 StatusCode::UNAUTHORIZED,
118 Json(json!({"detail":"Not authenticated"})),
119 )
120 .into_response()),
121 }
122 }
123}
124
125pub struct AdminUser(pub Arc<beyondigital_auth_sdk::CurrentUser>);
127
128impl<S> FromRequestParts<S> for AdminUser
129where
130 S: Send + Sync,
131{
132 type Rejection = Response;
133 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
134 let AuthUser(user) = AuthUser::from_request_parts(parts, state).await?;
135 if !user.is_admin() {
136 return Err((
137 StatusCode::FORBIDDEN,
138 Json(json!({"detail":"admin:* scope required"})),
139 )
140 .into_response());
141 }
142 Ok(AdminUser(user))
143 }
144}