Skip to main content

fastauth_plugin_organization/endpoints/
mod.rs

1//! The `/organization/*` endpoints and the lookups they share.
2
3mod invitations;
4mod members;
5mod org;
6pub(crate) mod server;
7
8use fastauth_core::adapter::DbError;
9use fastauth_core::plugin_prelude::*;
10use serde::Deserializer;
11
12pub use invitations::{
13    AcceptInvitation, CancelInvitation, GetInvitation, InvitationDetails, InvitationIdInput,
14    InvitationIdQuery, InvitationResponse, InvitationWithOrganization, InviteMember,
15    InviteMemberInput, ListInvitations, ListUserInvitations, OrganizationIdQuery, RejectInvitation,
16};
17pub use members::{
18    GetActiveMember, HasPermission, HasPermissionInput, HasPermissionOutput, LeaveOrganization,
19    LeaveOrganizationInput, ListMembers, ListMembersOutput, ListMembersQuery, RemoveMember,
20    RemoveMemberInput, RemoveMemberOutput, SortDirection, UpdateMemberRole, UpdateMemberRoleInput,
21};
22pub use org::{
23    CheckSlug, CheckSlugInput, CreateOrganization, CreateOrganizationInput, DeleteOrganization,
24    DeleteOrganizationInput, FullOrganization, GetFullOrganization, GetFullOrganizationQuery,
25    ListOrganizations, OrganizationWithMembers, SetActiveOrganization, SetActiveOrganizationInput,
26    UpdateOrganization, UpdateOrganizationData, UpdateOrganizationInput,
27};
28
29use crate::access::OWNER;
30use crate::model::{Member, MemberUser, MemberWithUser, OrganizationRow, OrganizationSession};
31use crate::{MemberAdded, Organization, OrganizationError};
32
33const SESSION_CACHE_COOKIE: &str = "session_data";
34
35/// A role in a request body: `"admin"`, `"admin,billing"` or `["admin", "billing"]`.
36#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
37#[serde(untagged)]
38pub enum RoleInput {
39    One(String),
40    Many(Vec<String>),
41}
42
43impl RoleInput {
44    fn names(&self) -> Vec<&str> {
45        match self {
46            Self::One(role) => crate::access::role_list(role).collect(),
47            Self::Many(roles) => roles
48                .iter()
49                .flat_map(|r| crate::access::role_list(r))
50                .collect(),
51        }
52    }
53}
54
55impl From<&str> for RoleInput {
56    fn from(role: &str) -> Self {
57        Self::One(role.to_owned())
58    }
59}
60
61/// Checks every role exists and returns them in their stored, comma-separated form.
62fn checked_roles(plugin: &Organization, roles: &RoleInput) -> Result<String, AuthError> {
63    let names = roles.names();
64    let unknown: Vec<&str> = names
65        .iter()
66        .copied()
67        .filter(|r| !plugin.roles.contains(r))
68        .collect();
69    if names.is_empty() || !unknown.is_empty() {
70        return Err(OrganizationError::RoleNotFound {
71            roles: unknown.join(", "),
72        }
73        .into());
74    }
75    Ok(names.join(","))
76}
77
78/// For fields where `null` and absent mean different things: absent is `None`, `null` is
79/// `Some(None)`.
80fn nullable<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
81    deserializer: D,
82) -> Result<Option<Option<T>>, D::Error> {
83    Option::<T>::deserialize(deserializer).map(Some)
84}
85
86/// The 400 `USER_NOT_FOUND` the server API answers for an unknown `user_id`.
87fn user_not_found() -> AuthError {
88    AuthError::bad_request(codes::USER_NOT_FOUND, "User not found")
89}
90
91fn plugin<D: Adapter, A>(ctx: &Ctx<D, A>) -> &Organization {
92    ctx.plugin::<Organization>()
93}
94
95fn active_organization(session: &SessionView) -> Result<Option<Id>, AuthError> {
96    Ok(session
97        .fields::<OrganizationSession>()
98        .map_err(AuthError::internal)?
99        .active_organization_id)
100}
101
102/// Sets or clears the session's active organization and drops the session cookie cache,
103/// which still holds the old value.
104async fn set_active<D: Adapter, A>(
105    ctx: &Ctx<D, A>,
106    session: &SessionView,
107    organization_id: Option<&Id>,
108) -> Result<(), AuthError> {
109    if session.ephemeral {
110        return Ok(());
111    }
112    ctx.db()
113        .update::<Session>(Session::ID.eq(&session.session.id))
114        .set(
115            OrganizationSession::ACTIVE_ORGANIZATION_ID,
116            organization_id.cloned(),
117        )
118        .exec()
119        .await?;
120    ctx.delete_cookie(SESSION_CACHE_COOKIE);
121    Ok(())
122}
123
124async fn find_organization<D: Adapter, A>(
125    ctx: &Ctx<D, A>,
126    id: &Id,
127) -> Result<Option<OrganizationRow>, AuthError> {
128    Ok(ctx
129        .db()
130        .find::<OrganizationRow>(OrganizationRow::ID.eq(id))
131        .one()
132        .await?)
133}
134
135async fn find_organization_by_slug<D: Adapter, A>(
136    ctx: &Ctx<D, A>,
137    slug: &str,
138) -> Result<Option<OrganizationRow>, AuthError> {
139    Ok(ctx
140        .db()
141        .find::<OrganizationRow>(OrganizationRow::SLUG.eq(slug))
142        .one()
143        .await?)
144}
145
146/// The organization by id, or the 400 `ORGANIZATION_NOT_FOUND` Better Auth answers.
147async fn organization<D: Adapter, A>(
148    ctx: &Ctx<D, A>,
149    id: &Id,
150) -> Result<OrganizationRow, AuthError> {
151    Ok(find_organization(ctx, id)
152        .await?
153        .ok_or(OrganizationError::OrganizationNotFound)?)
154}
155
156async fn find_member<D: Adapter, A>(
157    ctx: &Ctx<D, A>,
158    organization_id: &Id,
159    user_id: &Id,
160) -> Result<Option<Member>, AuthError> {
161    Ok(ctx
162        .db()
163        .find::<Member>(
164            Member::ORGANIZATION_ID
165                .eq(organization_id)
166                .and(Member::USER_ID.eq(user_id)),
167        )
168        .one()
169        .await?)
170}
171
172async fn members_of<D: Adapter, A>(
173    ctx: &Ctx<D, A>,
174    organization_id: &Id,
175) -> Result<Vec<Member>, AuthError> {
176    Ok(ctx
177        .db()
178        .find::<Member>(Member::ORGANIZATION_ID.eq(organization_id))
179        .order_by(Member::CREATED_AT.asc())
180        .all()
181        .await?)
182}
183
184/// Whether `member` holds the only owner role of its organization.
185async fn is_last_owner<D: Adapter, A>(ctx: &Ctx<D, A>, member: &Member) -> Result<bool, AuthError> {
186    if !member.has_role(OWNER) {
187        return Ok(false);
188    }
189    let owners = members_of(ctx, &member.organization_id)
190        .await?
191        .iter()
192        .filter(|m| m.has_role(OWNER))
193        .count();
194    Ok(owners <= 1)
195}
196
197/// The organization a request acts on: the one it names, else the session's active one.
198fn requested_organization(
199    session: &SessionView,
200    organization_id: Option<&str>,
201) -> Result<Option<Id>, AuthError> {
202    match organization_id {
203        Some(id) if !id.is_empty() => Ok(Some(Id::from(id))),
204        _ => active_organization(session),
205    }
206}
207
208/// Inserts a membership, refusing a second one for the same user and organization, and
209/// emits `MemberAdded`.
210async fn insert_member<D: Adapter, A>(
211    ctx: &Ctx<D, A>,
212    organization_id: &Id,
213    user_id: &Id,
214    role: String,
215) -> Result<Member, AuthError> {
216    if find_member(ctx, organization_id, user_id).await?.is_some() {
217        return Err(OrganizationError::UserIsAlreadyAMemberOfThisOrganization.into());
218    }
219    let member = ctx
220        .db()
221        .insert(&Member {
222            id: ctx.new_id()?,
223            organization_id: organization_id.clone(),
224            user_id: user_id.clone(),
225            role,
226            created_at: ctx.now(),
227        })
228        .await?;
229    ctx.emit(MemberAdded {
230        organization_id: member.organization_id.clone(),
231        user_id: member.user_id.clone(),
232        member_id: member.id.clone(),
233        role: member.role.clone(),
234    });
235    Ok(member)
236}
237
238/// Attaches `{ id, name, email, image }` of each member's user.
239async fn with_users<D: Adapter, A>(
240    ctx: &Ctx<D, A>,
241    members: Vec<Member>,
242) -> Result<Vec<MemberWithUser>, AuthError> {
243    if members.is_empty() {
244        return Ok(Vec::new());
245    }
246    let users = ctx
247        .db()
248        .find::<User>(User::ID.in_(members.iter().map(|m| m.user_id.clone())))
249        .all()
250        .await?;
251    members
252        .into_iter()
253        .map(|member| {
254            let user = users
255                .iter()
256                .find(|u| u.id == member.user_id)
257                .ok_or_else(|| AuthError::internal("member without a user"))?;
258            Ok(MemberWithUser {
259                user: MemberUser {
260                    id: user.id.clone(),
261                    name: user.name.clone(),
262                    email: user.email.clone(),
263                    image: user.image.clone(),
264                },
265                member,
266            })
267        })
268        .collect()
269}
270
271fn slug_taken(err: DbError) -> AuthError {
272    match err {
273        DbError::UniqueViolation { ref table, .. } if table == OrganizationRow::TABLE => {
274            OrganizationError::OrganizationAlreadyExists.into()
275        }
276        other => other.into(),
277    }
278}
279
280fn require_text(value: &str, field: &str) -> Result<(), AuthError> {
281    if value.trim().is_empty() {
282        return Err(AuthError::bad_request(
283            codes::INVALID_BODY,
284            format!("{field} must not be empty"),
285        ));
286    }
287    Ok(())
288}