diff options
| author | Dawid Rycerz <dawid@rycerz.xyz> | 2025-07-14 20:35:00 +0300 |
|---|---|---|
| committer | Dawid Rycerz <dawid@rycerz.xyz> | 2025-07-14 20:35:00 +0300 |
| commit | 1c2873b3059f3e4d6bd02307ec5b22f761ce1c80 (patch) | |
| tree | de196a57b76fcacbbc842bbb5bf2641c8f82be91 /src/auth.rs | |
| parent | 50ce8cb96b2b218751c2fc2a6b19372f51846acc (diff) | |
feat: Update routes and fix issues
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()) + } +} |
