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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

use better_auth_core::entity::AuthUser;
use better_auth_core::{AuthContext, AuthPlugin, AuthRoute};
use better_auth_core::{AuthError, AuthResult};
use better_auth_core::{AuthRecordFields, FieldMap, FieldValue};
use better_auth_core::{AuthRequest, AuthResponse, HttpMethod, RequestMeta};

use super::email_verification::EmailVerificationPlugin;
use better_auth_core::utils::password::{self as password_utils, PasswordHasher};
use better_auth_core::wire::UserView;

use crate::plugins::helpers::{SessionIssueError, issue_selected_user_session_optional};

mod callbacks;
mod request;
mod signup;
#[cfg(test)]
mod synthetic_tests;
use super::username::request::SignInUsernameRequest;
pub use callbacks::EmailPasswordCallbacks;
use signup::sign_up_core;
pub use signup::{CustomSyntheticUser, OnExistingUserSignUp, SyntheticUserInput};

const MESSAGE_EMAIL_NOT_VERIFIED: &str = "Email not verified";

/// Email and password authentication plugin
pub struct EmailPasswordPlugin {
    config: EmailPasswordConfig,
    /// Optional reference to the email-verification plugin so that
    /// `send_on_sign_in` can be triggered during the sign-in flow.
    email_verification: Option<Arc<EmailVerificationPlugin>>,
}

#[derive(Clone)]
pub struct EmailPasswordConfig {
    pub enable_signup: bool,
    /// Enable the upstream username plugin behavior. Requires both username fields.
    pub username: bool,
    pub require_email_verification: bool,
    pub password_min_length: Option<usize>,
    /// Maximum password length (default: 128).
    pub password_max_length: Option<usize>,
    /// Whether to automatically sign in the user after sign-up (default: true).
    /// With `Some(false)`, sign-up returns the user without creating a session.
    pub auto_sign_in: Option<bool>,
    /// Custom password hasher. When `None`, the default scrypt hasher is used.
    pub password_hasher: Option<Arc<dyn PasswordHasher>>,
    /// Notify the application after a protected duplicate signup hashes its password.
    pub on_existing_user_sign_up: Option<Arc<dyn OnExistingUserSignUp>>,
    /// Customize enumeration-safe signup responses without creating an account.
    pub custom_synthetic_user: Option<Arc<CustomSyntheticUser>>,
}

impl EmailPasswordConfig {
    /// Read the minimum password length. Omission uses eight characters.
    pub fn password_min_length(&self) -> usize {
        self.password_min_length.unwrap_or(8)
    }

    /// Read the maximum password length. Omission uses 128 characters.
    pub fn password_max_length(&self) -> usize {
        self.password_max_length.unwrap_or(128)
    }

    /// Read the sign-up session policy. Omission creates a session.
    pub fn auto_sign_in(&self) -> bool {
        self.auto_sign_in.unwrap_or(true)
    }
}

impl std::fmt::Debug for EmailPasswordConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EmailPasswordConfig")
            .field("enable_signup", &self.enable_signup)
            .field("username", &self.username)
            .field(
                "require_email_verification",
                &self.require_email_verification,
            )
            .field("password_min_length", &self.password_min_length)
            .field("password_max_length", &self.password_max_length)
            .field("auto_sign_in", &self.auto_sign_in)
            .field(
                "password_hasher",
                &self.password_hasher.as_ref().map(|_| "custom"),
            )
            .finish()
    }
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct SignUpRequest {
    name: String,
    email: String,
    password: String,
    image: Option<String>,
    #[serde(rename = "callbackURL")]
    callback_url: Option<String>,
    #[serde(rename = "rememberMe")]
    remember_me: Option<bool>,
    #[serde(flatten)]
    additional_fields: serde_json::Map<String, serde_json::Value>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct SignInRequest {
    email: String,
    password: String,
    #[serde(rename = "callbackURL")]
    callback_url: Option<String>,
    #[serde(rename = "rememberMe")]
    remember_me: Option<bool>,
}

#[derive(Debug, Serialize)]
pub(crate) struct SignUpResponse {
    #[serde(
        with = "better_auth_core::field_value::serde::value",
        skip_serializing_if = "better_auth_core::FieldValue::is_json_omitted"
    )]
    token: better_auth_core::FieldValue,
    #[serde(with = "better_auth_core::field_value::serde::map")]
    user: better_auth_core::FieldMap,
}

impl SignUpResponse {
    fn into_field_value(self) -> FieldValue {
        FieldMap::from([
            ("token".into(), self.token),
            ("user".into(), self.user.into()),
        ])
        .into()
    }
}

#[derive(Debug, Serialize)]
pub(crate) struct SignInResponse<U: Serialize> {
    redirect: bool,
    #[serde(skip_serializing_if = "better_auth_core::SchemaValue::is_json_omitted")]
    token: better_auth_core::SchemaValue<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    url: Option<String>,
    user: U,
}

impl SignInResponse<UserView> {
    pub(crate) fn into_field_value(self) -> AuthResult<FieldValue> {
        Ok(FieldMap::from([
            ("redirect".into(), self.redirect.into()),
            ("token".into(), self.token.into_field_value()),
            (
                "url".into(),
                self.url.map(FieldValue::from).unwrap_or_default(),
            ),
            ("user".into(), self.user.field_values()?.into()),
        ])
        .into())
    }
}

pub(crate) struct SignInCoreResult<U: Serialize> {
    pub response: SignInResponse<U>,
}

impl EmailPasswordPlugin {
    #[expect(
        clippy::new_without_default,
        reason = "plugin construction is intentionally explicit"
    )]
    pub fn new() -> Self {
        Self {
            config: EmailPasswordConfig::default(),
            email_verification: None,
        }
    }

    pub fn with_config(config: EmailPasswordConfig) -> Self {
        Self {
            config,
            email_verification: None,
        }
    }

    /// Attach an [`EmailVerificationPlugin`] so that `send_on_sign_in` is
    /// automatically called when a user signs in with an unverified email.
    pub fn with_email_verification(mut self, plugin: Arc<EmailVerificationPlugin>) -> Self {
        self.email_verification = Some(plugin);
        self
    }

    pub fn enable_signup(mut self, enable: bool) -> Self {
        self.config.enable_signup = enable;
        self
    }

    /// Enable username registration, sign-in, availability checks, and updates.
    ///
    /// The user entity must persist `username` and `display_username`.
    pub fn username(mut self, enabled: bool) -> Self {
        self.config.username = enabled;
        self
    }

    pub fn require_email_verification(mut self, require: bool) -> Self {
        self.config.require_email_verification = require;
        self
    }

    pub fn password_min_length(mut self, length: usize) -> Self {
        self.config.password_min_length = Some(length);
        self
    }

    pub fn password_max_length(mut self, length: usize) -> Self {
        self.config.password_max_length = Some(length);
        self
    }

    pub fn auto_sign_in(mut self, auto: bool) -> Self {
        self.config.auto_sign_in = Some(auto);
        self
    }

    pub fn password_hasher(mut self, hasher: Arc<dyn PasswordHasher>) -> Self {
        self.config.password_hasher = Some(hasher);
        self
    }

    /// Set the notification for a duplicate signup protected against enumeration.
    pub fn on_existing_user_sign_up(mut self, callback: Arc<dyn OnExistingUserSignUp>) -> Self {
        self.config.on_existing_user_sign_up = Some(callback);
        self
    }

    /// Customize synthetic users returned by enumeration-safe signup.
    pub fn custom_synthetic_user(mut self, callback: Arc<CustomSyntheticUser>) -> Self {
        self.config.custom_synthetic_user = Some(callback);
        self
    }

    async fn handle_sign_up(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    ) -> AuthResult<AuthResponse> {
        let endpoint_body: serde_json::Value = req
            .body_as_json()
            .map_err(|error| AuthError::bad_request(format!("Invalid JSON: {error}")))?;
        let signup_req = request::sign_up(req)?;
        request::form_csrf(req, ctx).await?;

        let response = sign_up_core(&signup_req, endpoint_body, &self.config, req, ctx).await?;

        Ok(AuthResponse::native(None, response.into_field_value()))
    }

    async fn handle_sign_in(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    ) -> AuthResult<AuthResponse> {
        let signin_req = request::sign_in(req)?;
        request::form_csrf(req, ctx).await?;
        if !super::json_body::valid_email(&signin_req.email)? {
            return Err(AuthError::bad_request("Invalid email"));
        }

        let meta = RequestMeta::from_request_with_config(req, &ctx.config.advanced.ip_address);
        let result = sign_in_core(
            req,
            &signin_req,
            &self.config,
            self.email_verification.as_deref(),
            &meta,
            ctx,
        )
        .await?;
        Ok(AuthResponse::native(
            None,
            result.response.into_field_value()?,
        ))
    }

    async fn handle_sign_in_username(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    ) -> AuthResult<AuthResponse> {
        super::username::UsernamePlugin::default()
            .sign_in_with_verification(req, ctx, self.email_verification.as_deref())
            .await
    }

    async fn handle_is_username_available(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<impl better_auth_core::AuthSchema>,
    ) -> AuthResult<AuthResponse> {
        super::username::UsernamePlugin::default()
            .available(req, ctx)
            .await
    }
}

// ---------------------------------------------------------------------------
// Core functions — framework-agnostic business logic
// ---------------------------------------------------------------------------

async fn load_credential_password_hash(
    user: &impl AuthUser,
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
) -> AuthResult<better_auth_core::FieldValue> {
    super::helpers::get_credential_password_hash(ctx, user.id().into_owned())
        .await?
        .ok_or(AuthError::InvalidCredentials)
}

async fn verify_user_password(
    user: &impl AuthUser,
    password: &str,
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
) -> AuthResult<()> {
    let stored_hash = load_credential_password_hash(user, ctx).await?;
    password_utils::verify_password_native(
        ctx.password_policy.hasher.as_ref(),
        password,
        &stored_hash,
    )
    .await
}

enum CredentialSignIn<'a> {
    Email(Option<&'a EmailVerificationPlugin>),
    Username,
}

/// Shared sign-in finalization logic after user lookup and credential verification.
async fn finalize_sign_in_with_user_core(
    req: &AuthRequest,
    user: impl AuthUser,
    remember_me: Option<bool>,
    method: CredentialSignIn<'_>,
    callback_url: Option<&str>,
    meta: &RequestMeta,
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
) -> AuthResult<SignInCoreResult<UserView>> {
    // Send verification email on sign-in if configured
    if let CredentialSignIn::Email(Some(ev)) = &method
        && let Err(e) = ev
            .send_verification_on_sign_in_with_request(&user, callback_url, Some(req), ctx)
            .await
    {
        better_auth_core::observability::logger::current().warn(
            "Failed to send verification email on sign-in",
            &[better_auth_core::observability::LogArgument::Error(&e)],
        )?;
    }

    let expires_in = if remember_me == Some(false) {
        chrono::Duration::days(1)
    } else {
        ctx.config.session.expires_in()
    };
    let user = ctx.internal_user_view(&user).await?;
    let issued = issue_selected_user_session_optional(
        ctx,
        better_auth_core::FieldMap::from(user.clone()).into(),
        meta,
        expires_in,
    )
    .await
    .map_err(SessionIssueError::into_auth_error)?;
    let Some(issued) = issued else {
        let session_failure_status = match method {
            CredentialSignIn::Email(_) => "UNAUTHORIZED",
            CredentialSignIn::Username => "INTERNAL_SERVER_ERROR",
        };
        if matches!(method, CredentialSignIn::Email(_)) {
            better_auth_core::observability::logger::current()
                .error("Failed to create session", &[])?;
        }
        return Err(AuthError::from_code(
            session_failure_status,
            "FAILED_TO_CREATE_SESSION",
            "Failed to create session",
        ));
    };
    let session = issued.session_value()?;
    let manager = ctx.session_manager();
    manager
        .set_native_session_cookie(req, issued, Some(remember_me == Some(false)))
        .await?;

    if let Some(callback) = callback_url.filter(|url| !url.is_empty()) {
        req.set_response_header("Location", callback)?;
    }
    let response = SignInResponse {
        redirect: callback_url.is_some_and(|url| !url.is_empty()),
        token: better_auth_core::SchemaValue::from_field(session.model_property("token")?),
        url: callback_url.map(str::to_owned),
        user: ctx.user_view(&user).await?,
    };
    Ok(SignInCoreResult { response })
}

/// Core sign-in by email.
pub(crate) async fn sign_in_core(
    req: &AuthRequest,
    body: &SignInRequest,
    config: &EmailPasswordConfig,
    email_verification: Option<&EmailVerificationPlugin>,
    meta: &RequestMeta,
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
) -> AuthResult<SignInCoreResult<UserView>> {
    ctx.password_policy.validate_max_length(&body.password)?;
    let verification = EmailVerificationPlugin::from_context(ctx);
    let email_verification = email_verification.or(verification.as_ref());
    let Some(record) = ctx.database.get_user_with_accounts(&body.email).await? else {
        _ = password_utils::hash_password(ctx.password_policy.hasher.as_ref(), &body.password)
            .await?;
        return Err(AuthError::InvalidCredentials);
    };

    let Some(stored_hash) = credential_password_from_accounts(&record)? else {
        _ = password_utils::hash_password(ctx.password_policy.hasher.as_ref(), &body.password)
            .await?;
        return Err(AuthError::InvalidCredentials);
    };
    let user = record.user;
    password_utils::verify_password_native(
        ctx.password_policy.hasher.as_ref(),
        &body.password,
        &stored_hash,
    )
    .await?;

    if (config.require_email_verification
        || email_verification.is_some_and(EmailVerificationPlugin::is_verification_required))
        && !user.email_verified().is_truthy()?
    {
        if let Some(verification) = email_verification {
            verification
                .send_verification_on_sign_in_with_request(
                    &user,
                    body.callback_url.as_deref(),
                    Some(req),
                    ctx,
                )
                .await?;
        }
        return Err(AuthError::forbidden(MESSAGE_EMAIL_NOT_VERIFIED));
    }

    finalize_sign_in_with_user_core(
        req,
        user,
        body.remember_me,
        CredentialSignIn::Email(email_verification),
        body.callback_url.as_deref(),
        meta,
        ctx,
    )
    .await
}

pub(super) fn credential_password_from_accounts(
    record: &better_auth_core::store::UserAccounts,
) -> AuthResult<Option<better_auth_core::FieldValue>> {
    let better_auth_core::store::JoinValue::Many(accounts) = &record.accounts else {
        return Err(AuthError::internal("accounts.find is not a function"));
    };
    Ok(accounts
        .iter()
        .find(|account| {
            account
                .provider_id
                .field_value()
                .strict_equals(&"credential".into())
                && account
                    .account_id
                    .field_value()
                    .strict_equals(&record.user.id.field_value())
        })
        .map(|account| account.password.field_value())
        .filter(better_auth_core::FieldValue::is_truthy))
}

/// Core sign-in by username.
pub(crate) async fn sign_in_username_core(
    req: &AuthRequest,
    body: &SignInUsernameRequest,
    normalized_username: &better_auth_core::FieldValue,
    config: &EmailPasswordConfig,
    email_verification: Option<&EmailVerificationPlugin>,
    meta: &RequestMeta,
    ctx: &AuthContext<impl better_auth_core::AuthSchema>,
) -> Result<SignInCoreResult<UserView>, SignInUsernameFailure> {
    ctx.password_policy
        .validate_max_length(&body.password)
        .map_err(SignInUsernameFailure::Auth)?;
    let verification = EmailVerificationPlugin::from_context(ctx);
    let email_verification = email_verification.or(verification.as_ref());
    let Some(user) = ctx
        .database
        .get_user_by_field_value("username", normalized_username)
        .await
        .map_err(SignInUsernameFailure::Auth)?
    else {
        let _ = password_utils::hash_password(ctx.password_policy.hasher.as_ref(), &body.password)
            .await
            .map_err(SignInUsernameFailure::Auth)?;
        return Err(SignInUsernameFailure::InvalidUsernameOrPassword);
    };

    verify_user_password(&user, &body.password, ctx)
        .await
        .map_err(|error| match error {
            AuthError::InvalidCredentials => SignInUsernameFailure::InvalidUsernameOrPassword,
            other => SignInUsernameFailure::Auth(other),
        })?;

    if (config.require_email_verification
        || email_verification.is_some_and(EmailVerificationPlugin::is_verification_required))
        && !user
            .email_verified()
            .is_truthy()
            .map_err(SignInUsernameFailure::Auth)?
    {
        if let Some(ev) = email_verification {
            ev.send_verification_on_sign_in_with_request(
                &user,
                body.callback_url.as_deref(),
                Some(req),
                ctx,
            )
            .await
            .map_err(SignInUsernameFailure::Auth)?;
        }
        return Err(SignInUsernameFailure::EmailNotVerified);
    }

    finalize_sign_in_with_user_core(
        req,
        user,
        body.remember_me,
        CredentialSignIn::Username,
        body.callback_url.as_deref(),
        meta,
        ctx,
    )
    .await
    .map_err(SignInUsernameFailure::Auth)
}

pub(crate) enum SignInUsernameFailure {
    InvalidUsernameOrPassword,
    EmailNotVerified,
    Auth(AuthError),
}

impl Default for EmailPasswordConfig {
    fn default() -> Self {
        Self {
            enable_signup: true,
            username: false,
            require_email_verification: false,
            password_min_length: None,
            password_max_length: None,
            auto_sign_in: None,
            password_hasher: None,
            on_existing_user_sign_up: None,
            custom_synthetic_user: None,
        }
    }
}

#[async_trait]
impl<S: better_auth_core::AuthSchema> AuthPlugin<S> for EmailPasswordPlugin {
    fn telemetry(&self, options: &mut better_auth_core::observability::telemetry::PluginTelemetry) {
        if let Some(verification) = &self.email_verification {
            <EmailVerificationPlugin as AuthPlugin<S>>::telemetry(verification, options);
        }
        let options = &mut options.email_and_password;
        options.enabled = true;
        options.disable_sign_up = !self.config.enable_signup;
        options.require_email_verification = self.config.require_email_verification;
        options.min_password_length = self.config.password_min_length;
        options.max_password_length = self.config.password_max_length;
        options.auto_sign_in = self.config.auto_sign_in == Some(true);
        options.password.hash |= self.config.password_hasher.is_some();
        options.password.verify |= self.config.password_hasher.is_some();
    }

    fn name(&self) -> &'static str {
        "email-password"
    }

    fn telemetry_plugin_id(&self) -> Option<&'static str> {
        None
    }

    fn openapi(&self) -> AuthResult<better_auth_core::openapi::OpenApiPluginMetadata> {
        if self.config.username {
            <crate::plugins::username::UsernamePlugin as AuthPlugin<S>>::openapi(&Default::default())
        } else {
            better_auth_core::openapi::OpenApiPluginMetadata::from_routes(
                <Self as better_auth_core::AuthPlugin<S>>::name(self),
                <Self as better_auth_core::AuthPlugin<S>>::routes(self),
            )
        }
    }

    fn password_hasher(&self) -> Option<Arc<dyn PasswordHasher>> {
        self.config.password_hasher.clone()
    }

    fn schema(&self, fields: &mut better_auth_core::plugin_runtime::ModelFields) -> AuthResult<()> {
        if self.config.username {
            <super::username::UsernamePlugin as AuthPlugin<S>>::schema(
                &super::username::UsernamePlugin::default(),
                fields,
            )?;
        }
        Ok(())
    }

    async fn on_init(&self, ctx: &mut better_auth_core::AuthInitContext<S>) -> AuthResult<()> {
        ctx.password_policy.min_length = self.config.password_min_length();
        ctx.password_policy.max_length = self.config.password_max_length();
        ctx.extensions.insert(self.config.clone());
        if self.config.username {
            <super::username::UsernamePlugin as AuthPlugin<S>>::on_init(
                &super::username::UsernamePlugin::default(),
                ctx,
            )
            .await?;
        }
        Ok(())
    }

    fn routes(&self) -> Vec<AuthRoute> {
        let mut routes = vec![
            AuthRoute::post("/sign-in/email", "signInEmail")
                .body_validator(request::sign_in_body)
                .allowed_media_types(&["application/x-www-form-urlencoded", "application/json"]),
        ];
        if self.config.username {
            routes.push(AuthRoute::post("/sign-in/username", "signInUsername"));
            routes.push(AuthRoute::post(
                "/is-username-available",
                "isUsernameAvailable",
            ));
        }

        if self.config.enable_signup {
            routes.push(
                AuthRoute::post("/sign-up/email", "signUpWithEmailAndPassword")
                    .body_validator(request::sign_up_body)
                    .allowed_media_types(&[
                        "application/x-www-form-urlencoded",
                        "application/json",
                    ]),
            );
        }

        routes
    }

    async fn before_request(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<S>,
    ) -> AuthResult<Option<better_auth_core::BeforeRequestAction>> {
        if self.config.username {
            super::username::UsernamePlugin::default()
                .before_endpoint(req, ctx)
                .await
        } else {
            Ok(None)
        }
    }

    async fn on_request(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<S>,
    ) -> AuthResult<Option<AuthResponse>> {
        match (req.method(), req.path()) {
            (HttpMethod::Post, "/sign-up/email") if self.config.enable_signup => {
                Ok(Some(self.handle_sign_up(req, ctx).await?))
            }
            (HttpMethod::Post, "/sign-in/email") => Ok(Some(self.handle_sign_in(req, ctx).await?)),
            (HttpMethod::Post, "/sign-in/username") if self.config.username => {
                Ok(Some(self.handle_sign_in_username(req, ctx).await?))
            }
            (HttpMethod::Post, "/is-username-available") if self.config.username => {
                Ok(Some(self.handle_is_username_available(req, ctx).await?))
            }
            _ => Ok(None),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugins::test_helpers;
    use better_auth_core::AuthContext;
    use better_auth_core::config::AuthConfig;
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    type TestSchema =
        better_auth_seaorm::store::__private_test_support::bundled_schema::BundledSchema;

    async fn create_test_context(plugin: &EmailPasswordPlugin) -> Arc<AuthContext<TestSchema>> {
        let config = AuthConfig::new("test-secret-key-at-least-32-chars-long");
        let config = Arc::new(config);
        let database = crate::plugins::test_helpers::create_test_database().await;
        let mut model_fields = better_auth_core::plugin_runtime::ModelFields::default();
        let mut init =
            better_auth_core::AuthInitContext::new(config.clone(), database.clone()).unwrap();
        init.password_policy.hasher =
            <EmailPasswordPlugin as AuthPlugin<TestSchema>>::password_hasher(plugin);
        better_auth_core::AuthPlugin::<TestSchema>::schema(plugin, &mut model_fields).unwrap();
        plugin.on_init(&mut init).await.unwrap();
        let parts = init.into_parts();
        let (adapter_config, endpoint_config, model_fields) = model_fields.resolve(&config);
        let database = database
            .with_runtime(
                Arc::new(adapter_config),
                parts.database_hooks.clone(),
                model_fields,
            )
            .unwrap();
        let mut context = AuthContext::new(Arc::new(endpoint_config), database).unwrap();
        parts.apply_request_runtime(&mut context);
        context.extensions = parts.extensions;
        context.email_verification_policy = parts.email_verification_policy;
        context.email_provider = parts.email_provider;
        context.secondary_storage = parts.secondary_storage;
        context.password_policy = parts.password_policy;
        context.metadata = parts.metadata;
        let context = Arc::new(context);
        parts.runtime.bind(&context).unwrap();
        context
    }

    fn create_signup_request(email: &str, password: &str) -> AuthRequest {
        let body = serde_json::json!({
            "name": "Test User",
            "email": email,
            "password": password,
        });
        AuthRequest::from_parts(
            HttpMethod::Post,
            "/sign-up/email".to_string(),
            HashMap::new(),
            Some(body.to_string().into_bytes()),
            None,
        )
    }

    // Upstream reference: packages/better-auth/src/api/routes/sign-up.test.ts :: describe("sign-up with custom fields") and packages/better-auth/src/api/routes/sign-in.test.ts :: describe("sign-in"); adapted to the Rust email-password plugin behavior.
    #[tokio::test]
    async fn test_auto_sign_in_false_returns_no_session() {
        let plugin = EmailPasswordPlugin::new().auto_sign_in(false);
        let ctx = create_test_context(&plugin).await;

        let req = create_signup_request("auto@example.com", "Password123!");
        let response = plugin.handle_sign_up(&req, &ctx).await.unwrap();
        let response = test_helpers::finalize_response(&ctx, &req, response);
        assert_eq!(response.status, 200);

        // Response should NOT have a Set-Cookie header
        let has_cookie = response
            .headers
            .iter()
            .any(|(k, _)| k.eq_ignore_ascii_case("Set-Cookie"));
        assert!(!has_cookie, "auto_sign_in=false should not set a cookie");

        // Response body token should be null
        let body: serde_json::Value =
            serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
        assert!(
            body["token"].is_null(),
            "auto_sign_in=false should return null token"
        );
        // But the user should still be created
        assert!(body["user"]["id"].is_string());
    }

    // Upstream reference: packages/better-auth/src/api/routes/sign-up.test.ts :: describe("sign-up with custom fields") and packages/better-auth/src/api/routes/sign-in.test.ts :: describe("sign-in"); adapted to the Rust email-password plugin behavior.
    #[tokio::test]
    async fn test_auto_sign_in_true_returns_session() {
        let plugin = EmailPasswordPlugin::new(); // default auto_sign_in=true
        let ctx = create_test_context(&plugin).await;

        let req = create_signup_request("autotrue@example.com", "Password123!");
        let response = plugin.handle_sign_up(&req, &ctx).await.unwrap();
        let response = test_helpers::finalize_response(&ctx, &req, response);
        assert_eq!(response.status, 200);

        // Response SHOULD have a Set-Cookie header
        let has_cookie = response
            .headers
            .iter()
            .any(|(k, _)| k.eq_ignore_ascii_case("Set-Cookie"));
        assert!(has_cookie, "auto_sign_in=true should set a cookie");

        // Response body token should be a string
        let body: serde_json::Value =
            serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
        assert!(
            body["token"].is_string(),
            "auto_sign_in=true should return a session token"
        );
    }

    // Upstream reference: packages/better-auth/src/api/routes/sign-up.test.ts :: describe("sign-up with custom fields") and packages/better-auth/src/api/routes/sign-in.test.ts :: describe("sign-in"); adapted to the Rust email-password plugin behavior.
    #[tokio::test]
    async fn test_password_max_length_rejection() {
        let plugin = EmailPasswordPlugin::new().password_max_length(128);
        let ctx = create_test_context(&plugin).await;

        // Password of exactly 129 chars should be rejected
        let long_password = format!("A1!{}", "a".repeat(126)); // 129 chars total
        let req = create_signup_request("long@example.com", &long_password);
        let err = plugin.handle_sign_up(&req, &ctx).await.unwrap_err();
        assert_eq!(err.status_code().unwrap(), 400);

        // Password of exactly 128 chars should be accepted
        let ok_password = format!("A1!{}", "a".repeat(125)); // 128 chars total
        let req = create_signup_request("ok@example.com", &ok_password);
        let response = plugin.handle_sign_up(&req, &ctx).await.unwrap();
        assert_eq!(response.status, 200);
    }

    // Upstream reference: packages/better-auth/src/api/routes/sign-up.test.ts :: describe("sign-up with custom fields") and packages/better-auth/src/api/routes/sign-in.test.ts :: describe("sign-in"); adapted to the Rust email-password plugin behavior.
    #[tokio::test]
    async fn test_custom_password_hasher() {
        /// A simple test hasher that prefixes the password with "hashed:"
        struct TestHasher;

        #[async_trait]
        impl PasswordHasher for TestHasher {
            async fn hash(&self, password: &str) -> AuthResult<String> {
                Ok(format!("hashed:{}", password))
            }
            async fn verify(&self, hash: &str, password: &str) -> AuthResult<bool> {
                Ok(hash == format!("hashed:{}", password))
            }
        }

        let hasher: Arc<dyn PasswordHasher> = Arc::new(TestHasher);
        let plugin = EmailPasswordPlugin::new().password_hasher(hasher);
        let ctx = create_test_context(&plugin).await;

        // Sign up with custom hasher
        let req = create_signup_request("hasher@example.com", "Password123!");
        let response = plugin.handle_sign_up(&req, &ctx).await.unwrap();
        assert_eq!(response.status, 200);

        // Verify the stored hash uses our custom hasher
        let user = ctx
            .database
            .get_user_by_email("hasher@example.com")
            .await
            .unwrap()
            .unwrap();
        let stored_hash = ctx
            .database
            .get_user_accounts(user.id().typed().unwrap())
            .await
            .unwrap()
            .into_iter()
            .find(|account| account.provider_id == "credential")
            .and_then(|account| account.password.typed().unwrap().clone())
            .expect("credential account should store hashed password");
        assert_eq!(stored_hash, "hashed:Password123!");

        // Sign in should work with the custom hasher
        let signin_body = serde_json::json!({
            "email": "hasher@example.com",
            "password": "Password123!",
        });
        let signin_req = AuthRequest::from_parts(
            HttpMethod::Post,
            "/sign-in/email".to_string(),
            HashMap::new(),
            Some(signin_body.to_string().into_bytes()),
            None,
        );
        let response = plugin.handle_sign_in(&signin_req, &ctx).await.unwrap();
        assert_eq!(response.status, 200);

        // Sign in with wrong password should fail
        let bad_body = serde_json::json!({
            "email": "hasher@example.com",
            "password": "WrongPassword!",
        });
        let bad_req = AuthRequest::from_parts(
            HttpMethod::Post,
            "/sign-in/email".to_string(),
            HashMap::new(),
            Some(bad_body.to_string().into_bytes()),
            None,
        );
        let err = plugin.handle_sign_in(&bad_req, &ctx).await.unwrap_err();
        assert_eq!(err.to_string(), AuthError::InvalidCredentials.to_string());
    }

    // Upstream reference: packages/better-auth/src/plugins/username/index.ts :: sign-in path verifies the password once before creating a session; adapted to ensure the Rust username path does not duplicate expensive password verification.
    #[tokio::test]
    async fn test_sign_in_username_verifies_password_once() {
        struct CountingHasher {
            verify_calls: Arc<AtomicUsize>,
        }

        #[async_trait]
        impl PasswordHasher for CountingHasher {
            async fn hash(&self, password: &str) -> AuthResult<String> {
                Ok(format!("hashed:{password}"))
            }

            async fn verify(&self, hash: &str, password: &str) -> AuthResult<bool> {
                self.verify_calls.fetch_add(1, Ordering::SeqCst);
                Ok(hash == format!("hashed:{password}"))
            }
        }

        let verify_calls = Arc::new(AtomicUsize::new(0));
        let hasher: Arc<dyn PasswordHasher> = Arc::new(CountingHasher {
            verify_calls: verify_calls.clone(),
        });
        let plugin = EmailPasswordPlugin::new()
            .username(true)
            .password_hasher(hasher);
        let ctx = create_test_context(&plugin).await;

        let signup_body = serde_json::json!({
            "email": "username-counter@example.com",
            "password": "Password123!",
            "name": "Counter User",
            "username": "Counter_User",
        });
        let signup_req = AuthRequest::from_parts(
            HttpMethod::Post,
            "/sign-up/email".to_string(),
            HashMap::new(),
            Some(signup_body.to_string().into_bytes()),
            None,
        );
        let signup_response = plugin.handle_sign_up(&signup_req, &ctx).await.unwrap();
        assert_eq!(signup_response.status, 200);

        verify_calls.store(0, Ordering::SeqCst);

        let signin_body = serde_json::json!({
            "username": "COUNTER_USER",
            "password": "Password123!",
        });
        let signin_req = AuthRequest::from_parts(
            HttpMethod::Post,
            "/sign-in/username".to_string(),
            HashMap::from([("content-type".into(), "application/json".into())]),
            Some(signin_body.to_string().into_bytes()),
            None,
        );
        let signin_response = plugin
            .handle_sign_in_username(&signin_req, &ctx)
            .await
            .unwrap();
        assert_eq!(signin_response.status, 200);
        assert_eq!(verify_calls.load(Ordering::SeqCst), 1);
    }

    // Rust-specific surface: route-table registration for the endpoint declared in
    // packages/better-auth/src/plugins/username/index.ts :: isUsernameAvailable.
    #[tokio::test]
    async fn test_is_username_available_route_registered() {
        let plugin = EmailPasswordPlugin::new().username(true);
        let routes =
            <EmailPasswordPlugin as better_auth_core::AuthPlugin<TestSchema>>::routes(&plugin);
        assert!(
            routes.iter().any(|r| r.path == "/is-username-available"),
            "route /is-username-available should be registered"
        );
    }

    // Upstream reference: packages/better-auth/src/plugins/username/index.ts ::
    // isUsernameAvailable returns `{ available: true }` when no user holds the
    // normalized username; adapted to the Rust email-password plugin.
    #[tokio::test]
    async fn test_is_username_available_fresh() {
        let plugin = EmailPasswordPlugin::new().username(true);
        let ctx = create_test_context(&plugin).await;

        let body = serde_json::json!({ "username": "fresh_user" });
        let req = AuthRequest::from_parts(
            HttpMethod::Post,
            "/is-username-available".to_string(),
            HashMap::from([("content-type".into(), "application/json".into())]),
            Some(body.to_string().into_bytes()),
            None,
        );
        let response = plugin
            .handle_is_username_available(&req, &ctx)
            .await
            .unwrap();
        assert_eq!(response.status, 200);
        let json: serde_json::Value =
            serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
        assert_eq!(json["available"], true);
    }

    // Upstream reference: packages/better-auth/src/plugins/username/index.ts ::
    // isUsernameAvailable returns `{ available: false }` when the adapter finds a
    // user on the normalized username; adapted to the Rust email-password plugin.
    #[tokio::test]
    async fn test_is_username_available_taken() {
        let plugin = EmailPasswordPlugin::new().username(true);
        let ctx = create_test_context(&plugin).await;

        // Sign up a user with a username
        let signup_body = serde_json::json!({
            "name": "Taken User",
            "email": "taken@example.com",
            "password": "Password123!",
            "username": "taken_user",
        });
        let signup_req = AuthRequest::from_parts(
            HttpMethod::Post,
            "/sign-up/email".to_string(),
            HashMap::new(),
            Some(signup_body.to_string().into_bytes()),
            None,
        );
        let resp = plugin.handle_sign_up(&signup_req, &ctx).await.unwrap();
        assert_eq!(resp.status, 200);

        let body = serde_json::json!({ "username": "taken_user" });
        let req = AuthRequest::from_parts(
            HttpMethod::Post,
            "/is-username-available".to_string(),
            HashMap::from([("content-type".into(), "application/json".into())]),
            Some(body.to_string().into_bytes()),
            None,
        );
        let response = plugin
            .handle_is_username_available(&req, &ctx)
            .await
            .unwrap();
        assert_eq!(response.status, 200);
        let json: serde_json::Value =
            serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
        assert_eq!(json["available"], false);
    }

    // Upstream reference: packages/better-auth/src/plugins/username/index.ts ::
    // isUsernameAvailable throws UNPROCESSABLE_ENTITY with code USERNAME_TOO_SHORT
    // below `minUsernameLength` (default 3); adapted to the Rust email-password plugin.
    #[tokio::test]
    async fn test_is_username_available_too_short() {
        let plugin = EmailPasswordPlugin::new().username(true);
        let ctx = create_test_context(&plugin).await;

        let body = serde_json::json!({ "username": "ab" });
        let req = AuthRequest::from_parts(
            HttpMethod::Post,
            "/is-username-available".to_string(),
            HashMap::from([("content-type".into(), "application/json".into())]),
            Some(body.to_string().into_bytes()),
            None,
        );
        let response = plugin
            .handle_is_username_available(&req, &ctx)
            .await
            .unwrap_err()
            .to_auth_response()
            .unwrap()
            .into_http_response()
            .unwrap();
        assert_eq!(response.status, 422);
        let json: serde_json::Value =
            serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
        assert_eq!(json["code"], "USERNAME_TOO_SHORT");
    }

    // Upstream reference: packages/better-auth/src/plugins/username/index.ts ::
    // isUsernameAvailable rejects usernames that fail `defaultUsernameValidator`
    // with UNPROCESSABLE_ENTITY; adapted to the Rust email-password plugin.
    #[tokio::test]
    async fn test_is_username_available_invalid_chars() {
        let plugin = EmailPasswordPlugin::new().username(true);
        let ctx = create_test_context(&plugin).await;

        let body = serde_json::json!({ "username": "bad user!" });
        let req = AuthRequest::from_parts(
            HttpMethod::Post,
            "/is-username-available".to_string(),
            HashMap::from([("content-type".into(), "application/json".into())]),
            Some(body.to_string().into_bytes()),
            None,
        );
        let response = plugin
            .handle_is_username_available(&req, &ctx)
            .await
            .unwrap_err()
            .to_auth_response()
            .unwrap()
            .into_http_response()
            .unwrap();
        assert_eq!(response.status, 422);
        let json: serde_json::Value =
            serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
        assert_eq!(json["code"], "INVALID_USERNAME");
    }
}