fastauth_plugin_organization/actix.rs
1//! actix-web extractors for organization membership and permissions (feature `actix`).
2//!
3//! The extractor types are the ones in [`crate::extract`]: `OrgMember`, `ActiveMember`
4//! and `RequirePermission`, with [`Active`] or [`FromPath`] naming the organization. This
5//! module adds their actix-web side, [`OrgSource`].
6//!
7//! ```
8//! use actix_web::{App, web};
9//! use fastauth_actix::AuthScope;
10//! use fastauth_core::prelude::*;
11//! use fastauth_plugin_organization::extract::{ActiveMember, FromPath, OrgMember, RequirePermission};
12//! use fastauth_plugin_organization::{Organization, access::MemberDelete, path_param};
13//!
14//! type AppAuth = Auth<MemoryAdapter, (), plugins![Organization]>;
15//!
16//! path_param!(pub OrgId = "org_id");
17//!
18//! // The session's active organization; 403 without one or without a membership.
19//! async fn dashboard(member: ActiveMember<AppAuth>) -> String {
20//! member.role.clone()
21//! }
22//!
23//! // `/orgs/{org_id}/...`: the membership in the organization the path names.
24//! async fn org_page(member: OrgMember<AppAuth, FromPath<OrgId>>) -> String {
25//! member.organization_id.to_string()
26//! }
27//!
28//! // 403 unless the member's role grants `member: [delete]`.
29//! async fn remove(member: RequirePermission<AppAuth, MemberDelete>) -> String {
30//! member.user_id.to_string()
31//! }
32//!
33//! fn routes(config: &mut web::ServiceConfig) {
34//! config
35//! .route("/dashboard", web::get().to(dashboard))
36//! .route("/orgs/{org_id}", web::get().to(org_page))
37//! .route("/members", web::delete().to(remove));
38//! }
39//! ```
40//!
41//! The extractors find the auth instance in app data, like `fastauth_actix::Session`, and
42//! share that request's single session lookup.
43
44use std::future::Future;
45use std::pin::Pin;
46
47use actix_web::dev::Payload;
48use actix_web::{FromRequest, HttpRequest};
49use fastauth_actix::Session;
50use fastauth_core::value::Id;
51use fastauth_core::{AuthError, AuthInstance};
52
53use crate::Permission;
54use crate::extract::{Active, FromPath, OrgMember, PathParam, RequirePermission, membership};
55use crate::model::Member;
56
57type LocalBoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
58
59/// Where an actix-web extractor finds the organization. axum's counterpart is
60/// [`crate::extract::OrgSource`].
61pub trait OrgSource: 'static {
62 /// The organization id, or `None` for the session's active organization.
63 fn organization_id(request: &HttpRequest) -> Result<Option<Id>, AuthError>;
64}
65
66impl OrgSource for Active {
67 fn organization_id(_request: &HttpRequest) -> Result<Option<Id>, AuthError> {
68 Ok(None)
69 }
70}
71
72/// The organization id in the path segment `P::NAME`. A route without that segment is a
73/// programming error and answers 500.
74impl<P: PathParam> OrgSource for FromPath<P> {
75 fn organization_id(request: &HttpRequest) -> Result<Option<Id>, AuthError> {
76 request
77 .match_info()
78 .get(P::NAME)
79 .map(|value| Some(Id::from(value)))
80 .ok_or_else(|| {
81 AuthError::internal(format!("the route has no `{{{}}}` segment", P::NAME))
82 })
83 }
84}
85
86async fn resolve<A: AuthInstance, S: OrgSource>(
87 request: HttpRequest,
88 permission: Option<(&'static str, &'static [&'static str])>,
89) -> Result<Member, AuthError> {
90 let session = Session::<A>::extract(&request).await?;
91 let organization_id = S::organization_id(&request)?;
92 let auth = fastauth_actix::auth::<A>(&request)?;
93 membership(&auth, &session, organization_id, permission).await
94}
95
96impl<A: AuthInstance, S: OrgSource> FromRequest for OrgMember<A, S> {
97 type Error = AuthError;
98 type Future = LocalBoxFuture<Result<Self, AuthError>>;
99
100 fn from_request(request: &HttpRequest, _: &mut Payload) -> Self::Future {
101 let request = request.clone();
102 Box::pin(async move { Ok(Self::new(resolve::<A, S>(request, None).await?)) })
103 }
104}
105
106impl<A: AuthInstance, P: Permission, S: OrgSource> FromRequest for RequirePermission<A, P, S> {
107 type Error = AuthError;
108 type Future = LocalBoxFuture<Result<Self, AuthError>>;
109
110 fn from_request(request: &HttpRequest, _: &mut Payload) -> Self::Future {
111 let request = request.clone();
112 Box::pin(async move {
113 Ok(Self::new(
114 resolve::<A, S>(request, Some((P::RESOURCE, P::ACTIONS))).await?,
115 ))
116 })
117 }
118}