diff options
Diffstat (limited to 'src/auth.rs')
| -rw-r--r-- | src/auth.rs | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..864efe0 --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,33 @@ +use crate::users::{User, UserRepository}; +use axum::extract::FromRef; +use axum::extract::FromRequestParts; +use axum::http::StatusCode; +use axum::http::request::Parts; +use axum::response::{IntoResponse, Response}; +use sqlx::SqlitePool; +use std::sync::Arc; + +pub struct AuthUser(pub User); + +impl<S> FromRequestParts<S> for AuthUser +where + Arc<SqlitePool>: axum::extract::FromRef<S>, + S: Send + Sync, +{ + type Rejection = Response; + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { + let pool = Arc::<SqlitePool>::from_ref(state); + let auth_header = parts + .headers + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.strip_prefix("Bearer ")); + if let Some(user_id) = auth_header { + let repo = UserRepository { db: &pool }; + if let Ok(Some(user)) = repo.get_user_by_user_id(user_id).await { + return Ok(AuthUser(user)); + } + } + Err((StatusCode::UNAUTHORIZED, "Unauthorized").into_response()) + } +} |
