summaryrefslogtreecommitdiff
path: root/src/auth.rs
blob: 864efe0731fe4065f2105312ffc85b217e405b80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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())
    }
}