better-auth-api 1.0.0-alpha.5

Plugin implementations for better-auth
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
use better_auth_core::error::{AuthError, AuthResult};
use better_auth_core::plugin::{AuthContext, AuthRoute};
use better_auth_core::types::{AuthRequest, AuthResponse, HttpMethod, Team};
use serde::Deserialize;
use validator::Validate;

use super::{require_native_session, resolve_organization_id};
use crate::plugins::organization::hooks::*;
use crate::plugins::organization::types::{NullableStringField, deserialize_nullable_string_field};
use crate::plugins::organization::{OrganizationConfig, rbac::check_permission};

mod lifecycle;

#[cfg(test)]
#[path = "team_input_tests.rs"]
mod input_tests;

use crate::plugins::organization::request::{from_fields, object, take};
use better_auth_core::{AuthRecordFields, FieldMap, FieldValue, FromFieldMap};

from_fields!(CreateBody { name: "name", organization_id: "organizationId" }; additional_fields);
from_fields!(UpdateData { name: "name", organization_id: "organizationId" }; additional_fields);
from_fields!(TeamBody {
    team_id: "teamId",
    organization_id: "organizationId"
});
from_fields!(MemberBody {
    team_id: "teamId",
    user_id: "userId",
    organization_id: "organizationId"
});
from_fields!(ActiveBody { team_id: "teamId" });

impl FromFieldMap for UpdateBody {
    fn from_field_values(mut fields: FieldMap) -> AuthResult<Self> {
        Ok(Self {
            team_id: take(&mut fields, "teamId")?,
            data: UpdateData::from_field_values(object(&mut fields, "data")?)?,
        })
    }
}

pub(crate) fn routes() -> Vec<AuthRoute> {
    vec![
        AuthRoute::post("/organization/create-team", "createTeam"),
        AuthRoute::post("/organization/update-team", "updateTeam").require_headers(true),
        AuthRoute::post("/organization/remove-team", "removeTeam"),
        AuthRoute::post("/organization/set-active-team", "setActiveTeam").require_headers(true),
        AuthRoute::post("/organization/add-team-member", "addTeamMember").require_headers(true),
        AuthRoute::post("/organization/remove-team-member", "removeTeamMember")
            .require_headers(true),
        AuthRoute::get("/organization/list-teams", "listOrganizationTeams")
            .require_headers(true)
            .query_validator(crate::plugins::query_input::organization_id),
        AuthRoute::get("/organization/list-user-teams", "listUserTeams")
            .require_headers(true)
            .query_validator(crate::plugins::query_input::user_teams),
        AuthRoute::get("/organization/list-team-members", "listTeamMembers")
            .require_headers(true)
            .query_validator(crate::plugins::query_input::team_members),
    ]
}

#[derive(Clone, Deserialize, serde::Serialize, Validate)]
#[serde(rename_all = "camelCase")]
pub(in crate::plugins::organization) struct CreateBody {
    #[serde(flatten)]
    #[serde(with = "better_auth_core::field_value::serde::map")]
    additional_fields: better_auth_core::FieldMap,
    #[serde(
        default,
        skip_serializing_if = "better_auth_core::SchemaValue::is_json_omitted"
    )]
    name: better_auth_core::SchemaValue<String>,
    #[serde(
        default,
        deserialize_with = "deserialize_nullable_string_field",
        skip_serializing_if = "NullableStringField::is_missing"
    )]
    organization_id: NullableStringField,
}
#[derive(Clone, Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
pub(in crate::plugins::organization) struct TeamBody {
    team_id: String,
    organization_id: Option<String>,
}
#[derive(Clone, Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
pub(in crate::plugins::organization) struct MemberBody {
    team_id: String,
    user_id: String,
    organization_id: Option<String>,
}
#[derive(Clone, Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
pub(in crate::plugins::organization) struct UpdateBody {
    team_id: String,
    data: UpdateData,
}
#[derive(Clone, Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub(in crate::plugins::organization) struct UpdateData {
    #[serde(flatten)]
    #[serde(with = "better_auth_core::field_value::serde::map")]
    additional_fields: better_auth_core::FieldMap,
    #[serde(
        default,
        skip_serializing_if = "better_auth_core::SchemaValue::is_json_omitted"
    )]
    name: better_auth_core::SchemaValue<String>,
    #[serde(
        default,
        deserialize_with = "deserialize_nullable_string_field",
        skip_serializing_if = "NullableStringField::is_missing"
    )]
    organization_id: NullableStringField,
}

fn optional_string(value: NullableStringField, path: &str) -> AuthResult<Option<String>> {
    match value {
        NullableStringField::Missing => Ok(None),
        NullableStringField::Value(value) => Ok(Some(value)),
        NullableStringField::Null => Err(AuthError::RequestValidation {
            message: format!("[{path}] Invalid input: expected string, received null"),
        }),
    }
}

#[derive(Clone, Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
pub(in crate::plugins::organization) struct ActiveBody {
    #[serde(
        default,
        deserialize_with = "crate::plugins::organization::types::deserialize_nullable_string_field"
    )]
    team_id: crate::plugins::organization::types::NullableStringField,
}

pub(crate) async fn find_team(
    team_id: &FieldValue,
    organization_id: &FieldValue,
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    config: &OrganizationConfig,
) -> AuthResult<Team> {
    let details = ctx
        .database
        .get_team_details_value(team_id, Some(organization_id), false)
        .await?
        .ok_or_else(|| AuthError::from_code("BAD_REQUEST", "TEAM_NOT_FOUND", "Team not found"))?;
    Ok(details.into_public_parts(&config.schema.team)?.0)
}

fn public_teams(teams: Vec<Team>, config: &OrganizationConfig) -> AuthResult<Vec<Team>> {
    teams
        .into_iter()
        .map(|team| crate::plugins::organization::fields::team(team, config))
        .collect()
}

fn teams_response(teams: Vec<Team>) -> AuthResult<AuthResponse> {
    let teams = teams
        .into_iter()
        .map(|team| team.field_values().map(FieldValue::from))
        .collect::<AuthResult<Vec<_>>>()?;
    Ok(AuthResponse::native(None, teams.into()))
}

async fn list_teams(
    organization_id: &FieldValue,
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    config: &OrganizationConfig,
) -> AuthResult<Vec<Team>> {
    public_teams(
        ctx.database
            .list_organization_teams_value(organization_id)
            .await?,
        config,
    )
}

async fn authorize(
    member: &better_auth_core::Member,
    org_id: &FieldValue,
    permission: (&str, &str),
    error: AuthError,
    config: &OrganizationConfig,
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
) -> AuthResult<()> {
    if !check_permission(
        member.role.typed()?,
        org_id,
        permission.0,
        &[permission.1],
        config,
        ctx,
    )
    .await?
    {
        return Err(error);
    }
    Ok(())
}

pub(crate) async fn handle_team_request(
    req: &AuthRequest,
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    config: &OrganizationConfig,
) -> AuthResult<Option<AuthResponse>> {
    match (req.method(), req.path()) {
        (HttpMethod::Post, "/organization/create-team") => {
            return lifecycle::create(req, ctx, config).await.map(Some);
        }
        (HttpMethod::Post, "/organization/remove-team") => {
            return lifecycle::remove(req, ctx, config).await.map(Some);
        }
        _ => {}
    }
    let data = require_native_session(req, ctx).await?;
    let session = &data;
    macro_rules! body {
        ($ty:ty) => {
            super::super::request::read::<$ty>(req, &config.schema)?
        };
    }
    let response = match (req.method(), req.path()) {
        (HttpMethod::Post, "/organization/update-team") => {
            let body = body!(UpdateBody);
            let additional_fields = body.data.additional_fields.clone();
            let name = (!body.data.name.is_undefined()).then_some(body.data.name);
            let organization_id =
                optional_string(body.data.organization_id, "body.data.organizationId")?;
            let org = resolve_organization_id(
                organization_id.as_deref(),
                session,
                AuthError::from_code(
                    "BAD_REQUEST",
                    "NO_ACTIVE_ORGANIZATION",
                    "No active organization",
                ),
            )?;
            let member = ctx
                .database
                .get_member_with_user_value(&org, &data.user_property("id")?)
                .await?
                .ok_or_else(|| {
                    AuthError::from_code(
                        "FORBIDDEN",
                        "YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM",
                        "You are not allowed to update this team",
                    )
                })?;
            authorize(
                &member.member,
                &org,
                ("team", "update"),
                AuthError::from_code(
                    "FORBIDDEN",
                    "YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM",
                    "You are not allowed to update this team",
                ),
                config,
                ctx,
            )
            .await?;
            let team = find_team(&body.team_id.as_str().into(), &org, ctx, config).await?;
            if !team.organization_id.field_value().strict_equals(&org) {
                return Err(AuthError::from_code(
                    "BAD_REQUEST",
                    "TEAM_NOT_FOUND",
                    "Team not found",
                ));
            }
            let organization = ctx
                .database
                .get_organization_by_id_value(&org)
                .await?
                .ok_or_else(|| {
                    AuthError::from_code(
                        "BAD_REQUEST",
                        "ORGANIZATION_NOT_FOUND",
                        "Organization not found",
                    )
                })?;
            let organization_view =
                crate::plugins::organization::fields::organization(&organization, ctx)?;
            let mut updates = better_auth_core::UpdateTeam {
                additional_fields,
                name,
                ..Default::default()
            };
            if let Some(hooks) = &config.hooks {
                hooks
                    .before_update_team(
                        &mut updates,
                        OrganizationTeamEvent {
                            team: &team,
                            user: Some(&data.user_value()?),
                            organization: &organization_view,
                        },
                    )
                    .await?;
            }
            let updated = ctx
                .database
                .update_team_value(&team.id.field_value(), updates)
                .await?;
            let updated = crate::plugins::organization::fields::team(updated, config)?;
            if let Some(hooks) = &config.hooks {
                hooks
                    .after_update_team(OrganizationTeamEvent {
                        team: &updated,
                        user: Some(&data.user_value()?),
                        organization: &organization_view,
                    })
                    .await?;
            }
            AuthResponse::native(None, updated.field_values()?.into())
        }
        (HttpMethod::Get, "/organization/list-teams") => {
            let org = resolve_organization_id(
                req.query_string("organizationId")?.as_deref(),
                session,
                AuthError::from_code(
                    "BAD_REQUEST",
                    "NO_ACTIVE_ORGANIZATION",
                    "No active organization",
                ),
            )?;
            if ctx
                .database
                .get_member_with_user_value(&org, &data.user_property("id")?)
                .await?
                .is_none()
            {
                return Err(AuthError::from_code(
                    "FORBIDDEN",
                    "YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION",
                    "You are not allowed to access this organization as an owner",
                ));
            }
            teams_response(list_teams(&org, ctx, config).await?)?
        }
        (HttpMethod::Post, "/organization/set-active-team") => {
            use crate::plugins::organization::types::NullableStringField;
            let body = body!(ActiveBody);
            let team_id = match body.team_id {
                NullableStringField::Null => {
                    if !session.session_property("activeTeamId")?.is_truthy() {
                        return Ok(Some(AuthResponse::json(None, &serde_json::Value::Null)?));
                    }
                    let updated = ctx
                        .database
                        .update_session_active_team_by_token_value(
                            &session.session_property("token")?,
                            None,
                        )
                        .await?;
                    let manager = ctx.session_manager();
                    manager
                        .set_native_session_cookie(req, data.with_session(updated)?, None)
                        .await?;
                    return Ok(Some(AuthResponse::json(None, &serde_json::Value::Null)?));
                }
                NullableStringField::Value(id) if !id.is_empty() => FieldValue::from(id),
                _ => session.session_property("activeTeamId")?,
            };
            if !team_id.is_truthy() {
                return Ok(Some(AuthResponse::json(None, &serde_json::Value::Null)?));
            }
            let org = resolve_organization_id(
                None,
                session,
                AuthError::from_code(
                    "BAD_REQUEST",
                    "NO_ACTIVE_ORGANIZATION",
                    "No active organization",
                ),
            )?;
            let team = find_team(&team_id, &org, ctx, config).await?;
            if ctx
                .database
                .get_team_member_value(&team_id, &data.user_property("id")?)
                .await?
                .is_none()
            {
                return Err(AuthError::from_code(
                    "FORBIDDEN",
                    "USER_IS_NOT_A_MEMBER_OF_THE_TEAM",
                    "User is not a member of the team",
                ));
            }
            let updated = ctx
                .database
                .update_session_active_team_by_token_value(
                    &session.session_property("token")?,
                    Some(&team.id.field_value()),
                )
                .await?;
            let manager = ctx.session_manager();
            manager
                .set_native_session_cookie(req, data.with_session(updated)?, None)
                .await?;
            AuthResponse::native(None, team.field_values()?.into())
        }
        (HttpMethod::Get, "/organization/list-user-teams") => {
            let target = req
                .query_string("userId")?
                .filter(|id| !id.is_empty())
                .map(FieldValue::from)
                .map(Ok)
                .unwrap_or_else(|| data.user_property("id"))?;
            let is_self = target.strict_equals(&data.user_property("id")?);
            let explicit_org = req
                .query_string("organizationId")?
                .filter(|id| !id.is_empty());
            let org = explicit_org
                .as_deref()
                .map(FieldValue::from)
                .map(Ok)
                .unwrap_or_else(|| session.session_property("activeOrganizationId"))?;
            if !is_self || explicit_org.is_some() {
                if !org.is_truthy() {
                    return Err(AuthError::from_code(
                        "BAD_REQUEST",
                        "NO_ACTIVE_ORGANIZATION",
                        "No active organization",
                    ));
                }
                let member = ctx
                    .database
                    .get_member_with_user_value(&org, &data.user_property("id")?)
                    .await?
                    .ok_or_else(|| {
                        AuthError::from_code(
                            "FORBIDDEN",
                            "YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION",
                            "You are not a member of this organization",
                        )
                    })?;
                if !is_self {
                    authorize(
                        &member.member,
                        &org,
                        ("member", "update"),
                        AuthError::from_code(
                            "FORBIDDEN",
                            "YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER",
                            "You are not allowed to update this member",
                        ),
                        config,
                        ctx,
                    )
                    .await?;
                    if ctx
                        .database
                        .get_member_with_user_value(&org, &target)
                        .await?
                        .is_none()
                    {
                        return Err(AuthError::from_code(
                            "BAD_REQUEST",
                            "USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION",
                            "User is not a member of the organization",
                        ));
                    }
                }
                let teams =
                    public_teams(ctx.database.list_user_teams_value(&target).await?, config)?
                        .into_iter()
                        .filter(|team| team.organization_id.field_value().strict_equals(&org))
                        .collect::<Vec<_>>();
                teams_response(teams)?
            } else {
                let mut teams = Vec::new();
                for team in
                    public_teams(ctx.database.list_user_teams_value(&target).await?, config)?
                {
                    if ctx
                        .database
                        .get_member_value(&team.organization_id.field_value(), &target)
                        .await?
                        .is_some()
                    {
                        teams.push(team);
                    }
                }
                teams_response(teams)?
            }
        }
        (HttpMethod::Get, "/organization/list-team-members") => {
            let team_id = req
                .query_string("teamId")?
                .filter(|id| !id.is_empty())
                .map(FieldValue::from)
                .map(Ok)
                .unwrap_or_else(|| session.session_property("activeTeamId"))?;
            if !team_id.is_truthy() {
                return Err(AuthError::from_code(
                    "BAD_REQUEST",
                    "YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM",
                    "You do not have an active team",
                ));
            }
            let details = ctx
                .database
                .get_team_details_value(&team_id, None, false)
                .await?
                .ok_or_else(|| {
                    AuthError::from_code("BAD_REQUEST", "TEAM_NOT_FOUND", "Team not found")
                })?;
            let team = details.into_public_parts(&config.schema.team)?.0;
            if ctx
                .database
                .get_member_value(
                    &team.organization_id.field_value(),
                    &data.user_property("id")?,
                )
                .await?
                .is_none()
                || ctx
                    .database
                    .get_team_member_value(&team_id, &data.user_property("id")?)
                    .await?
                    .is_none()
            {
                return Err(AuthError::from_code(
                    "BAD_REQUEST",
                    "USER_IS_NOT_A_MEMBER_OF_THE_TEAM",
                    "User is not a member of the team",
                ));
            }
            let members = ctx.database.list_team_members_value(&team_id).await?;
            let members = members
                .iter()
                .map(|member| member.field_values().map(FieldValue::from))
                .collect::<AuthResult<Vec<_>>>()?;
            AuthResponse::native(None, members.into())
        }
        (
            HttpMethod::Post,
            "/organization/add-team-member" | "/organization/remove-team-member",
        ) => {
            let body = body!(MemberBody);
            let org = resolve_organization_id(
                body.organization_id.as_deref(),
                session,
                AuthError::from_code(
                    "BAD_REQUEST",
                    "NO_ACTIVE_ORGANIZATION",
                    "No active organization",
                ),
            )?;
            let member = ctx
                .database
                .get_member_with_user_value(&org, &data.user_property("id")?)
                .await?
                .ok_or_else(|| {
                    AuthError::from_code(
                        "BAD_REQUEST",
                        "USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION",
                        "User is not a member of the organization",
                    )
                })?;
            let adding = req.path() == "/organization/add-team-member";
            authorize(
                &member.member,
                &org,
                ("member", if adding { "update" } else { "delete" }),
                if adding {
                    AuthError::from_code(
                        "FORBIDDEN",
                        "YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER",
                        "You are not allowed to create a new member",
                    )
                } else {
                    AuthError::from_code(
                        "FORBIDDEN",
                        "YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER",
                        "You are not allowed to remove a team member",
                    )
                },
                config,
                ctx,
            )
            .await?;
            if ctx
                .database
                .get_member_with_user_value(&org, &body.user_id.as_str().into())
                .await?
                .is_none()
            {
                return Err(AuthError::from_code(
                    "BAD_REQUEST",
                    "USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION",
                    "User is not a member of the organization",
                ));
            }
            let team = find_team(&body.team_id.as_str().into(), &org, ctx, config).await?;
            let organization = ctx
                .database
                .get_organization_by_id_value(&org)
                .await?
                .ok_or_else(|| {
                    AuthError::from_code(
                        "BAD_REQUEST",
                        "ORGANIZATION_NOT_FOUND",
                        "Organization not found",
                    )
                })?;
            let organization_view =
                crate::plugins::organization::fields::organization(&organization, ctx)?;
            let target_user = ctx
                .database
                .get_user_by_id(&body.user_id)
                .await?
                .ok_or_else(|| {
                    AuthError::from_status(
                        "BAD_REQUEST",
                        better_auth_core::FieldMap::from([(
                            "message".into(),
                            "User not found".into(),
                        )])
                        .into(),
                    )
                })?;
            let target_value = FieldValue::from(FieldMap::from(target_user));
            let target = OrganizationTeamMemberTarget {
                team: &team,
                organization: &organization_view,
                user: &target_value,
            };
            if adding {
                if let Some(hooks) = &config.hooks {
                    hooks.before_add_team_member(target).await?;
                }
                let maximum = config
                    .team_member_limit(OrganizationTeamMemberLimit {
                        team_id: &body.team_id.as_str().into(),
                        organization_id: &org,
                        session,
                    })
                    .await?;
                let member = ctx
                    .database
                    .add_team_member(&body.team_id.clone().into(), &body.user_id, maximum)
                    .await?
                    .ok_or_else(|| {
                        AuthError::from_code(
                            "FORBIDDEN",
                            "TEAM_MEMBER_LIMIT_REACHED",
                            "Team member limit reached",
                        )
                    })?;
                if let Some(hooks) = &config.hooks {
                    hooks.after_add_team_member(&member, target).await?;
                }
                AuthResponse::native(None, member.field_values()?.into())
            } else {
                let member = ctx
                    .database
                    .get_team_member(&body.team_id, &body.user_id)
                    .await?
                    .ok_or_else(|| {
                        AuthError::from_code(
                            "BAD_REQUEST",
                            "USER_IS_NOT_A_MEMBER_OF_THE_TEAM",
                            "User is not a member of the team",
                        )
                    })?;
                if let Some(hooks) = &config.hooks {
                    hooks.before_remove_team_member(&member, target).await?;
                }
                ctx.database
                    .remove_team_member(&body.team_id, &body.user_id)
                    .await?;
                if let Some(hooks) = &config.hooks {
                    hooks.after_remove_team_member(&member, target).await?;
                }
                AuthResponse::json(
                    None,
                    &serde_json::json!({"message":"Team member removed successfully."}),
                )?
            }
        }
        _ => return Ok(None),
    };
    Ok(Some(response))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugins::organization::{OrganizationPlugin, OrganizationTeamsConfig};
    use crate::plugins::test_helpers::{
        create_auth_json_request_no_query, create_test_config, create_test_context_with_plugins,
        create_user_and_session,
    };
    use better_auth_core::CreateTeam;
    use better_auth_core::{CreateMember, CreateOrganization, CreateUser};
    use chrono::Duration;

    #[tokio::test]
    async fn team_membership_is_idempotent_and_team_scope_is_enforced() {
        let config = OrganizationConfig {
            teams: OrganizationTeamsConfig {
                enabled: true,
                maximum_members_per_team: Some(1),
                ..Default::default()
            },
            ..Default::default()
        };
        let ctx = create_test_context_with_plugins(
            create_test_config(),
            &[&OrganizationPlugin::with_config(config.clone())],
        )
        .await;
        let (user, session) = create_user_and_session(
            &ctx,
            CreateUser {
                name: Some("Fixture".into()).into(),
                email: Some("team-owner@example.com".into()),
                ..Default::default()
            },
            Duration::hours(1),
        )
        .await;
        let org = ctx
            .database
            .create_organization(CreateOrganization {
                additional_fields: Default::default(),
                id: None,
                name: "Teams".into(),
                slug: "teams".into(),
                logo: None.into(),
                metadata: None.into(),
            })
            .await
            .unwrap();
        ctx.database
            .create_member(CreateMember {
                additional_fields: Default::default(),
                organization_id: org.id.clone(),
                user_id: user.id.clone(),
                role: "owner".into(),
            })
            .await
            .unwrap();
        ctx.database
            .update_session_active_organization(
                session.token.typed().unwrap(),
                Some(org.id.typed().unwrap()),
            )
            .await
            .unwrap();
        let team = ctx
            .database
            .create_team(CreateTeam {
                name: "One".into(),
                organization_id: org.id.clone(),
                updated_at: None,
                ..Default::default()
            })
            .await
            .unwrap();
        let add = create_auth_json_request_no_query(
            HttpMethod::Post,
            "/organization/add-team-member",
            Some(session.token.typed().unwrap()),
            Some(serde_json::json!({"teamId":team.id,"userId":user.id})),
        );
        let first = handle_team_request(&add, &ctx, &config)
            .await
            .unwrap()
            .unwrap();
        let duplicate = handle_team_request(&add, &ctx, &config)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(first.body.bytes().unwrap(), duplicate.body.bytes().unwrap());
        assert_eq!(
            ctx.database
                .list_team_members(team.id.typed().unwrap())
                .await
                .unwrap()
                .len(),
            1
        );
        let full = super::super::org::get_full_organization_core(
            &crate::plugins::organization::types::GetFullOrganizationQuery {
                organization_id: Some(org.id.typed().unwrap().clone()),
                ..Default::default()
            },
            &(user.clone(), session.clone()).into(),
            &config,
            &ctx,
        )
        .await
        .unwrap()
        .unwrap();
        assert_eq!(
            full.model_property("teams")
                .unwrap()
                .as_array()
                .unwrap()
                .get(0)
                .unwrap()
                .unwrap()
                .model_property("memberCount")
                .unwrap()
                .as_f64(),
            Some(1.0)
        );
        let foreign_org = ctx
            .database
            .create_organization(CreateOrganization {
                additional_fields: Default::default(),
                id: None,
                name: "Foreign".into(),
                slug: "foreign-teams".into(),
                logo: None.into(),
                metadata: None.into(),
            })
            .await
            .unwrap();
        let foreign = ctx
            .database
            .create_team(CreateTeam {
                name: "Foreign".into(),
                organization_id: foreign_org.id,
                updated_at: None,
                ..Default::default()
            })
            .await
            .unwrap();
        let active = create_auth_json_request_no_query(
            HttpMethod::Post,
            "/organization/set-active-team",
            Some(session.token.typed().unwrap()),
            Some(serde_json::json!({"teamId":foreign.id})),
        );
        assert_eq!(
            handle_team_request(&active, &ctx, &config)
                .await
                .unwrap_err()
                .status_code()
                .unwrap(),
            400
        );
        let active = create_auth_json_request_no_query(
            HttpMethod::Post,
            "/organization/set-active-team",
            Some(session.token.typed().unwrap()),
            Some(serde_json::json!({"teamId":team.id})),
        );
        let active_response = handle_team_request(&active, &ctx, &config)
            .await
            .unwrap()
            .unwrap();
        let active_response =
            crate::plugins::test_helpers::finalize_response(&ctx, &active, active_response);
        assert!(
            active_response
                .headers
                .get_all("set-cookie")
                .any(|cookie| cookie.starts_with("better-auth.session_token="))
        );
        let remove = create_auth_json_request_no_query(
            HttpMethod::Post,
            "/organization/remove-team",
            Some(session.token.typed().unwrap()),
            Some(serde_json::json!({"teamId":team.id})),
        );
        assert_eq!(
            handle_team_request(&remove, &ctx, &config)
                .await
                .unwrap_err()
                .status_code()
                .unwrap(),
            403
        );
    }
}