Skip to main content

fastauth_plugin_organization/endpoints/
invitations.rs

1//! Invitations: sending, answering, cancelling and listing them.
2
3use fastauth_core::mail::{AuthEmail, PluginEmail};
4use fastauth_core::plugin_prelude::*;
5use time::format_description::well_known::Rfc3339;
6
7use super::{
8    RoleInput, checked_roles, find_member, find_organization, insert_member, organization, plugin,
9    requested_organization, set_active,
10};
11use crate::access::OWNER;
12use crate::endpoints::org::visible_invitations;
13use crate::model::{Invitation, InvitationStatus, Member, OrganizationRow};
14use crate::{InvitationAccepted, Organization, OrganizationError};
15
16/// Body of `/organization/invite-member`.
17#[derive(Clone, Debug, Deserialize)]
18#[serde(rename_all = "camelCase")]
19pub struct InviteMemberInput {
20    pub email: String,
21    pub role: RoleInput,
22    /// Defaults to the active organization.
23    pub organization_id: Option<String>,
24    /// For an address with a pending invitation: extend it and send the email again,
25    /// instead of answering `USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION`.
26    #[serde(default)]
27    pub resend: bool,
28}
29
30/// `POST /organization/invite-member`: needs `invitation: [create]`; only owners invite
31/// owners. Stores a pending invitation that expires after the configured TTL and, when a
32/// mailer is configured, emails the invitee a link (`AuthEmail::Plugin`, kind
33/// `"organization-invitation"`). Answers the invitation.
34#[derive(Clone, Copy, Debug, Default)]
35pub struct InviteMember;
36
37impl<D: Adapter> Endpoint<D> for InviteMember {
38    const METHOD: Method = Method::POST;
39    const PATH: &'static str = "/organization/invite-member";
40    type Access = Authenticated;
41    type Input = InviteMemberInput;
42    type Output = Invitation;
43
44    async fn call(
45        &self,
46        ctx: Ctx<D, Authenticated>,
47        input: InviteMemberInput,
48    ) -> Result<Invitation, AuthError> {
49        let session = ctx.session();
50        let plugin = plugin(&ctx);
51        let organization_id = requested_organization(session, input.organization_id.as_deref())?
52            .ok_or(OrganizationError::OrganizationNotFound)?;
53        let email = normalized_email(&input.email)?;
54        let inviter = find_member(&ctx, &organization_id, &session.user.id)
55            .await?
56            .ok_or(OrganizationError::MemberNotFound)?;
57        if !plugin
58            .roles
59            .allows(&inviter.role, &[("invitation", &["create"])])
60        {
61            return Err(OrganizationError::YouAreNotAllowedToInviteUsersToThisOrganization.into());
62        }
63        let role = checked_roles(plugin, &input.role)?;
64        let grants_owner = |role: &str| crate::access::role_list(role).any(|r| r == OWNER);
65        if grants_owner(&role) && !inviter.has_role(OWNER) {
66            return Err(OrganizationError::YouAreNotAllowedToInviteUserWithThisRole.into());
67        }
68        if let Some(user) = ctx.internal().find_user_by_email(&email).await?
69            && find_member(&ctx, &organization_id, &user.id)
70                .await?
71                .is_some()
72        {
73            return Err(OrganizationError::UserIsAlreadyAMemberOfThisOrganization.into());
74        }
75        let organization = organization(&ctx, &organization_id).await?;
76        let expires_at = ctx.now() + plugin.invitation_ttl;
77        let pending = ctx
78            .db()
79            .find::<Invitation>(
80                Invitation::ORGANIZATION_ID
81                    .eq(&organization_id)
82                    .and(Invitation::EMAIL.eq(email.as_str()))
83                    .and(Invitation::STATUS.eq(InvitationStatus::Pending))
84                    .and(Invitation::EXPIRES_AT.gt(ctx.now())),
85            )
86            .one()
87            .await?;
88        let invitation = match pending {
89            Some(_) if !input.resend => {
90                return Err(OrganizationError::UserIsAlreadyInvitedToThisOrganization.into());
91            }
92            Some(existing) => {
93                if grants_owner(&existing.role) && !inviter.has_role(OWNER) {
94                    return Err(OrganizationError::YouAreNotAllowedToInviteUserWithThisRole.into());
95                }
96                ctx.db()
97                    .update::<Invitation>(Invitation::ID.eq(&existing.id))
98                    .set(Invitation::EXPIRES_AT, expires_at)
99                    .exec()
100                    .await?;
101                Invitation {
102                    expires_at,
103                    ..existing
104                }
105            }
106            None => {
107                ctx.db()
108                    .insert(&Invitation {
109                        id: ctx.new_id()?,
110                        organization_id,
111                        email,
112                        role,
113                        status: InvitationStatus::Pending,
114                        inviter_id: session.user.id.clone(),
115                        expires_at,
116                        created_at: ctx.now(),
117                    })
118                    .await?
119            }
120        };
121        send_invitation_email(&ctx, plugin, &invitation, &organization, &session.user).await?;
122        Ok(invitation)
123    }
124}
125
126fn normalized_email(email: &str) -> Result<String, AuthError> {
127    let email = email.trim().to_lowercase();
128    let valid = !email.contains(char::is_whitespace)
129        && email.split_once('@').is_some_and(|(local, domain)| {
130            !local.is_empty()
131                && !domain.contains('@')
132                && domain.contains('.')
133                && !domain.starts_with('.')
134                && !domain.ends_with('.')
135        });
136    if !valid {
137        return Err(AuthError::bad_request(
138            codes::INVALID_EMAIL,
139            "invalid email",
140        ));
141    }
142    Ok(email)
143}
144
145async fn send_invitation_email<D: Adapter, A>(
146    ctx: &Ctx<D, A>,
147    plugin: &Organization,
148    invitation: &Invitation,
149    organization: &OrganizationRow,
150    inviter: &UserView,
151) -> Result<(), AuthError> {
152    let internal = ctx.internal();
153    if !internal.can_send_email() {
154        return Ok(());
155    }
156    let url = plugin.invitation_url_for(ctx.config(), &invitation.id);
157    let expires = invitation
158        .expires_at
159        .format(&Rfc3339)
160        .map_err(AuthError::internal)?;
161    internal
162        .send_email(AuthEmail::Plugin(PluginEmail {
163            kind: "organization-invitation",
164            to: invitation.email.clone(),
165            subject: format!("{} invited you to {}", inviter.name, organization.name),
166            text: format!(
167                "{} ({}) invited you to join {} as {}.\n\nAccept the invitation: {url}\n\nThe invitation expires at {expires}.\n",
168                inviter.name, inviter.email, organization.name, invitation.role
169            ),
170            url: Some(url),
171            code: Some(invitation.id.to_string()),
172        }))
173        .await
174}
175
176/// Body of the endpoints that act on one invitation.
177#[derive(Clone, Debug, Deserialize)]
178#[serde(rename_all = "camelCase")]
179pub struct InvitationIdInput {
180    pub invitation_id: String,
181}
182
183/// What accepting or rejecting answers: the invitation and the new membership (`null`
184/// on rejection).
185#[derive(Clone, Debug, PartialEq, Serialize)]
186pub struct InvitationResponse {
187    pub invitation: Invitation,
188    pub member: Option<Member>,
189}
190
191/// The invitation, if it is addressed to the session's user and they may act on it.
192async fn own_invitation<D: Adapter>(
193    ctx: &Ctx<D, Authenticated>,
194    id: &str,
195    must_be_live: bool,
196) -> Result<Invitation, AuthError> {
197    let invitation = ctx
198        .db()
199        .find::<Invitation>(Invitation::ID.eq(Id::from(id)))
200        .one()
201        .await?
202        .filter(|i| {
203            i.status == InvitationStatus::Pending && (!must_be_live || i.expires_at > ctx.now())
204        })
205        .ok_or(OrganizationError::InvitationNotFound)?;
206    let user = &ctx.session().user;
207    if !invitation.email.eq_ignore_ascii_case(&user.email) {
208        return Err(OrganizationError::YouAreNotTheRecipientOfTheInvitation.into());
209    }
210    if plugin(ctx).require_email_verification_on_invitation && !user.email_verified {
211        return Err(
212            OrganizationError::EmailVerificationRequiredBeforeAcceptingOrRejectingInvitation.into(),
213        );
214    }
215    Ok(invitation)
216}
217
218/// `POST /organization/accept-invitation`: the invitee joins with the invited role, and the
219/// organization becomes the session's active one.
220#[derive(Clone, Copy, Debug, Default)]
221pub struct AcceptInvitation;
222
223impl<D: Adapter> Endpoint<D> for AcceptInvitation {
224    const METHOD: Method = Method::POST;
225    const PATH: &'static str = "/organization/accept-invitation";
226    type Access = Authenticated;
227    type Input = InvitationIdInput;
228    type Output = InvitationResponse;
229
230    async fn call(
231        &self,
232        ctx: Ctx<D, Authenticated>,
233        input: InvitationIdInput,
234    ) -> Result<InvitationResponse, AuthError> {
235        let invitation = own_invitation(&ctx, &input.invitation_id, true).await?;
236        let session = ctx.session();
237        organization(&ctx, &invitation.organization_id).await?;
238        if find_member(&ctx, &invitation.organization_id, &session.user.id)
239            .await?
240            .is_some()
241        {
242            return Err(OrganizationError::UserIsAlreadyAMemberOfThisOrganization.into());
243        }
244        let claimed = update_status(
245            &ctx,
246            &invitation.id,
247            InvitationStatus::Pending,
248            InvitationStatus::Accepted,
249        )
250        .await?;
251        if !claimed {
252            return Err(OrganizationError::InvitationNotFound.into());
253        }
254        let member = match insert_member(
255            &ctx,
256            &invitation.organization_id,
257            &session.user.id,
258            invitation.role.clone(),
259        )
260        .await
261        {
262            Ok(member) => member,
263            Err(err) => {
264                update_status(
265                    &ctx,
266                    &invitation.id,
267                    InvitationStatus::Accepted,
268                    InvitationStatus::Pending,
269                )
270                .await?;
271                return Err(err);
272            }
273        };
274        set_active(&ctx, session, Some(&invitation.organization_id)).await?;
275        ctx.emit(InvitationAccepted {
276            invitation_id: invitation.id.clone(),
277            organization_id: invitation.organization_id.clone(),
278            user_id: session.user.id.clone(),
279            member_id: member.id.clone(),
280        });
281        Ok(InvitationResponse {
282            invitation: Invitation {
283                status: InvitationStatus::Accepted,
284                ..invitation
285            },
286            member: Some(member),
287        })
288    }
289}
290
291/// Moves an invitation from `from` to `to`; false when it wasn't in `from` any more.
292async fn update_status<D: Adapter, A>(
293    ctx: &Ctx<D, A>,
294    id: &Id,
295    from: InvitationStatus,
296    to: InvitationStatus,
297) -> Result<bool, AuthError> {
298    let updated = ctx
299        .db()
300        .update::<Invitation>(Invitation::ID.eq(id).and(Invitation::STATUS.eq(from)))
301        .set(Invitation::STATUS, to)
302        .exec()
303        .await?;
304    Ok(updated == 1)
305}
306
307/// `POST /organization/reject-invitation`: the invitee declines.
308#[derive(Clone, Copy, Debug, Default)]
309pub struct RejectInvitation;
310
311impl<D: Adapter> Endpoint<D> for RejectInvitation {
312    const METHOD: Method = Method::POST;
313    const PATH: &'static str = "/organization/reject-invitation";
314    type Access = Authenticated;
315    type Input = InvitationIdInput;
316    type Output = InvitationResponse;
317
318    async fn call(
319        &self,
320        ctx: Ctx<D, Authenticated>,
321        input: InvitationIdInput,
322    ) -> Result<InvitationResponse, AuthError> {
323        let invitation = own_invitation(&ctx, &input.invitation_id, false).await?;
324        organization(&ctx, &invitation.organization_id).await?;
325        update_status(
326            &ctx,
327            &invitation.id,
328            InvitationStatus::Pending,
329            InvitationStatus::Rejected,
330        )
331        .await?;
332        Ok(InvitationResponse {
333            invitation: Invitation {
334                status: InvitationStatus::Rejected,
335                ..invitation
336            },
337            member: None,
338        })
339    }
340}
341
342/// `POST /organization/cancel-invitation`: needs `invitation: [cancel]` in the
343/// invitation's organization. Answers the cancelled invitation.
344#[derive(Clone, Copy, Debug, Default)]
345pub struct CancelInvitation;
346
347impl<D: Adapter> Endpoint<D> for CancelInvitation {
348    const METHOD: Method = Method::POST;
349    const PATH: &'static str = "/organization/cancel-invitation";
350    type Access = Authenticated;
351    type Input = InvitationIdInput;
352    type Output = Invitation;
353
354    async fn call(
355        &self,
356        ctx: Ctx<D, Authenticated>,
357        input: InvitationIdInput,
358    ) -> Result<Invitation, AuthError> {
359        let invitation = ctx
360            .db()
361            .find::<Invitation>(Invitation::ID.eq(Id::from(input.invitation_id)))
362            .one()
363            .await?
364            .ok_or(OrganizationError::InvitationNotFound)?;
365        let member = find_member(&ctx, &invitation.organization_id, &ctx.session().user.id)
366            .await?
367            .ok_or(OrganizationError::MemberNotFound)?;
368        if !plugin(&ctx)
369            .roles
370            .allows(&member.role, &[("invitation", &["cancel"])])
371        {
372            return Err(OrganizationError::YouAreNotAllowedToCancelThisInvitation.into());
373        }
374        organization(&ctx, &invitation.organization_id).await?;
375        ctx.db()
376            .update::<Invitation>(Invitation::ID.eq(&invitation.id))
377            .set(Invitation::STATUS, InvitationStatus::Canceled)
378            .exec()
379            .await?;
380        Ok(Invitation {
381            status: InvitationStatus::Canceled,
382            ..invitation
383        })
384    }
385}
386
387/// Query of `/organization/get-invitation`.
388#[derive(Clone, Debug, Deserialize)]
389pub struct InvitationIdQuery {
390    pub id: String,
391}
392
393/// An invitation with what an invitee needs to decide: `/organization/get-invitation`.
394#[derive(Clone, Debug, PartialEq, Serialize)]
395#[serde(rename_all = "camelCase")]
396pub struct InvitationDetails {
397    #[serde(flatten)]
398    pub invitation: Invitation,
399    pub organization_name: String,
400    pub organization_slug: String,
401    pub inviter_email: String,
402}
403
404/// `GET /organization/get-invitation?id=..`: a live invitation addressed to the caller.
405#[derive(Clone, Copy, Debug, Default)]
406pub struct GetInvitation;
407
408impl<D: Adapter> Endpoint<D> for GetInvitation {
409    const METHOD: Method = Method::GET;
410    const PATH: &'static str = "/organization/get-invitation";
411    type Access = Authenticated;
412    type Input = InvitationIdQuery;
413    type Output = InvitationDetails;
414
415    async fn call(
416        &self,
417        ctx: Ctx<D, Authenticated>,
418        input: InvitationIdQuery,
419    ) -> Result<InvitationDetails, AuthError> {
420        let invitation = ctx
421            .db()
422            .find::<Invitation>(Invitation::ID.eq(Id::from(input.id)))
423            .one()
424            .await?
425            .filter(|i| i.status == InvitationStatus::Pending && i.expires_at > ctx.now())
426            .ok_or(OrganizationError::InvitationNotFound)?;
427        let user = &ctx.session().user;
428        if !invitation.email.eq_ignore_ascii_case(&user.email) {
429            return Err(OrganizationError::YouAreNotTheRecipientOfTheInvitation.into());
430        }
431        if plugin(&ctx).require_email_verification_on_invitation && !user.email_verified {
432            return Err(OrganizationError::EmailVerificationRequiredForInvitation.into());
433        }
434        let organization = organization(&ctx, &invitation.organization_id).await?;
435        let inviter =
436            match find_member(&ctx, &invitation.organization_id, &invitation.inviter_id).await? {
437                Some(_) => {
438                    ctx.internal()
439                        .find_user_by_id(&invitation.inviter_id)
440                        .await?
441                }
442                None => None,
443            }
444            .ok_or(OrganizationError::InviterIsNoLongerAMemberOfTheOrganization)?;
445        Ok(InvitationDetails {
446            invitation,
447            organization_name: organization.name,
448            organization_slug: organization.slug,
449            inviter_email: inviter.email.clone(),
450        })
451    }
452}
453
454/// Query of `/organization/list-invitations`.
455#[derive(Clone, Debug, Default, Deserialize)]
456#[serde(rename_all = "camelCase")]
457pub struct OrganizationIdQuery {
458    /// Defaults to the active organization.
459    pub organization_id: Option<String>,
460}
461
462/// `GET /organization/list-invitations`: the organization's invitations, for members who
463/// may create them. Invitations granting `owner` only show to owners.
464#[derive(Clone, Copy, Debug, Default)]
465pub struct ListInvitations;
466
467impl<D: Adapter> Endpoint<D> for ListInvitations {
468    const METHOD: Method = Method::GET;
469    const PATH: &'static str = "/organization/list-invitations";
470    type Access = Authenticated;
471    type Input = OrganizationIdQuery;
472    type Output = Vec<Invitation>;
473
474    async fn call(
475        &self,
476        ctx: Ctx<D, Authenticated>,
477        input: OrganizationIdQuery,
478    ) -> Result<Vec<Invitation>, AuthError> {
479        let session = ctx.session();
480        let organization_id = requested_organization(session, input.organization_id.as_deref())?
481            .ok_or(OrganizationError::NoActiveOrganization)?;
482        let member = find_member(&ctx, &organization_id, &session.user.id)
483            .await?
484            .ok_or(OrganizationError::YouAreNotAMemberOfThisOrganization)?;
485        let plugin = plugin(&ctx);
486        if !plugin
487            .roles
488            .allows(&member.role, &[("invitation", &["create"])])
489        {
490            return Err(OrganizationError::YouAreNotAllowedToListInvitations.into());
491        }
492        visible_invitations(&ctx, plugin, &member).await
493    }
494}
495
496/// A pending invitation with its organization's name: `/organization/list-user-invitations`.
497#[derive(Clone, Debug, PartialEq, Serialize)]
498#[serde(rename_all = "camelCase")]
499pub struct InvitationWithOrganization {
500    #[serde(flatten)]
501    pub invitation: Invitation,
502    pub organization_name: String,
503}
504
505/// `GET /organization/list-user-invitations`: the pending invitations addressed to the
506/// caller's email, which must be verified. The server API lists any address's with
507/// `auth.organization().invitations_for_email(email)`.
508#[derive(Clone, Copy, Debug, Default)]
509pub struct ListUserInvitations;
510
511impl<D: Adapter> Endpoint<D> for ListUserInvitations {
512    const METHOD: Method = Method::GET;
513    const PATH: &'static str = "/organization/list-user-invitations";
514    type Access = Authenticated;
515    type Input = Empty;
516    type Output = Vec<InvitationWithOrganization>;
517
518    async fn call(
519        &self,
520        ctx: Ctx<D, Authenticated>,
521        _input: Empty,
522    ) -> Result<Vec<InvitationWithOrganization>, AuthError> {
523        let user = &ctx.session().user;
524        if !user.email_verified {
525            return Err(OrganizationError::EmailVerificationRequiredForInvitation.into());
526        }
527        invitations_for(&ctx, &user.email).await
528    }
529}
530
531/// Pending invitations addressed to `email`, with their organizations' names.
532pub(crate) async fn invitations_for<D: Adapter, A>(
533    ctx: &Ctx<D, A>,
534    email: &str,
535) -> Result<Vec<InvitationWithOrganization>, AuthError> {
536    let invitations = ctx
537        .db()
538        .find::<Invitation>(
539            Invitation::EMAIL
540                .eq(email.trim().to_lowercase())
541                .and(Invitation::STATUS.eq(InvitationStatus::Pending)),
542        )
543        .order_by(Invitation::CREATED_AT.asc())
544        .all()
545        .await?;
546    let mut out = Vec::with_capacity(invitations.len());
547    for invitation in invitations {
548        if let Some(organization) = find_organization(ctx, &invitation.organization_id).await? {
549            out.push(InvitationWithOrganization {
550                invitation,
551                organization_name: organization.name,
552            });
553        }
554    }
555    Ok(out)
556}