Skip to main content

fastauth_plugin_organization/
lib.rs

1//! Organizations for [fastauth](https://github.com/lassejlv/fastauth): organizations, members,
2//! invitations, roles and permissions. The `/organization/*` routes, JSON and error codes
3//! match Better Auth's organization plugin, so its `organizationClient` works unchanged.
4//!
5//! ```
6//! use fastauth_core::prelude::*;
7//! use fastauth_plugin_organization::{Organization, OrganizationExt, Roles};
8//!
9//! let auth: Auth<MemoryAdapter, (), plugins![Organization]> = FastAuth::builder()
10//!     .secret(Secret::from_bytes(vec![1u8; 32]))
11//!     .base_url("http://localhost:3000")
12//!     .database(MemoryAdapter::new())
13//!     .email_password(EmailPassword::default())
14//!     .plugin(
15//!         Organization::default()
16//!             .organization_limit(5)
17//!             .invitation_ttl(Duration::days(7))
18//!             .roles(Roles::new().role("billing", [("invoice", &["read", "pay"])])),
19//!     )
20//!     .build()?;
21//! assert!(auth.organization().roles().allows("billing", &[("invoice", &["pay"])]));
22//! # Ok::<(), BuildError>(())
23//! ```
24//!
25//! The plugin adds the `organization`, `member` and `invitation` tables and an
26//! `active_organization_id` column on `session`. A creator becomes the organization's
27//! `owner`, and the last owner can neither leave nor be demoted. What each role may do is
28//! decided in one place, [`Roles::allows`], which the endpoints, the server API
29//! ([`OrganizationExt`]) and the axum extractors (feature `axum`) all call.
30//!
31//! Without the plugin registered, `auth.organization()` doesn't compile:
32//!
33//! ```compile_fail
34//! use fastauth_core::prelude::*;
35//! use fastauth_plugin_organization::OrganizationExt;
36//!
37//! let auth: Auth<MemoryAdapter> = FastAuth::builder()
38//!     .secret(Secret::from_bytes(vec![1u8; 32]))
39//!     .base_url("http://localhost:3000")
40//!     .database(MemoryAdapter::new())
41//!     .build()
42//!     .unwrap();
43//! let _ = auth.organization();
44//! ```
45
46pub mod access;
47mod api;
48mod endpoints;
49mod error;
50#[cfg(feature = "axum")]
51pub mod extract;
52mod model;
53
54use fastauth_core::config::CoreConfig;
55use fastauth_core::plugin_prelude::*;
56
57pub use access::{Permission, Roles};
58pub use api::{OrganizationApi, OrganizationExt};
59pub use endpoints::server::{
60    AddMember, CheckPermission, EmailQuery, NewMember, PermissionCheck, UserInvitations,
61};
62pub use endpoints::*;
63pub use error::OrganizationError;
64pub use model::{
65    Invitation, InvitationStatus, Member, MemberUser, MemberWithUser, OrganizationRow,
66    OrganizationSession,
67};
68
69/// The organization plugin: `.plugin(Organization::default())`.
70#[derive(Clone, Debug)]
71pub struct Organization {
72    pub(crate) roles: Roles,
73    pub(crate) allow_user_to_create_organization: bool,
74    pub(crate) organization_limit: Option<u64>,
75    pub(crate) invitation_ttl: Duration,
76    pub(crate) invitation_url: Option<String>,
77    pub(crate) require_email_verification_on_invitation: bool,
78}
79
80impl Default for Organization {
81    fn default() -> Self {
82        Self {
83            roles: Roles::new(),
84            allow_user_to_create_organization: true,
85            organization_limit: None,
86            invitation_ttl: Duration::hours(48),
87            invitation_url: None,
88            require_email_verification_on_invitation: false,
89        }
90    }
91}
92
93impl Organization {
94    /// The roles members can hold and what each may do. Default: [`Roles::new()`].
95    pub fn roles(mut self, roles: Roles) -> Self {
96        self.roles = roles;
97        self
98    }
99
100    /// Whether signed-in users may create organizations over HTTP (default `true`). The
101    /// server API's `create` works either way.
102    pub fn allow_user_to_create_organization(mut self, allow: bool) -> Self {
103        self.allow_user_to_create_organization = allow;
104        self
105    }
106
107    /// How many organizations one user may belong to before creating another is refused
108    /// (default: no limit).
109    pub fn organization_limit(mut self, limit: u64) -> Self {
110        self.organization_limit = Some(limit);
111        self
112    }
113
114    /// How long an invitation can be accepted (default 48 hours).
115    pub fn invitation_ttl(mut self, ttl: Duration) -> Self {
116        self.invitation_ttl = ttl;
117        self
118    }
119
120    /// The link invitation emails carry, with `{id}` replaced by the invitation id, e.g.
121    /// `"https://app.acme.dk/invite/{id}"`. Default: `{base_url}/accept-invitation/{id}`. The
122    /// page behind it calls `/organization/accept-invitation` with the id.
123    pub fn invitation_url(mut self, template: impl Into<String>) -> Self {
124        self.invitation_url = Some(template.into());
125        self
126    }
127
128    /// Only users with a verified email may view, accept or reject invitations (default
129    /// `false`). Invitation ids are unguessable, so possessing the link is the default proof.
130    pub fn require_email_verification_on_invitation(mut self, require: bool) -> Self {
131        self.require_email_verification_on_invitation = require;
132        self
133    }
134
135    pub(crate) fn invitation_url_for(&self, config: &CoreConfig, id: &Id) -> String {
136        match &self.invitation_url {
137            Some(template) => template.replace("{id}", id.as_str()),
138            None => format!(
139                "{}/accept-invitation/{id}",
140                config.base_url.as_str().trim_end_matches('/')
141            ),
142        }
143    }
144}
145
146impl Plugin for Organization {
147    const ID: &'static str = "organization";
148    type Requires = ();
149    type UserFields = ();
150    type SessionFields = OrganizationSession;
151
152    fn schema(&self, schema: &mut SchemaBuilder) {
153        schema
154            .model::<OrganizationRow>()
155            .model::<Member>()
156            .model::<Invitation>();
157    }
158
159    fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
160        app.endpoint(CreateOrganization::client())
161            .endpoint(UpdateOrganization)
162            .endpoint(DeleteOrganization)
163            .endpoint(ListOrganizations)
164            .endpoint(GetFullOrganization)
165            .endpoint(SetActiveOrganization)
166            .endpoint(CheckSlug)
167            .endpoint(InviteMember)
168            .endpoint(AcceptInvitation)
169            .endpoint(RejectInvitation)
170            .endpoint(CancelInvitation)
171            .endpoint(GetInvitation)
172            .endpoint(ListInvitations)
173            .endpoint(ListUserInvitations)
174            .endpoint(RemoveMember)
175            .endpoint(UpdateMemberRole)
176            .endpoint(LeaveOrganization)
177            .endpoint(GetActiveMember)
178            .endpoint(ListMembers)
179            .endpoint(HasPermission)
180            .server_endpoint::<AddMember>()
181            .server_endpoint::<CheckPermission>()
182            .server_endpoint::<UserInvitations>()
183            .errors::<OrganizationError>();
184    }
185}
186
187/// Emitted when an organization is created, over HTTP or by the server API.
188#[derive(Clone, Debug, PartialEq, Eq)]
189pub struct OrganizationCreated {
190    pub organization_id: Id,
191    /// The creator, now its owner.
192    pub user_id: Id,
193}
194
195/// Emitted for every new membership: the creator's, `add_member`'s and an accepted
196/// invitation's.
197#[derive(Clone, Debug, PartialEq, Eq)]
198pub struct MemberAdded {
199    pub organization_id: Id,
200    pub user_id: Id,
201    pub member_id: Id,
202    pub role: String,
203}
204
205/// Emitted when a member is removed or leaves. Deleting an organization doesn't emit it
206/// per member.
207#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct MemberRemoved {
209    pub organization_id: Id,
210    pub user_id: Id,
211    pub member_id: Id,
212}
213
214/// Emitted when an invitee accepts; `MemberAdded` fires for the new membership too.
215#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct InvitationAccepted {
217    pub invitation_id: Id,
218    pub organization_id: Id,
219    pub user_id: Id,
220    pub member_id: Id,
221}
222
223impl Event for OrganizationCreated {}
224impl Event for MemberAdded {}
225impl Event for MemberRemoved {}
226impl Event for InvitationAccepted {}