Skip to main content

ch_auth/
authorization.rs

1//! Typed account authorization for session-backed handlers.
2
3use std::{fmt::Debug, hash::Hash};
4
5use serde::{Serialize, de::DeserializeOwned};
6
7use axum_session::DatabasePool;
8use axum_session_auth::Authentication;
9
10use crate::session::AuthSession;
11
12/// Application-owned authorization policy for a loaded account.
13pub trait AccountAuthorizer {
14    /// Role or permission requirement understood by the application.
15    type Role;
16
17    /// Error returned by the application's API boundary.
18    type Error;
19
20    /// Creates the error used when no account is present in the session.
21    fn unauthenticated_error() -> Self::Error;
22
23    /// Verifies that this account satisfies the requested authorization role.
24    fn authorize(&self, required_role: Self::Role) -> Result<(), Self::Error>;
25}
26
27/// Session capability used by protected handlers.
28pub trait AccountSession {
29    /// Account loaded by the session.
30    type Account: AccountAuthorizer;
31
32    /// Returns the current account after applying its authorization policy.
33    fn authorize(
34        &self,
35        required_role: <Self::Account as AccountAuthorizer>::Role,
36    ) -> Result<&Self::Account, <Self::Account as AccountAuthorizer>::Error>;
37}
38
39impl<User, Database, Sessions, Identifier> AccountSession
40    for AuthSession<User, Database, Sessions, Identifier>
41where
42    Database: Clone + Debug + Send + Sync + 'static,
43    Sessions: DatabasePool + Clone + Debug + Send + Sync + 'static,
44    User: AccountAuthorizer + Authentication<User, Identifier, Database> + Send,
45    Identifier: Eq + Default + Clone + Send + Sync + Hash + Serialize + DeserializeOwned + 'static,
46{
47    type Account = User;
48
49    fn authorize(
50        &self,
51        required_role: <Self::Account as AccountAuthorizer>::Role,
52    ) -> Result<&Self::Account, <Self::Account as AccountAuthorizer>::Error> {
53        let account = self
54            .current_user
55            .as_ref()
56            .ok_or_else(User::unauthenticated_error)?;
57        account.authorize(required_role)?;
58        Ok(account)
59    }
60}