use std::{fmt::Debug, hash::Hash};
use serde::{Serialize, de::DeserializeOwned};
use axum_session::DatabasePool;
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, Sessions, Identifier> AccountSession
for AuthSession<User, Database, Sessions, Identifier>
where
Database: Clone + Debug + Send + Sync + 'static,
Sessions: DatabasePool + Clone + Debug + Send + Sync + 'static,
User: AccountAuthorizer + Authentication<User, Identifier, Database> + Send,
Identifier: Eq + Default + Clone + Send + Sync + Hash + Serialize + DeserializeOwned + 'static,
{
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)
}
}