better-auth-api 0.10.0

Plugin implementations for better-auth
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
pub mod handlers;
pub mod rbac;
pub mod types;

use std::collections::HashMap;

use async_trait::async_trait;
use better_auth_core::adapters::DatabaseAdapter;
use better_auth_core::error::AuthResult;
use better_auth_core::plugin::{AuthContext, AuthPlugin, AuthRoute};
use better_auth_core::types::{AuthRequest, AuthResponse, HttpMethod};

#[cfg(feature = "axum")]
use better_auth_core::plugin::{AuthState, AxumPlugin};

/// Permission definitions for a role
#[derive(Debug, Clone, Default)]
pub struct RolePermissions {
    pub organization: Vec<String>,
    pub member: Vec<String>,
    pub invitation: Vec<String>,
}

/// Configuration for the Organization plugin
#[derive(Debug, Clone, better_auth_core::PluginConfig)]
#[plugin(name = "OrganizationPlugin")]
pub struct OrganizationConfig {
    /// Allow users to create organizations (default: true)
    #[config(default = true)]
    pub allow_user_to_create_organization: bool,
    /// Maximum organizations per user (None = unlimited)
    #[config(default = None)]
    pub organization_limit: Option<usize>,
    /// Maximum members per organization (None = unlimited)
    #[config(default = Some(100))]
    pub membership_limit: Option<usize>,
    /// Role assigned to organization creator (default: "owner")
    #[config(default = "owner".to_string())]
    pub creator_role: String,
    /// Invitation expiration in seconds (default: 48 hours)
    #[config(default = 60 * 60 * 48)]
    pub invitation_expires_in: u64,
    /// Maximum pending invitations per organization (None = unlimited)
    #[config(default = Some(100))]
    pub invitation_limit: Option<usize>,
    /// Disable organization deletion (default: false)
    #[config(default = false)]
    pub disable_organization_deletion: bool,
    /// Custom role definitions (extending default roles)
    #[config(default = HashMap::new(), skip)]
    pub roles: HashMap<String, RolePermissions>,
}

/// Organization plugin for multi-tenancy support
pub struct OrganizationPlugin {
    config: OrganizationConfig,
}

#[async_trait]
impl<DB: DatabaseAdapter> AuthPlugin<DB> for OrganizationPlugin {
    fn name(&self) -> &'static str {
        "organization"
    }

    fn routes(&self) -> Vec<AuthRoute> {
        vec![
            // Organization CRUD
            AuthRoute::post("/organization/create", "create_organization"),
            AuthRoute::post("/organization/update", "update_organization"),
            AuthRoute::post("/organization/delete", "delete_organization"),
            AuthRoute::get("/organization/list", "list_organizations"),
            AuthRoute::get(
                "/organization/get-full-organization",
                "get_full_organization",
            ),
            AuthRoute::post("/organization/check-slug", "check_slug"),
            AuthRoute::post("/organization/set-active", "set_active_organization"),
            AuthRoute::post("/organization/leave", "leave_organization"),
            // Member management
            AuthRoute::get("/organization/get-active-member", "get_active_member"),
            AuthRoute::get("/organization/list-members", "list_members"),
            AuthRoute::post("/organization/remove-member", "remove_member"),
            AuthRoute::post("/organization/update-member-role", "update_member_role"),
            // Invitations
            AuthRoute::post("/organization/invite-member", "invite_member"),
            AuthRoute::get("/organization/get-invitation", "get_invitation"),
            AuthRoute::get("/organization/list-invitations", "list_invitations"),
            AuthRoute::get(
                "/organization/list-user-invitations",
                "list_user_invitations",
            ),
            AuthRoute::post("/organization/accept-invitation", "accept_invitation"),
            AuthRoute::post("/organization/reject-invitation", "reject_invitation"),
            AuthRoute::post("/organization/cancel-invitation", "cancel_invitation"),
            // Permission check
            AuthRoute::post("/organization/has-permission", "has_permission"),
        ]
    }

    async fn on_request(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<DB>,
    ) -> AuthResult<Option<AuthResponse>> {
        match (req.method(), req.path()) {
            // Organization CRUD
            (HttpMethod::Post, "/organization/create") => Ok(Some(
                handlers::org::handle_create_organization(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/update") => Ok(Some(
                handlers::org::handle_update_organization(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/delete") => Ok(Some(
                handlers::org::handle_delete_organization(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Get, "/organization/list") => Ok(Some(
                handlers::org::handle_list_organizations(req, ctx).await?,
            )),
            (HttpMethod::Get, "/organization/get-full-organization") => Ok(Some(
                handlers::org::handle_get_full_organization(req, ctx).await?,
            )),
            (HttpMethod::Post, "/organization/check-slug") => {
                Ok(Some(handlers::org::handle_check_slug(req, ctx).await?))
            }
            (HttpMethod::Post, "/organization/set-active") => Ok(Some(
                handlers::org::handle_set_active_organization(req, ctx).await?,
            )),
            (HttpMethod::Post, "/organization/leave") => Ok(Some(
                handlers::org::handle_leave_organization(req, ctx).await?,
            )),
            // Member management
            (HttpMethod::Get, "/organization/get-active-member") => Ok(Some(
                handlers::member::handle_get_active_member(req, ctx).await?,
            )),
            (HttpMethod::Get, "/organization/list-members") => {
                Ok(Some(handlers::member::handle_list_members(req, ctx).await?))
            }
            (HttpMethod::Post, "/organization/remove-member") => Ok(Some(
                handlers::member::handle_remove_member(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/update-member-role") => Ok(Some(
                handlers::member::handle_update_member_role(req, ctx, &self.config).await?,
            )),
            // Invitations
            (HttpMethod::Post, "/organization/invite-member") => Ok(Some(
                handlers::invitation::handle_invite_member(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Get, "/organization/get-invitation") => Ok(Some(
                handlers::invitation::handle_get_invitation(req, ctx).await?,
            )),
            (HttpMethod::Get, "/organization/list-invitations") => Ok(Some(
                handlers::invitation::handle_list_invitations(req, ctx).await?,
            )),
            (HttpMethod::Get, "/organization/list-user-invitations") => Ok(Some(
                handlers::invitation::handle_list_user_invitations(req, ctx).await?,
            )),
            (HttpMethod::Post, "/organization/accept-invitation") => Ok(Some(
                handlers::invitation::handle_accept_invitation(req, ctx, &self.config).await?,
            )),
            (HttpMethod::Post, "/organization/reject-invitation") => Ok(Some(
                handlers::invitation::handle_reject_invitation(req, ctx).await?,
            )),
            (HttpMethod::Post, "/organization/cancel-invitation") => Ok(Some(
                handlers::invitation::handle_cancel_invitation(req, ctx, &self.config).await?,
            )),
            // Permission check
            (HttpMethod::Post, "/organization/has-permission") => Ok(Some(
                handlers::handle_has_permission(req, ctx, &self.config).await?,
            )),
            _ => Ok(None),
        }
    }
}

// ---------------------------------------------------------------------------
// Axum-native routing (feature-gated)
// ---------------------------------------------------------------------------

#[cfg(feature = "axum")]
mod axum_impl {
    use super::*;
    use std::sync::Arc;

    use axum::Json;
    use axum::extract::{Extension, Query, State};
    use better_auth_core::error::AuthError;
    use better_auth_core::extractors::{CurrentSession, ValidatedJson};

    use super::handlers::has_permission_core;
    use super::handlers::invitation::{
        accept_invitation_core, cancel_invitation_core, get_invitation_core, invite_member_core,
        list_invitations_core, list_user_invitations_core, reject_invitation_core,
    };
    use super::handlers::member::{
        get_active_member_core, list_members_core, remove_member_core, update_member_role_core,
    };
    use super::handlers::org::{
        check_slug_core, create_organization_core, delete_organization_core,
        get_full_organization_core, leave_organization_core, list_organizations_core,
        set_active_organization_core, update_organization_core,
    };
    use super::types::*;

    #[derive(Clone)]
    struct PluginState {
        config: OrganizationConfig,
    }

    // -- Organization CRUD --

    async fn handle_create_organization<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Extension(ps): Extension<Arc<PluginState>>,
        CurrentSession { user, .. }: CurrentSession<DB>,
        ValidatedJson(body): ValidatedJson<CreateOrganizationRequest>,
    ) -> Result<Json<CreateOrganizationResponse<DB::Organization, MemberResponse>>, AuthError> {
        let ctx = state.to_context();
        let result = create_organization_core(&body, &user, &ps.config, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_update_organization<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Extension(ps): Extension<Arc<PluginState>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        ValidatedJson(body): ValidatedJson<UpdateOrganizationRequest>,
    ) -> Result<Json<DB::Organization>, AuthError> {
        let ctx = state.to_context();
        let result = update_organization_core(&body, &user, &session, &ps.config, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_delete_organization<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Extension(ps): Extension<Arc<PluginState>>,
        CurrentSession { user, .. }: CurrentSession<DB>,
        Json(body): Json<DeleteOrganizationRequest>,
    ) -> Result<Json<SuccessResponse>, AuthError> {
        let ctx = state.to_context();
        let result = delete_organization_core(&body, &user, &ps.config, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_list_organizations<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { user, .. }: CurrentSession<DB>,
    ) -> Result<Json<Vec<DB::Organization>>, AuthError> {
        let ctx = state.to_context();
        let result = list_organizations_core(&user, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_get_full_organization<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        Query(query): Query<GetFullOrganizationQuery>,
    ) -> Result<Json<FullOrganizationResponse<DB::Organization, DB::Invitation>>, AuthError> {
        let ctx = state.to_context();
        let result = get_full_organization_core(&query, &user, &session, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_check_slug<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { .. }: CurrentSession<DB>,
        Json(body): Json<CheckSlugRequest>,
    ) -> Result<Json<CheckSlugResponse>, AuthError> {
        let ctx = state.to_context();
        let result = check_slug_core(&body, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_set_active_organization<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        Json(body): Json<SetActiveOrganizationRequest>,
    ) -> Result<Json<DB::Session>, AuthError> {
        let ctx = state.to_context();
        let result = set_active_organization_core(&body, &user, &session, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_leave_organization<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        Json(body): Json<LeaveOrganizationRequest>,
    ) -> Result<Json<SuccessResponse>, AuthError> {
        let ctx = state.to_context();
        let result = leave_organization_core(&body, &user, &session, &ctx).await?;
        Ok(Json(result))
    }

    // -- Member management --

    async fn handle_get_active_member<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
    ) -> Result<Json<MemberResponse>, AuthError> {
        let ctx = state.to_context();
        let result = get_active_member_core(&user, &session, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_list_members<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        Query(query): Query<ListMembersQuery>,
    ) -> Result<Json<ListMembersResponse>, AuthError> {
        let ctx = state.to_context();
        let result = list_members_core(&query, &user, &session, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_remove_member<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Extension(ps): Extension<Arc<PluginState>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        Json(body): Json<RemoveMemberRequest>,
    ) -> Result<Json<RemovedMemberResponse>, AuthError> {
        let ctx = state.to_context();
        let result = remove_member_core(&body, &user, &session, &ps.config, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_update_member_role<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Extension(ps): Extension<Arc<PluginState>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        Json(body): Json<UpdateMemberRoleRequest>,
    ) -> Result<Json<MemberWrappedResponse>, AuthError> {
        let ctx = state.to_context();
        let result = update_member_role_core(&body, &user, &session, &ps.config, &ctx).await?;
        Ok(Json(result))
    }

    // -- Invitations --

    async fn handle_invite_member<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Extension(ps): Extension<Arc<PluginState>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        ValidatedJson(body): ValidatedJson<InviteMemberRequest>,
    ) -> Result<Json<DB::Invitation>, AuthError> {
        let ctx = state.to_context();
        let result = invite_member_core(&body, &user, &session, &ps.config, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_get_invitation<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Query(query): Query<GetInvitationQuery>,
    ) -> Result<Json<GetInvitationResponse<DB::Invitation>>, AuthError> {
        let ctx = state.to_context();
        let result = get_invitation_core(&query, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_list_invitations<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        Query(query): Query<ListInvitationsQuery>,
    ) -> Result<Json<Vec<DB::Invitation>>, AuthError> {
        let ctx = state.to_context();
        let result = list_invitations_core(&query, &user, &session, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_list_user_invitations<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { user, .. }: CurrentSession<DB>,
    ) -> Result<Json<Vec<DB::Invitation>>, AuthError> {
        let ctx = state.to_context();
        let result = list_user_invitations_core(&user, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_accept_invitation<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Extension(ps): Extension<Arc<PluginState>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        Json(body): Json<AcceptInvitationRequest>,
    ) -> Result<Json<AcceptInvitationResponse<DB::Invitation>>, AuthError> {
        let ctx = state.to_context();
        let result = accept_invitation_core(&body, &user, &session, &ps.config, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_reject_invitation<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        CurrentSession { user, .. }: CurrentSession<DB>,
        Json(body): Json<RejectInvitationRequest>,
    ) -> Result<Json<SuccessResponse>, AuthError> {
        let ctx = state.to_context();
        let result = reject_invitation_core(&body, &user, &ctx).await?;
        Ok(Json(result))
    }

    async fn handle_cancel_invitation<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Extension(ps): Extension<Arc<PluginState>>,
        CurrentSession { user, .. }: CurrentSession<DB>,
        Json(body): Json<CancelInvitationRequest>,
    ) -> Result<Json<SuccessResponse>, AuthError> {
        let ctx = state.to_context();
        let result = cancel_invitation_core(&body, &user, &ps.config, &ctx).await?;
        Ok(Json(result))
    }

    // -- Permission check --

    async fn handle_has_permission<DB: DatabaseAdapter>(
        State(state): State<AuthState<DB>>,
        Extension(ps): Extension<Arc<PluginState>>,
        CurrentSession { user, session, .. }: CurrentSession<DB>,
        Json(body): Json<HasPermissionRequest>,
    ) -> Result<Json<HasPermissionResponse>, AuthError> {
        let ctx = state.to_context();
        let result = has_permission_core(&body, &user, &session, &ps.config, &ctx).await?;
        Ok(Json(result))
    }

    // -- AxumPlugin impl --

    #[async_trait]
    impl<DB: DatabaseAdapter> AxumPlugin<DB> for OrganizationPlugin {
        fn name(&self) -> &'static str {
            "organization"
        }

        fn router(&self) -> axum::Router<AuthState<DB>> {
            use axum::routing::{get, post};

            let plugin_state = Arc::new(PluginState {
                config: self.config.clone(),
            });

            axum::Router::new()
                // Organization CRUD
                .route(
                    "/organization/create",
                    post(handle_create_organization::<DB>),
                )
                .route(
                    "/organization/update",
                    post(handle_update_organization::<DB>),
                )
                .route(
                    "/organization/delete",
                    post(handle_delete_organization::<DB>),
                )
                .route("/organization/list", get(handle_list_organizations::<DB>))
                .route(
                    "/organization/get-full-organization",
                    get(handle_get_full_organization::<DB>),
                )
                .route("/organization/check-slug", post(handle_check_slug::<DB>))
                .route(
                    "/organization/set-active",
                    post(handle_set_active_organization::<DB>),
                )
                .route("/organization/leave", post(handle_leave_organization::<DB>))
                // Member management
                .route(
                    "/organization/get-active-member",
                    get(handle_get_active_member::<DB>),
                )
                .route("/organization/list-members", get(handle_list_members::<DB>))
                .route(
                    "/organization/remove-member",
                    post(handle_remove_member::<DB>),
                )
                .route(
                    "/organization/update-member-role",
                    post(handle_update_member_role::<DB>),
                )
                // Invitations
                .route(
                    "/organization/invite-member",
                    post(handle_invite_member::<DB>),
                )
                .route(
                    "/organization/get-invitation",
                    get(handle_get_invitation::<DB>),
                )
                .route(
                    "/organization/list-invitations",
                    get(handle_list_invitations::<DB>),
                )
                .route(
                    "/organization/list-user-invitations",
                    get(handle_list_user_invitations::<DB>),
                )
                .route(
                    "/organization/accept-invitation",
                    post(handle_accept_invitation::<DB>),
                )
                .route(
                    "/organization/reject-invitation",
                    post(handle_reject_invitation::<DB>),
                )
                .route(
                    "/organization/cancel-invitation",
                    post(handle_cancel_invitation::<DB>),
                )
                // Permission check
                .route(
                    "/organization/has-permission",
                    post(handle_has_permission::<DB>),
                )
                .layer(Extension(plugin_state))
        }
    }
}