64 lines
1.5 KiB
Rust
64 lines
1.5 KiB
Rust
use crate::controllers::auth::AuthController;
|
|
use crate::utils::{models::*, DbPool};
|
|
use axum::{
|
|
extract::FromRequestParts,
|
|
http::{header::AUTHORIZATION, request::Parts, StatusCode},
|
|
};
|
|
|
|
#[derive(Clone)]
|
|
pub struct AuthUser {
|
|
pub user: User,
|
|
}
|
|
|
|
impl FromRequestParts<DbPool> for AuthUser {
|
|
type Rejection = StatusCode;
|
|
|
|
async fn from_request_parts(
|
|
parts: &mut Parts,
|
|
state: &DbPool,
|
|
) -> Result<Self, Self::Rejection> {
|
|
let auth_header = parts
|
|
.headers
|
|
.get(AUTHORIZATION)
|
|
.and_then(|header| header.to_str().ok())
|
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
|
|
|
if !auth_header.starts_with("Bearer ") {
|
|
return Err(StatusCode::UNAUTHORIZED);
|
|
}
|
|
|
|
let token = &auth_header[7..];
|
|
|
|
let user = AuthController::authenticate_user(state, token)
|
|
.await
|
|
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
|
|
|
Ok(AuthUser { user })
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct AdminUser {
|
|
#[allow(dead_code)]
|
|
pub user: User,
|
|
}
|
|
|
|
impl FromRequestParts<DbPool> for AdminUser {
|
|
type Rejection = StatusCode;
|
|
|
|
async fn from_request_parts(
|
|
parts: &mut Parts,
|
|
state: &DbPool,
|
|
) -> Result<Self, Self::Rejection> {
|
|
let auth_user = AuthUser::from_request_parts(parts, state).await?;
|
|
|
|
if auth_user.user.role != UserRole::Admin {
|
|
return Err(StatusCode::FORBIDDEN);
|
|
}
|
|
|
|
Ok(AdminUser {
|
|
user: auth_user.user,
|
|
})
|
|
}
|
|
}
|