Skip to main content

fastauth_plugin_admin/
actix.rs

1//! `RequireRole<A, R>` for actix-web (feature `actix`): lets a route through only for a role.
2//!
3//! ```
4//! use actix_web::web;
5//! use fastauth_core::prelude::*;
6//! use fastauth_plugin_admin::actix::RequireRole;
7//! use fastauth_plugin_admin::{Admin, role};
8//!
9//! type AppAuth = Auth<MemoryAdapter, (), plugins![Admin]>;
10//!
11//! role!(pub Support = "support");
12//!
13//! async fn dashboard(admin: RequireRole<AppAuth, role::Admin>) -> String {
14//!     format!("hello {}", admin.user.email)
15//! }
16//!
17//! async fn tickets(agent: RequireRole<AppAuth, Support>) -> String {
18//!     agent.user.name.clone()
19//! }
20//!
21//! fn routes(config: &mut web::ServiceConfig) {
22//!     config
23//!         .route("/admin", web::get().to(dashboard))
24//!         .route("/tickets", web::get().to(tickets));
25//! }
26//! ```
27
28use std::future::Future;
29use std::marker::PhantomData;
30use std::ops::Deref;
31use std::pin::Pin;
32
33use actix_web::dev::Payload;
34use actix_web::{FromRequest, HttpRequest};
35use fastauth_actix::Session;
36use fastauth_core::{AuthError, AuthInstance};
37
38use crate::Role;
39
40/// The signed-in session of a user who holds role `R`. Rejects with `401 UNAUTHORIZED`
41/// without a session and `403 FORBIDDEN` without the role, like the axum `RequireRole`.
42/// Derefs to the [`Session`].
43pub struct RequireRole<A: AuthInstance, R>(Session<A>, PhantomData<fn() -> R>);
44
45impl<A: AuthInstance, R> RequireRole<A, R> {
46    /// The session.
47    pub fn into_session(self) -> Session<A> {
48        self.0
49    }
50}
51
52impl<A: AuthInstance, R> Clone for RequireRole<A, R> {
53    fn clone(&self) -> Self {
54        Self(self.0.clone(), PhantomData)
55    }
56}
57
58impl<A: AuthInstance, R> Deref for RequireRole<A, R> {
59    type Target = Session<A>;
60
61    fn deref(&self) -> &Session<A> {
62        &self.0
63    }
64}
65
66impl<A: AuthInstance, R: Role> FromRequest for RequireRole<A, R> {
67    type Error = AuthError;
68    type Future = Pin<Box<dyn Future<Output = Result<Self, AuthError>>>>;
69
70    fn from_request(request: &HttpRequest, _: &mut Payload) -> Self::Future {
71        let request = request.clone();
72        Box::pin(async move {
73            let session = Session::<A>::extract(&request).await?;
74            crate::roles::require::<R, A>(&fastauth_actix::auth::<A>(&request)?, &session)?;
75            Ok(Self(session, PhantomData))
76        })
77    }
78}