2024-10-03 15:55:38 -04:00
|
|
|
use axum::{
|
|
|
|
debug_handler,
|
2024-10-05 08:09:46 -04:00
|
|
|
extract::State,
|
2024-10-03 15:55:38 -04:00
|
|
|
response::{IntoResponse, Response},
|
2024-10-05 08:09:46 -04:00
|
|
|
Json,
|
2024-10-03 15:55:38 -04:00
|
|
|
};
|
2024-10-06 07:14:44 -04:00
|
|
|
use http::StatusCode;
|
|
|
|
use pasetors::{keys::SymmetricKey, version4::V4};
|
2024-10-05 08:09:46 -04:00
|
|
|
use tracing::debug;
|
2024-10-03 15:55:38 -04:00
|
|
|
|
2024-10-05 08:09:46 -04:00
|
|
|
use crate::{
|
2024-10-06 07:14:44 -04:00
|
|
|
db::{get_username_and_password_by_username, DbPool, UserAndHashedPassword},
|
|
|
|
models::{ApiResponse, AppError},
|
|
|
|
requests::{
|
|
|
|
auth::login::models::{AuthLoginResponse, AuthLoginTokenData},
|
|
|
|
AppState,
|
|
|
|
},
|
|
|
|
services::{
|
|
|
|
auth_token::{generate_access_token, generate_auth_token},
|
|
|
|
verify_password,
|
|
|
|
},
|
2024-10-05 08:09:46 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
use super::models::AuthLoginRequest;
|
2024-10-03 15:55:38 -04:00
|
|
|
|
|
|
|
#[debug_handler]
|
2024-10-05 08:09:46 -04:00
|
|
|
pub async fn auth_login_post_handler(
|
|
|
|
State(state): State<AppState>,
|
|
|
|
Json(body): Json<AuthLoginRequest>,
|
|
|
|
) -> Result<Response, AppError> {
|
|
|
|
let pool = state.db_pool();
|
2024-10-06 07:14:44 -04:00
|
|
|
let token_key = state.env().token_key();
|
|
|
|
auth_login_request(pool, token_key, body).await
|
2024-10-05 08:09:46 -04:00
|
|
|
}
|
|
|
|
|
2024-10-06 07:14:44 -04:00
|
|
|
async fn auth_login_request(
|
|
|
|
pool: &DbPool,
|
|
|
|
token_key: &SymmetricKey<V4>,
|
|
|
|
body: AuthLoginRequest,
|
|
|
|
) -> Result<Response, AppError> {
|
2024-10-05 08:09:46 -04:00
|
|
|
debug!(?body);
|
|
|
|
|
|
|
|
let AuthLoginRequest { username, password } = body;
|
2024-10-06 07:14:44 -04:00
|
|
|
let UserAndHashedPassword {
|
|
|
|
id: user_id,
|
|
|
|
username,
|
|
|
|
name,
|
2024-10-05 08:09:46 -04:00
|
|
|
password: hashed_password,
|
|
|
|
} = get_username_and_password_by_username(pool, username).await?;
|
|
|
|
|
|
|
|
verify_password(password, hashed_password)?;
|
|
|
|
|
2024-10-06 07:14:44 -04:00
|
|
|
let (access_token, _access_token_id, access_token_expiration) =
|
|
|
|
generate_access_token(token_key, user_id);
|
|
|
|
|
|
|
|
let (auth_token, _auth_token_id, auth_token_expiration) =
|
|
|
|
generate_auth_token(token_key, user_id);
|
|
|
|
|
|
|
|
let response = AuthLoginResponse {
|
|
|
|
user_id,
|
|
|
|
username,
|
|
|
|
name,
|
|
|
|
access: AuthLoginTokenData {
|
|
|
|
token: access_token,
|
|
|
|
expiration: access_token_expiration,
|
|
|
|
},
|
|
|
|
auth: AuthLoginTokenData {
|
|
|
|
token: auth_token,
|
|
|
|
expiration: auth_token_expiration,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok((
|
|
|
|
StatusCode::OK,
|
|
|
|
ApiResponse::new(response).into_json_response(),
|
|
|
|
)
|
|
|
|
.into_response())
|
2024-10-03 15:55:38 -04:00
|
|
|
}
|