Skip to main content

fastauth_plugin_organization/
api.rs

1//! `auth.organization()`: the server API.
2
3use std::collections::BTreeMap;
4
5use fastauth_core::ApiResponse;
6use fastauth_core::plugin_prelude::*;
7use fastauth_core::routes::Status;
8
9use crate::endpoints::server::{
10    AddMember, CheckPermission, EmailQuery, NewMember, PermissionCheck, UserInvitations,
11};
12use crate::endpoints::*;
13use crate::{Invitation, Member, MemberWithUser, Organization, OrganizationRow, Roles};
14
15/// `auth.organization()`: the server API. Only compiles on an `Auth` with `Organization`
16/// registered.
17pub trait OrganizationExt: AuthInstance + Sized {
18    fn organization<I>(&self) -> OrganizationApi<'_, Self>
19    where
20        Self: HasPlugin<Organization, I>,
21    {
22        OrganizationApi {
23            auth: self,
24            plugin: self.plugin_arc().clone(),
25        }
26    }
27}
28
29impl<A: AuthInstance> OrganizationExt for A {}
30
31/// Calls the organization endpoints without HTTP.
32///
33/// [`create`](Self::create), [`add_member`](Self::add_member),
34/// [`has_permission`](Self::has_permission) and
35/// [`invitations_for_email`](Self::invitations_for_email) act for the server and need no
36/// session. Every other method calls the route of the same name as the session in
37/// `headers` (their cookies, or whatever a session resolver reads), and answers what the
38/// route would, plus the cookies it sets.
39pub struct OrganizationApi<'a, A> {
40    auth: &'a A,
41    plugin: Arc<Organization>,
42}
43
44impl<A: AuthInstance> OrganizationApi<'_, A> {
45    /// The configured roles.
46    pub fn roles(&self) -> &Roles {
47        &self.plugin.roles
48    }
49
50    /// Creates an organization owned by `user_id` (which replaces `input.user_id`). Ignores
51    /// `allow_user_to_create_organization`, but not `organization_limit`. Runs hooks on
52    /// `CreateOrganization` and emits `OrganizationCreated` and `MemberAdded`.
53    pub async fn create(
54        &self,
55        user_id: &Id,
56        input: CreateOrganizationInput,
57    ) -> Result<OrganizationWithMembers, AuthError> {
58        let input = CreateOrganizationInput {
59            user_id: Some(user_id.clone()),
60            ..input
61        };
62        Ok(self
63            .auth
64            .api()
65            .call(&CreateOrganization::server(), input)
66            .await?
67            .data)
68    }
69
70    /// Adds a user to an organization without an invitation. `role` is one role or a
71    /// comma-separated list; each must exist. Runs hooks on `AddMember` and emits
72    /// `MemberAdded`.
73    pub async fn add_member(
74        &self,
75        organization_id: &Id,
76        user_id: &Id,
77        role: &str,
78    ) -> Result<Member, AuthError> {
79        let input = NewMember {
80            organization_id: organization_id.clone(),
81            user_id: user_id.clone(),
82            role: role.into(),
83        };
84        Ok(self.auth.api().call(&AddMember, input).await?.data)
85    }
86
87    /// Whether the user's role in the organization grants `permissions`; `false` when they
88    /// aren't a member.
89    pub async fn has_permission(
90        &self,
91        organization_id: &Id,
92        user_id: &Id,
93        permissions: &[(&str, &[&str])],
94    ) -> Result<bool, AuthError> {
95        let input = PermissionCheck {
96            organization_id: organization_id.clone(),
97            user_id: user_id.clone(),
98            permissions: permissions
99                .iter()
100                .map(|(resource, actions)| {
101                    let actions = actions.iter().map(|a| (*a).to_owned()).collect();
102                    ((*resource).to_owned(), actions)
103                })
104                .collect::<BTreeMap<_, _>>(),
105        };
106        Ok(self.auth.api().call(&CheckPermission, input).await?.data)
107    }
108
109    /// Pending invitations addressed to `email`, with their organizations' names.
110    pub async fn invitations_for_email(
111        &self,
112        email: &str,
113    ) -> Result<Vec<InvitationWithOrganization>, AuthError> {
114        let input = EmailQuery {
115            email: email.to_owned(),
116        };
117        Ok(self.auth.api().call(&UserInvitations, input).await?.data)
118    }
119}
120
121macro_rules! session_calls {
122    ($($route:literal $name:ident($endpoint:expr, $input:ty) -> $output:ty;)*) => {
123        impl<A: AuthInstance> OrganizationApi<'_, A> {
124            $(
125                #[doc = concat!("`", $route, "` as the session in `headers`.")]
126                pub async fn $name(
127                    &self,
128                    headers: &HeaderMap,
129                    input: $input,
130                ) -> Result<ApiResponse<$output>, AuthError> {
131                    self.auth.api().headers(headers).call(&$endpoint, input).await
132                }
133            )*
134        }
135    };
136}
137
138session_calls! {
139    "POST /organization/create" create_as(CreateOrganization::client(), CreateOrganizationInput) -> OrganizationWithMembers;
140    "POST /organization/update" update(UpdateOrganization, UpdateOrganizationInput) -> OrganizationRow;
141    "POST /organization/delete" delete(DeleteOrganization, DeleteOrganizationInput) -> OrganizationRow;
142    "GET /organization/list" list(ListOrganizations, Empty) -> Vec<OrganizationRow>;
143    "GET /organization/get-full-organization" get_full(GetFullOrganization, GetFullOrganizationQuery) -> Option<FullOrganization>;
144    "POST /organization/set-active" set_active(SetActiveOrganization, SetActiveOrganizationInput) -> Option<OrganizationRow>;
145    "POST /organization/check-slug" check_slug(CheckSlug, CheckSlugInput) -> Status;
146    "POST /organization/invite-member" invite_member(InviteMember, InviteMemberInput) -> Invitation;
147    "POST /organization/accept-invitation" accept_invitation(AcceptInvitation, InvitationIdInput) -> InvitationResponse;
148    "POST /organization/reject-invitation" reject_invitation(RejectInvitation, InvitationIdInput) -> InvitationResponse;
149    "POST /organization/cancel-invitation" cancel_invitation(CancelInvitation, InvitationIdInput) -> Invitation;
150    "GET /organization/get-invitation" get_invitation(GetInvitation, InvitationIdQuery) -> InvitationDetails;
151    "GET /organization/list-invitations" list_invitations(ListInvitations, OrganizationIdQuery) -> Vec<Invitation>;
152    "GET /organization/list-user-invitations" list_user_invitations(ListUserInvitations, Empty) -> Vec<InvitationWithOrganization>;
153    "POST /organization/remove-member" remove_member(RemoveMember, RemoveMemberInput) -> RemoveMemberOutput;
154    "POST /organization/update-member-role" update_member_role(UpdateMemberRole, UpdateMemberRoleInput) -> Member;
155    "POST /organization/leave" leave(LeaveOrganization, LeaveOrganizationInput) -> Member;
156    "GET /organization/get-active-member" get_active_member(GetActiveMember, Empty) -> MemberWithUser;
157    "GET /organization/list-members" list_members(ListMembers, ListMembersQuery) -> ListMembersOutput;
158    "POST /organization/has-permission" check_permission(HasPermission, HasPermissionInput) -> HasPermissionOutput;
159}