Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Add rate limiting to sign-in verification code (max 5 attempts)

Matt Robertsb41d1b831782
diff --git a/app/handlers/signin.go b/app/handlers/signin.go
index 881fab00d..470aada7a 100644
--- a/app/handlers/signin.go
+++ b/app/handlers/signin.go
@@ -1,6 +1,7 @@
package handlers
import (
+ "fmt"
"net/http"
"time"
@@ -97,6 +98,12 @@ func SignInByEmail() web.HandlerFunc {
// Only send code if user exists
if userExists {
+ // Invalidate any previous active verification codes for this email
+ _ = bus.Dispatch(c, &cmd.InvalidateVerificationsByEmail{
+ Email: action.Email,
+ Kind: enum.EmailVerificationKindSignIn,
+ })
+
err := bus.Dispatch(c, &cmd.SaveVerificationKey{
Key: action.LinkKey,
Code: action.VerificationCode,
@@ -139,6 +146,12 @@ func SignInByEmailWithName() web.HandlerFunc {
return c.Forbidden()
}
+ // Invalidate any previous active verification codes for this email
+ _ = bus.Dispatch(c, &cmd.InvalidateVerificationsByEmail{
+ Email: action.Email,
+ Kind: enum.EmailVerificationKindSignIn,
+ })
+
// Save verification with name
err = bus.Dispatch(c, &cmd.SaveVerificationKey{
Key: action.LinkKey,
@@ -159,18 +172,19 @@ func SignInByEmailWithName() web.HandlerFunc {
// VerifySignInCode verifies the code entered by the user and signs them in
func VerifySignInCode() web.HandlerFunc {
return func(c *web.Context) error {
+ const maxAttempts = 5
+
action := &actions.VerifySignInCode{}
if result := c.BindTo(action); !result.Ok {
return c.HandleValidation(result)
}
- // Get verification by email and code
- verification := &query.GetVerificationByEmailAndCode{
+ // Look up the most recent active verification by email (without code)
+ activeVerification := &query.GetActiveVerificationByEmail{
Email: action.Email,
- Code: action.Code,
Kind: enum.EmailVerificationKindSignIn,
}
- err := bus.Dispatch(c, verification)
+ err := bus.Dispatch(c, activeVerification)
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
return c.BadRequest(web.Map{
@@ -180,21 +194,31 @@ func VerifySignInCode() web.HandlerFunc {
return c.Failure(err)
}
- result := verification.Result
+ result := activeVerification.Result
- // Code is single-use: reject if already verified
- if result.VerifiedAt != nil {
+ // Check if max attempts exceeded
+ if result.Attempts >= maxAttempts {
return c.BadRequest(web.Map{
- "code": "Invalid or expired verification code",
+ "code": "Too many attempts. Please request a new code.",
})
}
- // Check if expired
- if time.Now().After(result.ExpiresAt) {
- // Mark as verified to prevent reuse
- _ = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: result.Key})
+ // Increment attempts before comparing (prevents timing attacks)
+ if err := bus.Dispatch(c, &cmd.IncrementVerificationAttempts{Key: result.Key}); err != nil {
+ return c.Failure(err)
+ }
+
+ // Compare the submitted code with the stored code
+ if result.Code != action.Code {
+ if result.Attempts+1 >= maxAttempts {
+ // Final attempt failed — invalidate the code
+ _ = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: result.Key})
+ return c.BadRequest(web.Map{
+ "code": "Too many attempts. Please request a new code.",
+ })
+ }
return c.BadRequest(web.Map{
- "code": "Invalid or expired verification code",
+ "code": "Invalid or expired verification code" + fmt.Sprintf(" (attempt %d of %d)", result.Attempts+1, maxAttempts),
})
}
@@ -267,6 +291,12 @@ func ResendSignInCode() web.HandlerFunc {
return c.Forbidden()
}
+ // Invalidate any previous active verification codes for this email
+ _ = bus.Dispatch(c, &cmd.InvalidateVerificationsByEmail{
+ Email: action.Email,
+ Kind: enum.EmailVerificationKindSignIn,
+ })
+
// Save new verification code
err := bus.Dispatch(c, &cmd.SaveVerificationKey{
Key: action.LinkKey,
diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go
index c1cd6b584..ca027bf9d 100644
--- a/app/handlers/signin_test.go
+++ b/app/handlers/signin_test.go
@@ -43,6 +43,10 @@ func TestSignInByEmailHandler_ExistingUser(t *testing.T) {
return nil
})
+ bus.AddHandler(func(ctx context.Context, c *cmd.InvalidateVerificationsByEmail) error {
+ return nil
+ })
+
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
if q.Email == "[email protected]" {
q.Result = mock.JonSnow
@@ -89,6 +93,10 @@ func TestSignInByEmailWithNameHandler_NewUser(t *testing.T) {
return nil
})
+ bus.AddHandler(func(ctx context.Context, c *cmd.InvalidateVerificationsByEmail) error {
+ return nil
+ })
+
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
return app.ErrNotFound
})
@@ -788,7 +796,33 @@ func TestSignInPageHandler_PrivateTenant_UnauthenticatedUser(t *testing.T) {
func TestVerifySignInCodeHandler_InvalidCode(t *testing.T) {
RegisterT(t)
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveVerificationByEmail) error {
+ q.Result = &entity.EmailVerification{
+ Email: "[email protected]",
+ Key: "some-long-link-key",
+ Code: "123456",
+ CreatedAt: time.Now(),
+ ExpiresAt: time.Now().Add(15 * time.Minute),
+ }
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.IncrementVerificationAttempts) error {
+ return nil
+ })
+
+ server := mock.NewServer()
+ code, _ := server.
+ OnTenant(mock.DemoTenant).
+ ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "999999" }`)
+
+ Expect(code).Equals(http.StatusBadRequest)
+}
+
+func TestVerifySignInCodeHandler_NoActiveVerification(t *testing.T) {
+ RegisterT(t)
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveVerificationByEmail) error {
return app.ErrNotFound
})
@@ -800,44 +834,83 @@ func TestVerifySignInCodeHandler_InvalidCode(t *testing.T) {
Expect(code).Equals(http.StatusBadRequest)
}
-func TestVerifySignInCodeHandler_ExpiredCode(t *testing.T) {
+func TestVerifySignInCodeHandler_MaxAttemptsExceeded(t *testing.T) {
RegisterT(t)
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveVerificationByEmail) error {
q.Result = &entity.EmailVerification{
- Key: "123456",
- CreatedAt: time.Now().Add(-20 * time.Minute),
- ExpiresAt: time.Now().Add(-5 * time.Minute),
+ Key: "some-long-link-key",
+ Code: "123456",
+ CreatedAt: time.Now(),
+ ExpiresAt: time.Now().Add(15 * time.Minute),
+ Attempts: 5,
}
return nil
})
+ server := mock.NewServer()
+ code, response := server.
+ OnTenant(mock.DemoTenant).
+ ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "123456" }`)
+
+ Expect(code).Equals(http.StatusBadRequest)
+ Expect(response.Body.String()).ContainsSubstring("Too many attempts")
+}
+
+func TestVerifySignInCodeHandler_WrongCode_FinalAttempt_InvalidatesCode(t *testing.T) {
+ RegisterT(t)
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveVerificationByEmail) error {
+ q.Result = &entity.EmailVerification{
+ Email: "[email protected]",
+ Key: "some-long-link-key",
+ Code: "123456",
+ CreatedAt: time.Now(),
+ ExpiresAt: time.Now().Add(15 * time.Minute),
+ Attempts: 4, // This is the 5th attempt (0-indexed)
+ }
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, c *cmd.IncrementVerificationAttempts) error {
+ return nil
+ })
+
+ verified := false
bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ verified = true
return nil
})
server := mock.NewServer()
- code, _ := server.
+ code, response := server.
OnTenant(mock.DemoTenant).
- ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "123456" }`)
+ ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "999999" }`)
Expect(code).Equals(http.StatusBadRequest)
+ Expect(verified).IsTrue()
+ Expect(response.Body.String()).ContainsSubstring("Too many attempts")
}
func TestVerifySignInCodeHandler_CorrectCode_ExistingUser(t *testing.T) {
RegisterT(t)
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveVerificationByEmail) error {
q.Result = &entity.EmailVerification{
- Key: "123456",
+ Key: "some-long-link-key",
+ Code: "123456",
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(15 * time.Minute),
}
return nil
})
+ bus.AddHandler(func(ctx context.Context, c *cmd.IncrementVerificationAttempts) error {
+ return nil
+ })
+
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
q.Result = mock.JonSnow
return nil
@@ -859,10 +932,11 @@ func TestVerifySignInCodeHandler_CorrectCode_ExistingUser(t *testing.T) {
func TestVerifySignInCodeHandler_CorrectCode_NewUser_WithoutName(t *testing.T) {
RegisterT(t)
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveVerificationByEmail) error {
q.Result = &entity.EmailVerification{
- Key: "123456",
+ Key: "some-long-link-key",
+ Code: "123456",
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(15 * time.Minute),
Name: "", // No name stored (legacy flow)
@@ -870,6 +944,10 @@ func TestVerifySignInCodeHandler_CorrectCode_NewUser_WithoutName(t *testing.T) {
return nil
})
+ bus.AddHandler(func(ctx context.Context, c *cmd.IncrementVerificationAttempts) error {
+ return nil
+ })
+
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
return app.ErrNotFound
})
@@ -886,10 +964,11 @@ func TestVerifySignInCodeHandler_CorrectCode_NewUser_WithoutName(t *testing.T) {
func TestVerifySignInCodeHandler_CorrectCode_NewUser_WithName(t *testing.T) {
RegisterT(t)
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveVerificationByEmail) error {
q.Result = &entity.EmailVerification{
- Key: "123456",
+ Key: "some-long-link-key",
+ Code: "123456",
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(15 * time.Minute),
Name: "New User", // Name stored (new flow)
@@ -897,6 +976,10 @@ func TestVerifySignInCodeHandler_CorrectCode_NewUser_WithName(t *testing.T) {
return nil
})
+ bus.AddHandler(func(ctx context.Context, c *cmd.IncrementVerificationAttempts) error {
+ return nil
+ })
+
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
return app.ErrNotFound
})
@@ -932,16 +1015,21 @@ func TestVerifySignInCodeHandler_CorrectCode_NewUser_PrivateTenant(t *testing.T)
server := mock.NewServer()
mock.DemoTenant.IsPrivate = true
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {
+ bus.AddHandler(func(ctx context.Context, q *query.GetActiveVerificationByEmail) error {
q.Result = &entity.EmailVerification{
- Key: "123456",
+ Key: "some-long-link-key",
+ Code: "123456",
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(15 * time.Minute),
}
return nil
})
+ bus.AddHandler(func(ctx context.Context, c *cmd.IncrementVerificationAttempts) error {
+ return nil
+ })
+
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
return app.ErrNotFound
})
@@ -953,28 +1041,10 @@ func TestVerifySignInCodeHandler_CorrectCode_NewUser_PrivateTenant(t *testing.T)
Expect(code).Equals(http.StatusForbidden)
}
-func TestVerifySignInCodeHandler_AlreadyVerifiedCode_ShouldReject(t *testing.T) {
- RegisterT(t)
-
- verifiedAt := time.Now().Add(-1 * time.Minute)
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {
- q.Result = &entity.EmailVerification{
- Email: "[email protected]",
- Key: "some-long-link-key",
- CreatedAt: time.Now().Add(-10 * time.Minute),
- ExpiresAt: time.Now().Add(5 * time.Minute),
- VerifiedAt: &verifiedAt,
- }
- return nil
- })
-
- server := mock.NewServer()
- code, _ := server.
- OnTenant(mock.DemoTenant).
- ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "123456" }`)
-
- Expect(code).Equals(http.StatusBadRequest)
-}
+// Note: AlreadyVerifiedCode test removed — the new flow uses GetActiveVerificationByEmail
+// which filters out verified records at the SQL level (verified_at IS NULL).
+// If all codes are verified, GetActiveVerificationByEmail returns ErrNotFound,
+// which is covered by TestVerifySignInCodeHandler_NoActiveVerification.
func TestResendSignInCodeHandler_ValidEmail(t *testing.T) {
RegisterT(t)
@@ -985,12 +1055,21 @@ func TestResendSignInCodeHandler_ValidEmail(t *testing.T) {
return nil
})
+ invalidated := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.InvalidateVerificationsByEmail) error {
+ Expect(c.Email).Equals("[email protected]")
+ Expect(c.Kind).Equals(enum.EmailVerificationKindSignIn)
+ invalidated = true
+ return nil
+ })
+
server := mock.NewServer()
code, _ := server.
OnTenant(mock.DemoTenant).
ExecutePost(handlers.ResendSignInCode(), `{ "email": "[email protected]" }`)
Expect(code).Equals(http.StatusOK)
+ Expect(invalidated).IsTrue()
Expect(saveKeyCmd.Key).HasLen(64)
Expect(saveKeyCmd.Code).HasLen(6)
Expect(saveKeyCmd.Request.GetKind()).Equals(enum.EmailVerificationKindSignIn)
diff --git a/app/models/cmd/tenant.go b/app/models/cmd/tenant.go
index 7877377b7..0b18f211f 100644
--- a/app/models/cmd/tenant.go
+++ b/app/models/cmd/tenant.go
@@ -64,5 +64,14 @@ type SetKeyAsVerified struct {
Key string
}
+type IncrementVerificationAttempts struct {
+ Key string
+}
+
+type InvalidateVerificationsByEmail struct {
+ Email string
+ Kind enum.EmailVerificationKind
+}
+
type InvalidatePreviousSignUpKeys struct {
}
diff --git a/app/models/entity/email_verification.go b/app/models/entity/email_verification.go
index 06825b395..47410a0de 100644
--- a/app/models/entity/email_verification.go
+++ b/app/models/entity/email_verification.go
@@ -12,11 +12,13 @@ type EmailVerification struct {
Email string
Name string
Key string
+ Code string
UserID int
Kind enum.EmailVerificationKind
CreatedAt time.Time
ExpiresAt time.Time
VerifiedAt *time.Time
+ Attempts int
}
// GenerateEmailVerificationKey returns a 64 chars key
diff --git a/app/models/query/tenant.go b/app/models/query/tenant.go
index 6cdba0fd3..f8e9daaf4 100644
--- a/app/models/query/tenant.go
+++ b/app/models/query/tenant.go
@@ -36,6 +36,14 @@ type GetVerificationByEmailAndCode struct {
Result *entity.EmailVerification
}
+type GetActiveVerificationByEmail struct {
+ Email string
+ Kind enum.EmailVerificationKind
+
+ // Output
+ Result *entity.EmailVerification
+}
+
type GetFirstTenant struct {
// Output
diff --git a/app/services/sqlstore/dbEntities/verification.go b/app/services/sqlstore/dbEntities/verification.go
index be01b5d66..2b8684388 100644
--- a/app/services/sqlstore/dbEntities/verification.go
+++ b/app/services/sqlstore/dbEntities/verification.go
@@ -13,11 +13,13 @@ type EmailVerification struct {
Name string `db:"name"`
Email string `db:"email"`
Key string `db:"key"`
+ Code dbx.NullString `db:"code"`
Kind enum.EmailVerificationKind `db:"kind"`
UserID dbx.NullInt `db:"user_id"`
CreatedAt time.Time `db:"created_at"`
ExpiresAt time.Time `db:"expires_at"`
VerifiedAt dbx.NullTime `db:"verified_at"`
+ Attempts int `db:"attempts"`
}
func (t *EmailVerification) ToModel() *entity.EmailVerification {
@@ -25,10 +27,12 @@ func (t *EmailVerification) ToModel() *entity.EmailVerification {
Name: t.Name,
Email: t.Email,
Key: t.Key,
+ Code: t.Code.String,
Kind: t.Kind,
CreatedAt: t.CreatedAt,
ExpiresAt: t.ExpiresAt,
VerifiedAt: nil,
+ Attempts: t.Attempts,
}
if t.VerifiedAt.Valid {
diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.go
index 2d825ea60..fc8026e39 100644
--- a/app/services/sqlstore/postgres/postgres.go
+++ b/app/services/sqlstore/postgres/postgres.go
@@ -118,8 +118,11 @@ func (s Service) Init() {
bus.AddHandler(getVerificationByKey)
bus.AddHandler(getVerificationByEmailAndCode)
+ bus.AddHandler(getActiveVerificationByEmail)
bus.AddHandler(saveVerificationKey)
bus.AddHandler(setKeyAsVerified)
+ bus.AddHandler(incrementVerificationAttempts)
+ bus.AddHandler(invalidateVerificationsByEmail)
bus.AddHandler(getPendingSignUpVerification)
bus.AddHandler(invalidatePreviousSignUpKeys)
diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.go
index bf46acdd5..8093a6531 100644
--- a/app/services/sqlstore/postgres/tenant.go
+++ b/app/services/sqlstore/postgres/tenant.go
@@ -130,7 +130,7 @@ func getVerificationByKey(ctx context.Context, q *query.GetVerificationByKey) er
return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
verification := dbEntities.EmailVerification{}
- query := "SELECT id, email, name, key, created_at, verified_at, expires_at, kind, user_id FROM email_verifications WHERE key = $1 AND kind = $2 LIMIT 1"
+ query := "SELECT id, email, name, key, code, created_at, verified_at, expires_at, kind, user_id, attempts FROM email_verifications WHERE key = $1 AND kind = $2 LIMIT 1"
err := trx.Get(&verification, query, q.Key, q.Kind)
if err != nil {
return errors.Wrap(err, "failed to get email verification by its key")
@@ -145,7 +145,7 @@ func getVerificationByEmailAndCode(ctx context.Context, q *query.GetVerification
return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
verification := dbEntities.EmailVerification{}
- query := "SELECT id, email, name, key, created_at, verified_at, expires_at, kind, user_id FROM email_verifications WHERE tenant_id = $1 AND email = $2 AND code = $3 AND kind = $4 LIMIT 1"
+ query := "SELECT id, email, name, key, code, created_at, verified_at, expires_at, kind, user_id, attempts FROM email_verifications WHERE tenant_id = $1 AND email = $2 AND code = $3 AND kind = $4 LIMIT 1"
err := trx.Get(&verification, query, tenant.ID, q.Email, q.Code, q.Kind)
if err != nil {
return errors.Wrap(err, "failed to get email verification by email and code")
@@ -188,6 +188,52 @@ func setKeyAsVerified(ctx context.Context, c *cmd.SetKeyAsVerified) error {
})
}
+func getActiveVerificationByEmail(ctx context.Context, q *query.GetActiveVerificationByEmail) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ verification := dbEntities.EmailVerification{}
+
+ query := `SELECT id, email, name, key, code, created_at, verified_at, expires_at, kind, user_id, attempts
+ FROM email_verifications
+ WHERE tenant_id = $1 AND email = $2 AND kind = $3
+ AND verified_at IS NULL AND expires_at > $4
+ ORDER BY created_at DESC
+ LIMIT 1`
+ err := trx.Get(&verification, query, tenant.ID, q.Email, q.Kind, time.Now())
+ if err != nil {
+ return errors.Wrap(err, "failed to get active email verification by email")
+ }
+
+ q.Result = verification.ToModel()
+ return nil
+ })
+}
+
+func incrementVerificationAttempts(ctx context.Context, c *cmd.IncrementVerificationAttempts) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ _, err := trx.Execute(
+ "UPDATE email_verifications SET attempts = attempts + 1 WHERE tenant_id = $1 AND key = $2",
+ tenant.ID, c.Key,
+ )
+ if err != nil {
+ return errors.Wrap(err, "failed to increment verification attempts")
+ }
+ return nil
+ })
+}
+
+func invalidateVerificationsByEmail(ctx context.Context, c *cmd.InvalidateVerificationsByEmail) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ _, err := trx.Execute(
+ "UPDATE email_verifications SET verified_at = $1 WHERE tenant_id = $2 AND email = $3 AND kind = $4 AND verified_at IS NULL",
+ time.Now(), tenant.ID, c.Email, c.Kind,
+ )
+ if err != nil {
+ return errors.Wrap(err, "failed to invalidate verifications for email '%s'", c.Email)
+ }
+ return nil
+ })
+}
+
func createTenant(ctx context.Context, c *cmd.CreateTenant) error {
return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
now := time.Now()
@@ -253,10 +299,10 @@ func getPendingSignUpVerification(ctx context.Context, q *query.GetPendingSignUp
return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
verification := dbEntities.EmailVerification{}
- query := `SELECT id, email, name, key, created_at, verified_at, expires_at, kind, user_id
- FROM email_verifications
+ query := `SELECT id, email, name, key, code, created_at, verified_at, expires_at, kind, user_id, attempts
+ FROM email_verifications
WHERE tenant_id = $1 AND kind = $2 AND verified_at IS NULL
- ORDER BY created_at DESC
+ ORDER BY created_at DESC
LIMIT 1`
err := trx.Get(&verification, query, tenant.ID, enum.EmailVerificationKindSignUp)
if err != nil {
diff --git a/migrations/202605011200_add_verification_attempts.sql b/migrations/202605011200_add_verification_attempts.sql
new file mode 100644
index 000000000..54f47392a
--- /dev/null
+++ b/migrations/202605011200_add_verification_attempts.sql
@@ -0,0 +1 @@
+ALTER TABLE email_verifications ADD COLUMN attempts SMALLINT NOT NULL DEFAULT 0;
diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsx
index fac58a92d..96fe22026 100644
--- a/public/components/common/SignInControl.tsx
+++ b/public/components/common/SignInControl.tsx
@@ -32,6 +32,7 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (props
const [code, setCode] = useState("")
const [error, setError] = useState<Failure | undefined>(undefined)
const [resendMessage, setResendMessage] = useState("")
+ const [lockedOut, setLockedOut] = useState(false)
const forceShowEmailForm = (e: React.MouseEvent<HTMLAnchorElement>) => {
e.preventDefault()
@@ -99,6 +100,12 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (props
// Handle validation errors - convert data object to Failure format
const data = result.data as Record<string, string> | undefined
if (data && typeof data === "object") {
+ // Check if locked out due to too many attempts
+ if (data.code && data.code.includes("Too many attempts")) {
+ setLockedOut(true)
+ setError(undefined)
+ return
+ }
const errors = Object.entries(data).map(([field, message]) => ({
field,
message,
@@ -117,6 +124,7 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (props
if (result.ok) {
setError(undefined)
setCode("")
+ setLockedOut(false)
setResendMessage(i18n._({ id: "signin.code.sent", message: "A new code has been sent to your email." }))
} else if (result.error) {
setError(result.error)
@@ -127,6 +135,7 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (props
const handleFormSubmit = async (e: React.FormEvent) => {
e.preventDefault()
+ setResendMessage("")
// Form submission handler that routes to the correct function based on step
if (emailSignInStep === EmailSigninStep.EnterEmail) {
await signIn()
@@ -153,6 +162,7 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (props
)
}
if (emailSignInStep === EmailSigninStep.EnterCode) {
+ if (lockedOut) return null
return (
<Button className="w-full justify-center" type="submit" variant="primary" disabled={code.length !== 6}>
<Trans id="action.submit">Submit</Trans>
@@ -251,8 +261,25 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (props
}
function renderCodeField(): React.ReactNode {
+ if (lockedOut) {
+ return (
+ <>
+ <p className="text-muted mb-2 text-left">
+ <Trans id="signin.code.locked">Your code has expired due to too many incorrect attempts. Please request a new one.</Trans>
+ </p>
+ {resendMessage && <p className="text-green-700 mt-2">{resendMessage}</p>}
+ <div className="pt-3">
+ <Button className="w-full justify-center" variant="primary" onClick={resendCode}>
+ <Trans id="signin.code.getnew">Get a new code</Trans>
+ </Button>
+ </div>
+ </>
+ )
+ }
+
return (
<>
+ {resendMessage && <p className="text-green-700 mb-2">{resendMessage}</p>}
<p className="text-muted mb-2 text-left">
<Trans id="signin.code.instruction">
Please type in the code we just sent to <strong>{email}</strong>
@@ -279,7 +306,6 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (props
placeholder={i18n._({ id: "signin.code.placeholder", message: "Type in the code here" })}
maxLength={6}
/>
- {resendMessage && <p className="text-green-700 mt-2">{resendMessage}</p>}
<p className="text-center mt-2 text-muted text-left">
<a
href="#"