HomeDisk/server/src/auth/whoami.rs

38 lines
1.0 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;
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
2022-06-14 20:37:42 +00:00
let response = match db.find_user_by_id(&token.claims.sub).await {
2022-07-25 21:02:25 +00:00
Ok(user) => Response {
username: user.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()))),
},
};
2022-07-25 21:02:25 +00:00
// send response
Ok(Json(response))
}