Extract authentication into a wrapper function

This commit is contained in:
Savanni D'Gerinel 2024-12-31 14:16:44 -05:00
parent 822dfe2a13
commit 82e41d711b

View File

@ -74,6 +74,22 @@ pub async fn check_password(
} }
} }
pub async fn authenticated<F, A>(
core: Core,
headers: HeaderMap,
f: F,
) -> (StatusCode, Json<Option<A>>)
where
F: FnOnce(User) -> (StatusCode, Json<Option<A>>),
{
match check_session(&core, headers).await {
ResultExt::Ok(Some(user)) => f(user),
ResultExt::Ok(None) => (StatusCode::UNAUTHORIZED, Json(None)),
ResultExt::Err(_err) => (StatusCode::BAD_REQUEST, Json(None)),
ResultExt::Fatal(err) => panic!("{}", err),
}
}
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
#[typeshare] #[typeshare]
pub struct UserProfile { pub struct UserProfile {
@ -82,14 +98,16 @@ pub struct UserProfile {
} }
pub async fn get_user(core: Core, headers: HeaderMap) -> (StatusCode, Json<Option<UserProfile>>) { pub async fn get_user(core: Core, headers: HeaderMap) -> (StatusCode, Json<Option<UserProfile>>) {
match check_session(&core, headers).await { authenticated(core.clone(), headers, |user| {
ResultExt::Ok(Some(user)) => { (
(StatusCode::OK, Json(Some(UserProfile{userid: UserId::from(user.id), username: user.name} ))) StatusCode::OK,
} Json(Some(UserProfile {
ResultExt::Ok(None) => (StatusCode::UNAUTHORIZED, Json(None)), userid: UserId::from(user.id),
ResultExt::Err(_err) => (StatusCode::BAD_REQUEST, Json(None)), username: user.name,
ResultExt::Fatal(err) => panic!("{}", err), })),
} )
})
.await
} }
/* /*