This commit is contained in:
2026-06-28 18:12:00 +02:00
parent 5152ec0f7e
commit 7a593fc204
27 changed files with 413 additions and 100 deletions
+68 -3
View File
@@ -6,11 +6,13 @@ use crate::http::error::HTTPError;
use crate::routes::user::mapper::user_model_to_user_response;
use axum::extract::State;
use axum::Json;
use axum_extra::extract::cookie::{Cookie, SameSite};
use axum_extra::extract::CookieJar;
use sea_orm::ActiveModelBehavior;
#[utoipa::path(
get,
path = "/auth/login",
post,
path = "/auth/bearer-login",
request_body = LoginRequest,
responses(
(status = 200, description = "Login successful", body = LoginResponse),
@@ -18,7 +20,7 @@ use sea_orm::ActiveModelBehavior;
),
tag = "Auth"
)]
pub async fn login_user_pw(
pub async fn login_bearer(
State(state): State<AppState>,
Json(payload): Json<LoginRequest>,
) -> Result<Json<LoginResponse>, HTTPError> {
@@ -41,6 +43,69 @@ pub async fn login_user_pw(
Ok(Json(LoginResponse { token }))
}
#[utoipa::path(
post,
path = "/auth/login",
request_body = LoginRequest,
responses(
(status = 200, description = "Login successful with cookie set", body = LoginResponse),
(status = 401, description = "Unauthorized")
),
tag = "Auth"
)]
pub async fn login_cookie(
State(state): State<AppState>,
jar: CookieJar,
Json(payload): Json<LoginRequest>,
) -> Result<(CookieJar, Json<LoginResponse>), HTTPError> {
let user = state
.repositories
.user
.check_password(&payload.username, &payload.password)
.await
.map_err(|_| HTTPError::Unauthorized)?;
let token = create_jwt(
user.id,
&user.username,
user.is_superuser,
&state.config.jwt.secret,
state.config.jwt.duration,
)
.map_err(|_| HTTPError::InternalServerError("Failed to create JWT token".to_string()))?;
// Création du cookie sécurisé contenant le token JWT
let cookie = Cookie::build(("token", token.clone()))
.path("/")
.http_only(true)
.same_site(SameSite::Lax)
.secure(false) // Mettez à true si vous forcez le HTTPS en production
.build();
let updated_jar = jar.add(cookie);
Ok((updated_jar, Json(LoginResponse { token })))
}
#[utoipa::path(
post,
path = "/auth/logout",
responses(
(status = 200, description = "Logout successful")
),
tag = "Auth"
)]
pub async fn logout_cookie(jar: CookieJar) -> Result<CookieJar, HTTPError> {
// On crée un cookie expiré en lui donnant une durée négative de 1 seconde (ou Duration::ZERO)
let cookie = Cookie::build(("token", ""))
.path("/")
.max_age(time::Duration::seconds(-1))
.build();
let updated_jar = jar.add(cookie);
Ok(updated_jar)
}
#[utoipa::path(
post,
path = "/auth/me",