Skip to main content

fastauth_plugin_organization/
model.rs

1//! The organization plugin's tables and the column it adds to `session`.
2
3use fastauth_core::plugin_prelude::*;
4use serde_json::{Map, Value as JsonValue};
5
6/// A row of `organization`. Named `OrganizationRow` because `Organization` is the plugin.
7#[derive(Model, Clone, Debug, PartialEq, Serialize)]
8#[model(table = "organization")]
9#[serde(rename_all = "camelCase")]
10pub struct OrganizationRow {
11    #[model(id)]
12    pub id: Id,
13    pub name: String,
14    /// Unique across organizations; clients can address an organization by it.
15    #[model(unique)]
16    pub slug: String,
17    pub logo: Option<String>,
18    /// Free-form JSON the app attaches to the organization.
19    pub metadata: Option<Json<Map<String, JsonValue>>>,
20    #[model(default = now)]
21    #[serde(with = "time::serde::rfc3339")]
22    pub created_at: OffsetDateTime,
23}
24
25/// A row of `member`: one user's membership and role in one organization. A user is a
26/// member of an organization at most once; the plugin checks that before every insert.
27#[derive(Model, Clone, Debug, PartialEq, Serialize)]
28#[model(table = "member")]
29#[serde(rename_all = "camelCase")]
30pub struct Member {
31    #[model(id)]
32    pub id: Id,
33    #[model(references = OrganizationRow, on_delete = Cascade, index)]
34    pub organization_id: Id,
35    #[model(references = User, on_delete = Cascade, index)]
36    pub user_id: Id,
37    /// One role or several, comma-separated (`"admin,billing"`), as Better Auth stores them.
38    #[model(default = "member")]
39    pub role: String,
40    #[model(default = now)]
41    #[serde(with = "time::serde::rfc3339")]
42    pub created_at: OffsetDateTime,
43}
44
45impl Member {
46    /// The member's roles, split from the stored comma-separated list.
47    pub fn roles(&self) -> impl Iterator<Item = &str> {
48        crate::access::role_list(&self.role)
49    }
50
51    /// Whether one of the member's roles is `role`.
52    pub fn has_role(&self, role: &str) -> bool {
53        self.roles().any(|r| r == role)
54    }
55}
56
57/// Where an invitation stands. Only `Pending` invitations can be accepted, rejected or
58/// resent.
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(rename_all = "lowercase")]
61pub enum InvitationStatus {
62    Pending,
63    Accepted,
64    Rejected,
65    Canceled,
66}
67
68impl InvitationStatus {
69    /// The stored and serialized name: `"pending"`, `"accepted"`, `"rejected"`, `"canceled"`.
70    pub const fn as_str(self) -> &'static str {
71        match self {
72            Self::Pending => "pending",
73            Self::Accepted => "accepted",
74            Self::Rejected => "rejected",
75            Self::Canceled => "canceled",
76        }
77    }
78}
79
80impl ColumnValue for InvitationStatus {
81    const TYPE: ColumnType = ColumnType::Text;
82
83    fn into_value(self) -> Value {
84        Value::Text(self.as_str().to_owned())
85    }
86
87    fn from_value(value: Value) -> Result<Self, String> {
88        match value {
89            Value::Text(text) => match text.as_str() {
90                "pending" => Ok(Self::Pending),
91                "accepted" => Ok(Self::Accepted),
92                "rejected" => Ok(Self::Rejected),
93                "canceled" => Ok(Self::Canceled),
94                other => Err(format!("unknown invitation status `{other}`")),
95            },
96            other => Err(format!("expected Text, got {other:?}")),
97        }
98    }
99}
100
101/// A row of `invitation`. Its id is the secret in the invitation link.
102#[derive(Model, Clone, Debug, PartialEq, Serialize)]
103#[model(table = "invitation")]
104#[serde(rename_all = "camelCase")]
105pub struct Invitation {
106    #[model(id)]
107    pub id: Id,
108    #[model(references = OrganizationRow, on_delete = Cascade, index)]
109    pub organization_id: Id,
110    /// Lowercased. Only a user signed in with this email can accept or reject it.
111    #[model(index)]
112    pub email: String,
113    /// The role or comma-separated roles the invitee gets on accepting.
114    pub role: String,
115    #[model(default = "pending")]
116    pub status: InvitationStatus,
117    #[model(references = User, on_delete = Cascade)]
118    pub inviter_id: Id,
119    #[serde(with = "time::serde::rfc3339")]
120    pub expires_at: OffsetDateTime,
121    #[model(default = now)]
122    #[serde(with = "time::serde::rfc3339")]
123    pub created_at: OffsetDateTime,
124}
125
126/// The column the plugin adds to `session`. Clients see it as `activeOrganizationId`;
127/// handlers read it with `session.session_plugin::<Organization, _>()`.
128#[derive(Fields, Clone, Debug, Default, PartialEq)]
129#[fields(table = Session)]
130pub struct OrganizationSession {
131    /// The organization `/organization/set-active` chose, which endpoints without an
132    /// explicit `organizationId` act on.
133    pub active_organization_id: Option<Id>,
134}
135
136/// The user part of a member in list responses: `{ id, name, email, image }`.
137#[derive(Clone, Debug, PartialEq, Serialize)]
138pub struct MemberUser {
139    pub id: Id,
140    pub name: String,
141    pub email: String,
142    pub image: Option<String>,
143}
144
145/// A member with its user, as `/organization/list-members` and
146/// `/organization/get-active-member` answer.
147#[derive(Clone, Debug, PartialEq, Serialize)]
148pub struct MemberWithUser {
149    #[serde(flatten)]
150    pub member: Member,
151    pub user: MemberUser,
152}