74 lines
1.9 KiB
Rust
74 lines
1.9 KiB
Rust
use axum::{extract::FromRequestParts, http::request::Parts};
|
|
use std::result;
|
|
use tower_sessions::{Session, session::Error};
|
|
use uuid::Uuid;
|
|
|
|
use crate::authentication::Role;
|
|
|
|
pub struct TypedSession(Session);
|
|
|
|
type Result<T> = result::Result<T, Error>;
|
|
|
|
impl TypedSession {
|
|
const USER_ID_KEY: &'static str = "user_id";
|
|
const USERNAME_KEY: &'static str = "username";
|
|
const ROLE_KEY: &'static str = "role";
|
|
|
|
pub async fn renew(&self) -> Result<()> {
|
|
self.0.cycle_id().await
|
|
}
|
|
|
|
pub async fn insert_user_id(&self, user_id: Uuid) -> Result<()> {
|
|
self.0.insert(Self::USER_ID_KEY, user_id).await
|
|
}
|
|
|
|
pub async fn get_user_id(&self) -> Result<Option<Uuid>> {
|
|
self.0.get(Self::USER_ID_KEY).await
|
|
}
|
|
|
|
pub async fn insert_username(&self, username: String) -> Result<()> {
|
|
self.0.insert(Self::USERNAME_KEY, username).await
|
|
}
|
|
|
|
pub async fn get_username(&self) -> Result<Option<String>> {
|
|
self.0.get(Self::USERNAME_KEY).await
|
|
}
|
|
|
|
pub async fn insert_role(&self, role: Role) -> Result<()> {
|
|
self.0.insert(Self::ROLE_KEY, role).await
|
|
}
|
|
|
|
pub async fn get_role(&self) -> Result<Option<Role>> {
|
|
self.0.get(Self::ROLE_KEY).await
|
|
}
|
|
|
|
pub async fn has_admin_permissions(&self) -> Result<bool> {
|
|
let role = self.0.get(Self::ROLE_KEY).await?;
|
|
if let Some(Role::Admin) = role {
|
|
Ok(true)
|
|
} else {
|
|
Ok(false)
|
|
}
|
|
}
|
|
|
|
pub async fn clear(&self) {
|
|
self.0.clear().await;
|
|
}
|
|
}
|
|
|
|
impl<S> FromRequestParts<S> for TypedSession
|
|
where
|
|
S: Sync + Send,
|
|
{
|
|
type Rejection = <Session as FromRequestParts<S>>::Rejection;
|
|
|
|
async fn from_request_parts(
|
|
parts: &mut Parts,
|
|
state: &S,
|
|
) -> result::Result<Self, Self::Rejection> {
|
|
Session::from_request_parts(parts, state)
|
|
.await
|
|
.map(TypedSession)
|
|
}
|
|
}
|