76 lines
1.7 KiB
Rust
76 lines
1.7 KiB
Rust
use axum::{
|
|
extract::State,
|
|
http::StatusCode,
|
|
Json,
|
|
};
|
|
use axum_login::AuthSession;
|
|
use serde::{Deserialize, Serialize};
|
|
use utoipa::ToSchema;
|
|
|
|
use crate::auth::{AuthBackend, Credentials};
|
|
|
|
#[derive(Debug, Deserialize, ToSchema)]
|
|
pub struct LoginRequest {
|
|
pub username: String,
|
|
pub password: String,
|
|
}
|
|
|
|
#[derive(Debug, Serialize, ToSchema)]
|
|
pub struct LoginResponse {
|
|
pub success: bool,
|
|
pub is_admin: bool,
|
|
}
|
|
|
|
#[utoipa::path(
|
|
post,
|
|
path = "/login",
|
|
tag = "auth",
|
|
request_body = LoginRequest,
|
|
responses(
|
|
(status = 200, description = "Login successful", body = LoginResponse),
|
|
(status = 401, description = "Invalid credentials")
|
|
)
|
|
)]
|
|
pub async fn login(
|
|
mut auth_session: AuthSession<AuthBackend>,
|
|
Json(payload): Json<LoginRequest>,
|
|
) -> Result<Json<LoginResponse>, StatusCode> {
|
|
let user = auth_session
|
|
.authenticate(Credentials {
|
|
username: payload.username,
|
|
password: payload.password,
|
|
})
|
|
.await
|
|
.map_err(|_| StatusCode::UNAUTHORIZED)?
|
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
|
|
|
auth_session
|
|
.login(&user)
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
|
|
Ok(Json(LoginResponse {
|
|
success: true,
|
|
is_admin: user.is_admin,
|
|
}))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
post,
|
|
path = "/logout",
|
|
tag = "auth",
|
|
responses(
|
|
(status = 200, description = "Logout successful")
|
|
)
|
|
)]
|
|
pub async fn logout(
|
|
mut auth_session: AuthSession<AuthBackend>,
|
|
) -> Result<StatusCode, StatusCode> {
|
|
auth_session
|
|
.logout()
|
|
.await
|
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
|
|
|
Ok(StatusCode::OK)
|
|
}
|