HomeDisk/server/src/auth/whoami.rs

38 lines
1.1 KiB
Rust
Raw Normal View History

use axum::{Extension, Json};
use axum_auth::AuthBearer;
use homedisk_database::{Database, Error};
use homedisk_types::{
auth::whoami::Response,
2022-06-08 19:16:12 +00:00
config::Config,
errors::{AuthError, ServerError},
};
use crate::middleware::validate_jwt;
2022-06-08 17:08:06 +00:00
/// Handle `/auth/whoami` requests
pub async fn handle(
db: Extension<Database>,
config: Extension<Config>,
AuthBearer(token): AuthBearer,
) -> Result<Json<Response>, ServerError> {
2022-06-07 20:36:26 +00:00
// validate user token
let token = validate_jwt(config.jwt.secret.as_bytes(), &token)?;
2022-06-08 19:16:12 +00:00
// search for a user in database
let response = match db.find_user_by_id(token.claims.sub).await {
Ok(res) => Response {
username: res.username,
},
2022-06-11 08:19:47 +00:00
// error while searching for a user
Err(err) => match err {
2022-06-11 08:19:47 +00:00
// user not found
Error::UserNotFound => return Err(ServerError::AuthError(AuthError::UserNotFound)),
2022-06-11 08:19:47 +00:00
// other error
_ => return Err(ServerError::AuthError(AuthError::Other(err.to_string()))),
},
};
Ok(Json(response))
}