From 1c2873b3059f3e4d6bd02307ec5b22f761ce1c80 Mon Sep 17 00:00:00 2001 From: Dawid Rycerz Date: Mon, 14 Jul 2025 20:35:00 +0300 Subject: feat: Update routes and fix issues --- src/auth.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/auth.rs (limited to 'src/auth.rs') 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 FromRequestParts for AuthUser +where + Arc: axum::extract::FromRef, + S: Send + Sync, +{ + type Rejection = Response; + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + let pool = Arc::::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()) + } +} -- cgit v1.2.3