Skip to main content

fastauth_plugin_organization/endpoints/
org.rs

1//! Creating, updating, deleting, listing and activating organizations.
2
3use fastauth_core::adapter::Transaction;
4use fastauth_core::plugin_prelude::*;
5use fastauth_core::routes::Status;
6use serde_json::{Map, Value as JsonValue};
7
8use super::{
9    active_organization, find_member, find_organization, find_organization_by_slug, nullable,
10    organization, plugin, requested_organization, require_text, set_active, slug_taken,
11    user_not_found, with_users,
12};
13use crate::access::OWNER;
14use crate::model::{Invitation, Member, MemberWithUser, OrganizationRow, OrganizationSession};
15use crate::{MemberAdded, Organization, OrganizationCreated, OrganizationError};
16
17/// Body of `/organization/create`.
18#[derive(Clone, Debug, Default, Deserialize)]
19#[serde(rename_all = "camelCase")]
20pub struct CreateOrganizationInput {
21    pub name: String,
22    pub slug: String,
23    pub logo: Option<String>,
24    pub metadata: Option<Map<String, JsonValue>>,
25    /// Leave the session's active organization as it is instead of switching to the new one.
26    #[serde(default)]
27    pub keep_current_active_organization: bool,
28    /// The creator, who becomes the owner, when the server API creates it. Never read from a
29    /// request body: over HTTP (and `create_as`) the session's user is the creator.
30    #[serde(skip)]
31    pub user_id: Option<Id>,
32}
33
34/// An organization with its members: what `/organization/create` answers.
35#[derive(Clone, Debug, PartialEq, Serialize)]
36pub struct OrganizationWithMembers {
37    #[serde(flatten)]
38    pub organization: OrganizationRow,
39    pub members: Vec<Member>,
40}
41
42/// `POST /organization/create`: creates an organization with the caller as its owner and
43/// makes it the session's active organization. The server API's `create` runs the same
44/// endpoint, so hooks on `CreateOrganization` see both.
45#[derive(Clone, Copy, Debug)]
46pub struct CreateOrganization {
47    trusted: bool,
48}
49
50impl CreateOrganization {
51    /// The HTTP route: the session's user creates it, if `allow_user_to_create_organization`.
52    pub fn client() -> Self {
53        Self { trusted: false }
54    }
55
56    /// The server API: `user_id` names the creator, no session is needed, and
57    /// `allow_user_to_create_organization` doesn't apply.
58    pub fn server() -> Self {
59        Self { trusted: true }
60    }
61}
62
63impl<D: Adapter> Endpoint<D> for CreateOrganization {
64    const METHOD: Method = Method::POST;
65    const PATH: &'static str = "/organization/create";
66    type Access = MaybeAuthenticated;
67    type Input = CreateOrganizationInput;
68    type Output = OrganizationWithMembers;
69
70    async fn call(
71        &self,
72        ctx: Ctx<D, MaybeAuthenticated>,
73        mut input: CreateOrganizationInput,
74    ) -> Result<OrganizationWithMembers, AuthError> {
75        if self.trusted {
76            let user_id = input.user_id.take().ok_or_else(AuthError::unauthorized)?;
77            let user = ctx
78                .internal()
79                .find_user_by_id(&user_id)
80                .await?
81                .ok_or_else(user_not_found)?;
82            return create(&ctx, &user.id, input).await;
83        }
84        let session = ctx.session().ok_or_else(AuthError::unauthorized)?;
85        if !plugin(&ctx).allow_user_to_create_organization {
86            return Err(OrganizationError::YouAreNotAllowedToCreateANewOrganization.into());
87        }
88        let keep_active = input.keep_current_active_organization;
89        let created = create(&ctx, &session.user.id, input).await?;
90        if !keep_active {
91            set_active(&ctx, session, Some(&created.organization.id)).await?;
92        }
93        Ok(created)
94    }
95}
96
97/// Creates the organization and its owner membership in one transaction.
98async fn create<D: Adapter, A>(
99    ctx: &Ctx<D, A>,
100    user_id: &Id,
101    input: CreateOrganizationInput,
102) -> Result<OrganizationWithMembers, AuthError> {
103    require_text(&input.name, "name")?;
104    require_text(&input.slug, "slug")?;
105    if let Some(limit) = plugin(ctx).organization_limit {
106        let owned = ctx
107            .db()
108            .count::<Member>(Member::USER_ID.eq(user_id))
109            .await?;
110        if owned >= limit {
111            return Err(OrganizationError::YouHaveReachedTheMaximumNumberOfOrganizations.into());
112        }
113    }
114    if find_organization_by_slug(ctx, &input.slug).await?.is_some() {
115        return Err(OrganizationError::OrganizationAlreadyExists.into());
116    }
117    let now = ctx.now();
118    let organization = OrganizationRow {
119        id: ctx.new_id()?,
120        name: input.name,
121        slug: input.slug,
122        logo: input.logo,
123        metadata: input.metadata.map(Json),
124        created_at: now,
125    };
126    let member = Member {
127        id: ctx.new_id()?,
128        organization_id: organization.id.clone(),
129        user_id: user_id.clone(),
130        role: OWNER.to_owned(),
131        created_at: now,
132    };
133    let tx = ctx.adapter().begin().await?;
134    let db = ctx.db_on(&tx);
135    let organization = db.insert(&organization).await.map_err(slug_taken)?;
136    let member = db.insert(&member).await?;
137    tx.commit().await?;
138    ctx.emit(OrganizationCreated {
139        organization_id: organization.id.clone(),
140        user_id: user_id.clone(),
141    });
142    ctx.emit(MemberAdded {
143        organization_id: organization.id.clone(),
144        user_id: user_id.clone(),
145        member_id: member.id.clone(),
146        role: member.role.clone(),
147    });
148    Ok(OrganizationWithMembers {
149        organization,
150        members: vec![member],
151    })
152}
153
154/// The fields `/organization/update` changes; absent fields stay as they are.
155#[derive(Clone, Debug, Default, Deserialize)]
156#[serde(rename_all = "camelCase")]
157pub struct UpdateOrganizationData {
158    pub name: Option<String>,
159    pub slug: Option<String>,
160    /// `null` removes the logo.
161    #[serde(default, deserialize_with = "nullable")]
162    pub logo: Option<Option<String>>,
163    pub metadata: Option<Map<String, JsonValue>>,
164}
165
166/// Body of `/organization/update`.
167#[derive(Clone, Debug, Default, Deserialize)]
168#[serde(rename_all = "camelCase")]
169pub struct UpdateOrganizationInput {
170    pub data: UpdateOrganizationData,
171    /// Defaults to the active organization.
172    pub organization_id: Option<String>,
173}
174
175/// `POST /organization/update`: needs `organization: [update]`.
176#[derive(Clone, Copy, Debug, Default)]
177pub struct UpdateOrganization;
178
179impl<D: Adapter> Endpoint<D> for UpdateOrganization {
180    const METHOD: Method = Method::POST;
181    const PATH: &'static str = "/organization/update";
182    type Access = Authenticated;
183    type Input = UpdateOrganizationInput;
184    type Output = OrganizationRow;
185
186    async fn call(
187        &self,
188        ctx: Ctx<D, Authenticated>,
189        input: UpdateOrganizationInput,
190    ) -> Result<OrganizationRow, AuthError> {
191        let session = ctx.session();
192        let organization_id = requested_organization(session, input.organization_id.as_deref())?
193            .ok_or(OrganizationError::OrganizationNotFound)?;
194        let member = find_member(&ctx, &organization_id, &session.user.id)
195            .await?
196            .ok_or(OrganizationError::UserIsNotAMemberOfTheOrganization)?;
197        if !plugin(&ctx)
198            .roles
199            .allows(&member.role, &[("organization", &["update"])])
200        {
201            return Err(OrganizationError::YouAreNotAllowedToUpdateThisOrganization.into());
202        }
203        let data = input.data;
204        if let Some(slug) = &data.slug {
205            require_text(slug, "slug")?;
206            if find_organization_by_slug(&ctx, slug)
207                .await?
208                .is_some_and(|o| o.id != organization_id)
209            {
210                return Err(OrganizationError::OrganizationSlugAlreadyTaken.into());
211            }
212        }
213        let mut update = ctx
214            .db()
215            .update::<OrganizationRow>(OrganizationRow::ID.eq(&organization_id));
216        let mut changed = false;
217        if let Some(name) = data.name {
218            require_text(&name, "name")?;
219            update = update.set(OrganizationRow::NAME, name);
220            changed = true;
221        }
222        if let Some(slug) = data.slug {
223            update = update.set(OrganizationRow::SLUG, slug);
224            changed = true;
225        }
226        if let Some(logo) = data.logo {
227            update = update.set(OrganizationRow::LOGO, logo);
228            changed = true;
229        }
230        if let Some(metadata) = data.metadata {
231            update = update.set(OrganizationRow::METADATA, Some(Json(metadata)));
232            changed = true;
233        }
234        if changed {
235            update.exec().await.map_err(slug_taken)?;
236        }
237        organization(&ctx, &organization_id).await
238    }
239}
240
241/// Body of `/organization/delete`.
242#[derive(Clone, Debug, Deserialize)]
243#[serde(rename_all = "camelCase")]
244pub struct DeleteOrganizationInput {
245    pub organization_id: String,
246}
247
248/// `POST /organization/delete`: needs `organization: [delete]`. Deletes the organization
249/// with its members and invitations, and clears it as any session's active organization.
250/// Answers the deleted organization.
251#[derive(Clone, Copy, Debug, Default)]
252pub struct DeleteOrganization;
253
254impl<D: Adapter> Endpoint<D> for DeleteOrganization {
255    const METHOD: Method = Method::POST;
256    const PATH: &'static str = "/organization/delete";
257    type Access = Authenticated;
258    type Input = DeleteOrganizationInput;
259    type Output = OrganizationRow;
260
261    async fn call(
262        &self,
263        ctx: Ctx<D, Authenticated>,
264        input: DeleteOrganizationInput,
265    ) -> Result<OrganizationRow, AuthError> {
266        let session = ctx.session();
267        let organization_id = Id::from(input.organization_id);
268        let member = find_member(&ctx, &organization_id, &session.user.id)
269            .await?
270            .ok_or(OrganizationError::UserIsNotAMemberOfTheOrganization)?;
271        if !plugin(&ctx)
272            .roles
273            .allows(&member.role, &[("organization", &["delete"])])
274        {
275            return Err(OrganizationError::YouAreNotAllowedToDeleteThisOrganization.into());
276        }
277        let deleted = organization(&ctx, &organization_id).await?;
278        delete(&ctx, &organization_id).await?;
279        if active_organization(session)?.as_ref() == Some(&organization_id) {
280            ctx.delete_cookie(super::SESSION_CACHE_COOKIE);
281        }
282        Ok(deleted)
283    }
284}
285
286/// Deletes the organization, its members and invitations in one transaction, without
287/// relying on the database's cascades, and clears it from sessions.
288pub(crate) async fn delete<D: Adapter, A>(ctx: &Ctx<D, A>, id: &Id) -> Result<(), AuthError> {
289    let tx = ctx.adapter().begin().await?;
290    let db = ctx.db_on(&tx);
291    db.delete::<Invitation>(Invitation::ORGANIZATION_ID.eq(id))
292        .await?;
293    db.delete::<Member>(Member::ORGANIZATION_ID.eq(id)).await?;
294    db.delete::<OrganizationRow>(OrganizationRow::ID.eq(id))
295        .await?;
296    db.update::<Session>(OrganizationSession::ACTIVE_ORGANIZATION_ID.eq(Some(id.clone())))
297        .set(OrganizationSession::ACTIVE_ORGANIZATION_ID, None::<Id>)
298        .exec()
299        .await?;
300    tx.commit().await?;
301    Ok(())
302}
303
304/// `GET /organization/list`: the organizations the caller is a member of.
305#[derive(Clone, Copy, Debug, Default)]
306pub struct ListOrganizations;
307
308impl<D: Adapter> Endpoint<D> for ListOrganizations {
309    const METHOD: Method = Method::GET;
310    const PATH: &'static str = "/organization/list";
311    type Access = Authenticated;
312    type Input = Empty;
313    type Output = Vec<OrganizationRow>;
314
315    async fn call(
316        &self,
317        ctx: Ctx<D, Authenticated>,
318        _input: Empty,
319    ) -> Result<Vec<OrganizationRow>, AuthError> {
320        let memberships = ctx
321            .db()
322            .find::<Member>(Member::USER_ID.eq(&ctx.session().user.id))
323            .order_by(Member::CREATED_AT.asc())
324            .all()
325            .await?;
326        if memberships.is_empty() {
327            return Ok(Vec::new());
328        }
329        let organizations = ctx
330            .db()
331            .find::<OrganizationRow>(
332                OrganizationRow::ID.in_(memberships.iter().map(|m| m.organization_id.clone())),
333            )
334            .all()
335            .await?;
336        Ok(memberships
337            .iter()
338            .filter_map(|m| {
339                organizations
340                    .iter()
341                    .find(|o| o.id == m.organization_id)
342                    .cloned()
343            })
344            .collect())
345    }
346}
347
348/// Query of `/organization/get-full-organization`.
349#[derive(Clone, Debug, Default, Deserialize)]
350#[serde(rename_all = "camelCase")]
351pub struct GetFullOrganizationQuery {
352    pub organization_id: Option<String>,
353    pub organization_slug: Option<String>,
354    pub members_limit: Option<u64>,
355}
356
357/// An organization with its members (and their users) and invitations.
358#[derive(Clone, Debug, PartialEq, Serialize)]
359pub struct FullOrganization {
360    #[serde(flatten)]
361    pub organization: OrganizationRow,
362    pub members: Vec<MemberWithUser>,
363    /// Empty unless the caller may create invitations; invitations granting `owner` only
364    /// show to owners.
365    pub invitations: Vec<Invitation>,
366}
367
368/// `GET /organization/get-full-organization`: the requested organization (by id or slug,
369/// else the active one) with members and invitations. `null` when there is no active
370/// organization.
371#[derive(Clone, Copy, Debug, Default)]
372pub struct GetFullOrganization;
373
374impl<D: Adapter> Endpoint<D> for GetFullOrganization {
375    const METHOD: Method = Method::GET;
376    const PATH: &'static str = "/organization/get-full-organization";
377    type Access = Authenticated;
378    type Input = GetFullOrganizationQuery;
379    type Output = Option<FullOrganization>;
380
381    async fn call(
382        &self,
383        ctx: Ctx<D, Authenticated>,
384        input: GetFullOrganizationQuery,
385    ) -> Result<Option<FullOrganization>, AuthError> {
386        let session = ctx.session();
387        let active = active_organization(session)?;
388        let found = match (&input.organization_slug, &input.organization_id, &active) {
389            (Some(slug), _, _) => find_organization_by_slug(&ctx, slug).await?,
390            (None, Some(id), _) => find_organization(&ctx, &Id::from(id.as_str())).await?,
391            (None, None, Some(id)) => find_organization(&ctx, id).await?,
392            (None, None, None) => return Ok(None),
393        };
394        let organization = found.ok_or(OrganizationError::OrganizationNotFound)?;
395        let Some(member) = find_member(&ctx, &organization.id, &session.user.id).await? else {
396            if active.as_ref() == Some(&organization.id) {
397                set_active(&ctx, session, None).await?;
398            }
399            return Err(OrganizationError::UserIsNotAMemberOfTheOrganization
400                .with_status(StatusCode::FORBIDDEN));
401        };
402        let mut members = ctx
403            .db()
404            .find::<Member>(Member::ORGANIZATION_ID.eq(&organization.id))
405            .order_by(Member::CREATED_AT.asc());
406        if let Some(limit) = input.members_limit {
407            members = members.limit(limit);
408        }
409        let members = with_users(&ctx, members.all().await?).await?;
410        let invitations = visible_invitations(&ctx, plugin(&ctx), &member).await?;
411        Ok(Some(FullOrganization {
412            organization,
413            members,
414            invitations,
415        }))
416    }
417}
418
419/// The member's organization's invitations, as far as the member may see them: none
420/// without `invitation: [create]` (an invitation id works as a link), and none granting
421/// `owner` unless the member is an owner.
422pub(crate) async fn visible_invitations<D: Adapter, A>(
423    ctx: &Ctx<D, A>,
424    plugin: &Organization,
425    member: &Member,
426) -> Result<Vec<Invitation>, AuthError> {
427    if !plugin
428        .roles
429        .allows(&member.role, &[("invitation", &["create"])])
430    {
431        return Ok(Vec::new());
432    }
433    let invitations = ctx
434        .db()
435        .find::<Invitation>(Invitation::ORGANIZATION_ID.eq(&member.organization_id))
436        .order_by(Invitation::CREATED_AT.asc())
437        .all()
438        .await?;
439    let is_owner = member.has_role(OWNER);
440    Ok(invitations
441        .into_iter()
442        .filter(|i| is_owner || !crate::access::role_list(&i.role).any(|r| r == OWNER))
443        .collect())
444}
445
446/// Body of `/organization/set-active`.
447#[derive(Clone, Debug, Default, Deserialize)]
448#[serde(rename_all = "camelCase")]
449pub struct SetActiveOrganizationInput {
450    /// `null` clears the active organization.
451    #[serde(default, deserialize_with = "nullable")]
452    pub organization_id: Option<Option<String>>,
453    pub organization_slug: Option<String>,
454}
455
456/// `POST /organization/set-active`: makes an organization the caller is a member of the
457/// session's active one, or clears it with `organizationId: null`. Answers the organization,
458/// or `null`.
459#[derive(Clone, Copy, Debug, Default)]
460pub struct SetActiveOrganization;
461
462impl<D: Adapter> Endpoint<D> for SetActiveOrganization {
463    const METHOD: Method = Method::POST;
464    const PATH: &'static str = "/organization/set-active";
465    type Access = Authenticated;
466    type Input = SetActiveOrganizationInput;
467    type Output = Option<OrganizationRow>;
468
469    async fn call(
470        &self,
471        ctx: Ctx<D, Authenticated>,
472        input: SetActiveOrganizationInput,
473    ) -> Result<Option<OrganizationRow>, AuthError> {
474        let session = ctx.session();
475        let active = active_organization(session)?;
476        let organization_id = match (input.organization_id, input.organization_slug) {
477            (Some(None), _) => {
478                if active.is_some() {
479                    set_active(&ctx, session, None).await?;
480                }
481                return Ok(None);
482            }
483            (Some(Some(id)), _) => Id::from(id),
484            (None, Some(slug)) => {
485                find_organization_by_slug(&ctx, &slug)
486                    .await?
487                    .ok_or(OrganizationError::OrganizationNotFound)?
488                    .id
489            }
490            (None, None) => match &active {
491                Some(id) => id.clone(),
492                None => return Ok(None),
493            },
494        };
495        if find_member(&ctx, &organization_id, &session.user.id)
496            .await?
497            .is_none()
498        {
499            if active.is_some() {
500                set_active(&ctx, session, None).await?;
501            }
502            return Err(OrganizationError::UserIsNotAMemberOfTheOrganization
503                .with_status(StatusCode::FORBIDDEN));
504        }
505        let organization = organization(&ctx, &organization_id).await?;
506        set_active(&ctx, session, Some(&organization.id)).await?;
507        Ok(Some(organization))
508    }
509}
510
511/// Body of `/organization/check-slug`.
512#[derive(Clone, Debug, Deserialize)]
513pub struct CheckSlugInput {
514    pub slug: String,
515}
516
517/// `POST /organization/check-slug`: `{ "status": true }` when the slug is free, else 400
518/// `ORGANIZATION_SLUG_ALREADY_TAKEN`.
519#[derive(Clone, Copy, Debug, Default)]
520pub struct CheckSlug;
521
522impl<D: Adapter> Endpoint<D> for CheckSlug {
523    const METHOD: Method = Method::POST;
524    const PATH: &'static str = "/organization/check-slug";
525    type Access = Authenticated;
526    type Input = CheckSlugInput;
527    type Output = Status;
528
529    async fn call(
530        &self,
531        ctx: Ctx<D, Authenticated>,
532        input: CheckSlugInput,
533    ) -> Result<Status, AuthError> {
534        if find_organization_by_slug(&ctx, &input.slug)
535            .await?
536            .is_some()
537        {
538            return Err(OrganizationError::OrganizationSlugAlreadyTaken.into());
539        }
540        Ok(Status { status: true })
541    }
542}