use std::fmt::Debug;
use axum_session_auth::Authentication;
use crate::session::AuthSession;
pub trait AccountAuthorizer {
type Role;
type Error;
fn unauthenticated_error() -> Self::Error;
fn authorize(&self, required_role: Self::Role) -> Result<(), Self::Error>;
}
pub trait AccountSession {
type Account: AccountAuthorizer;
fn authorize(
&self,
required_role: <Self::Account as AccountAuthorizer>::Role,
) -> Result<&Self::Account, <Self::Account as AccountAuthorizer>::Error>;
}
impl<User, Database> AccountSession for AuthSession<User, Database>
where
Database: Clone + Debug + Send + Sync + 'static,
User: AccountAuthorizer + Authentication<User, String, Database> + Send,
{
type Account = User;
fn authorize(
&self,
required_role: <Self::Account as AccountAuthorizer>::Role,
) -> Result<&Self::Account, <Self::Account as AccountAuthorizer>::Error> {
let account = self
.current_user
.as_ref()
.ok_or_else(User::unauthenticated_error)?;
account.authorize(required_role)?;
Ok(account)
}
}