Create utility functions

This commit is contained in:
2025-09-08 21:17:03 +02:00
parent f31d10b6e1
commit f03a6935d5
6 changed files with 545 additions and 0 deletions

70
server/src/utils/auth.rs Normal file
View File

@@ -0,0 +1,70 @@
use crate::controllers::auth::AuthController;
use crate::utils::{models::*, DbPool};
use axum::{
async_trait,
extract::FromRequestParts,
http::{header::AUTHORIZATION, request::Parts, StatusCode},
};
#[derive(Clone)]
pub struct AuthUser {
pub user: User,
}
#[async_trait]
impl<S> FromRequestParts<S> for AuthUser
where
S: Send + Sync,
{
type Rejection = StatusCode;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> 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 pool = parts
.extensions
.get::<DbPool>()
.ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
let user = AuthController::authenticate_user(pool, token)
.await
.map_err(|_| StatusCode::UNAUTHORIZED)?;
Ok(AuthUser { user })
}
}
#[derive(Clone)]
pub struct AdminUser {
#[allow(dead_code)]
pub user: User,
}
#[async_trait]
impl<S> FromRequestParts<S> for AdminUser
where
S: Send + Sync,
{
type Rejection = StatusCode;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> 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,
})
}
}