Skip to main content

aurelin_framework/authorization/
http.rs

1use std::{
2    any::Any,
3    marker::PhantomData,
4    mem,
5    pin::Pin,
6    task::{Context as TaskContext, Poll},
7};
8
9use axum::{
10    body::Body,
11    http::{Request, StatusCode},
12    response::{IntoResponse, Response},
13};
14use axum_login::{AuthSession, AuthnBackend};
15use tower::{Layer, Service};
16
17use super::Gate;
18
19/// A route layer that authorizes an ability using the current `axum-login` session.
20pub struct AuthorizeLayer<Backend, Context = ()>
21where
22    Backend: AuthnBackend,
23{
24    gate: Gate<Backend::User>,
25    ability: String,
26    context: Context,
27    backend: PhantomData<fn() -> Backend>,
28}
29
30impl<Backend> AuthorizeLayer<Backend>
31where
32    Backend: AuthnBackend,
33{
34    /// Authorize a resource-free ability before the route handler runs.
35    pub fn new(gate: Gate<Backend::User>, ability: impl Into<String>) -> Self {
36        Self { gate, ability: ability.into(), context: (), backend: PhantomData }
37    }
38}
39
40impl<Backend, Context> AuthorizeLayer<Backend, Context>
41where
42    Backend: AuthnBackend,
43{
44    /// Authorize an ability against fixed route context.
45    pub fn with_context(gate: Gate<Backend::User>, ability: impl Into<String>, context: Context) -> Self {
46        Self { gate, ability: ability.into(), context, backend: PhantomData }
47    }
48}
49
50impl<Backend, Context> Clone for AuthorizeLayer<Backend, Context>
51where
52    Backend: AuthnBackend,
53    Context: Clone,
54{
55    fn clone(&self) -> Self {
56        Self {
57            gate: self.gate.clone(),
58            ability: self.ability.clone(),
59            context: self.context.clone(),
60            backend: PhantomData,
61        }
62    }
63}
64
65impl<S, Backend, Context> Layer<S> for AuthorizeLayer<Backend, Context>
66where
67    Backend: AuthnBackend,
68    Context: Clone,
69{
70    type Service = AuthorizeService<S, Backend, Context>;
71
72    fn layer(&self, inner: S) -> Self::Service {
73        AuthorizeService {
74            inner,
75            gate: self.gate.clone(),
76            ability: self.ability.clone(),
77            context: self.context.clone(),
78            backend: PhantomData,
79        }
80    }
81}
82
83/// Service produced by [`AuthorizeLayer`].
84pub struct AuthorizeService<S, Backend, Context>
85where
86    Backend: AuthnBackend,
87{
88    inner: S,
89    gate: Gate<Backend::User>,
90    ability: String,
91    context: Context,
92    backend: PhantomData<fn() -> Backend>,
93}
94
95impl<S, Backend, Context> Clone for AuthorizeService<S, Backend, Context>
96where
97    S: Clone,
98    Backend: AuthnBackend,
99    Context: Clone,
100{
101    fn clone(&self) -> Self {
102        Self {
103            inner: self.inner.clone(),
104            gate: self.gate.clone(),
105            ability: self.ability.clone(),
106            context: self.context.clone(),
107            backend: PhantomData,
108        }
109    }
110}
111
112impl<S, Backend, Context> Service<Request<Body>> for AuthorizeService<S, Backend, Context>
113where
114    S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
115    S::Future: Send + 'static,
116    S::Error: Send + 'static,
117    Backend: AuthnBackend + Send + Sync + 'static,
118    Backend::User: Clone + Send + Sync + 'static,
119    Context: Any + Clone + Send + Sync + 'static,
120{
121    type Response = Response;
122    type Error = S::Error;
123    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
124
125    fn poll_ready(&mut self, context: &mut TaskContext<'_>) -> Poll<Result<(), Self::Error>> {
126        self.inner.poll_ready(context)
127    }
128
129    fn call(&mut self, request: Request<Body>) -> Self::Future {
130        let replacement = self.inner.clone();
131        let mut inner = mem::replace(&mut self.inner, replacement);
132        let gate = self.gate.clone();
133        let ability = self.ability.clone();
134        let context = self.context.clone();
135        let Some(session) = request.extensions().get::<AuthSession<Backend>>() else {
136            tracing::error!("authorization route is missing the axum-login session layer");
137            return Box::pin(async move {
138                Ok((StatusCode::INTERNAL_SERVER_ERROR, "Internal server error").into_response())
139            });
140        };
141        let user = session.user.clone();
142
143        Box::pin(async move {
144            match gate.for_user(user.as_ref()).authorize(ability, &context).await {
145                Ok(_) => inner.call(request).await,
146                Err(error) => Ok(error.into_response()),
147            }
148        })
149    }
150}