Open platform to collect and prioritize feedback
First stab at login codes.
Matt Roberts4e2e87931456
diff --git a/app/actions/signin.go b/app/actions/signin.goindex 4b5a3ebeb..8836394d3 100644--- a/app/actions/signin.go+++ b/app/actions/signin.go@@ -14,13 +14,13 @@ import (// SignInByEmail happens when user request to sign in by emailtype SignInByEmail struct {- Email string `json:"email" format:"lower"`- VerificationKey string+ Email string `json:"email" format:"lower"`+ VerificationCode string}func NewSignInByEmail() *SignInByEmail {return &SignInByEmail{- VerificationKey: entity.GenerateEmailVerificationKey(),+ VerificationCode: entity.GenerateEmailVerificationCode(),}}@@ -74,6 +74,45 @@ func (action *SignInByEmail) GetKind() enum.EmailVerificationKind {return enum.EmailVerificationKindSignIn}+// VerifySignInCode happens when user enters the verification code received via email+type VerifySignInCode struct {+ Email string `json:"email" format:"lower"`+ Code string `json:"code"`+}++// IsAuthorized returns true if current user is authorized to perform this action+func (action *VerifySignInCode) IsAuthorized(ctx context.Context, user *entity.User) bool {+ return true+}++// Validate if current model is valid+func (action *VerifySignInCode) Validate(ctx context.Context, user *entity.User) *validate.Result {+ result := validate.Success()++ if action.Email == "" {+ result.AddFieldFailure("email", propertyIsRequired(ctx, "email"))+ } else {+ messages := validate.Email(ctx, action.Email)+ result.AddFieldFailure("email", messages...)+ }++ if action.Code == "" {+ result.AddFieldFailure("code", propertyIsRequired(ctx, "code"))+ } else if len(action.Code) != 6 {+ result.AddFieldFailure("code", "Verification code must be 6 digits")+ } else {+ // Validate that code contains only digits+ for _, char := range action.Code {+ if char < '0' || char > '9' {+ result.AddFieldFailure("code", "Verification code must contain only digits")+ break+ }+ }+ }++ return result+}+// CompleteProfile happens when users completes their profile during first time sign intype CompleteProfile struct {Kind enum.EmailVerificationKind `json:"kind"`diff --git a/app/actions/signin_test.go b/app/actions/signin_test.goindex 156ba5952..90efad559 100644--- a/app/actions/signin_test.go+++ b/app/actions/signin_test.go@@ -32,7 +32,8 @@ func TestSignInByEmail_ShouldHaveVerificationKey(t *testing.T) {result := action.Validate(context.Background(), nil)ExpectSuccess(result)- Expect(action.VerificationKey).IsNotEmpty()+ Expect(action.VerificationCode).IsNotEmpty()+ Expect(len(action.VerificationCode)).Equals(6)}func TestCompleteProfile_EmptyNameAndKey(t *testing.T) {@@ -52,3 +53,55 @@ func TestCompleteProfile_LongName(t *testing.T) {result := action.Validate(context.Background(), nil)ExpectFailed(result, "name", "key")}++func TestVerifySignInCode_EmptyEmail(t *testing.T) {+ RegisterT(t)++ action := actions.VerifySignInCode{Email: "", Code: "123456"}+ result := action.Validate(context.Background(), nil)+ ExpectFailed(result, "email")+}++func TestVerifySignInCode_InvalidEmail(t *testing.T) {+ RegisterT(t)++ action := actions.VerifySignInCode{Email: "invalid", Code: "123456"}+ result := action.Validate(context.Background(), nil)+ ExpectFailed(result, "email")+}++func TestVerifySignInCode_EmptyCode(t *testing.T) {+ RegisterT(t)++ action := actions.VerifySignInCode{Email: "[email protected]", Code: ""}+ result := action.Validate(context.Background(), nil)+ ExpectFailed(result, "code")+}++func TestVerifySignInCode_InvalidCodeLength(t *testing.T) {+ RegisterT(t)++ action := actions.VerifySignInCode{Email: "[email protected]", Code: "12345"}+ result := action.Validate(context.Background(), nil)+ ExpectFailed(result, "code")++ action2 := actions.VerifySignInCode{Email: "[email protected]", Code: "1234567"}+ result2 := action2.Validate(context.Background(), nil)+ ExpectFailed(result2, "code")+}++func TestVerifySignInCode_NonNumericCode(t *testing.T) {+ RegisterT(t)++ action := actions.VerifySignInCode{Email: "[email protected]", Code: "12345A"}+ result := action.Validate(context.Background(), nil)+ ExpectFailed(result, "code")+}++func TestVerifySignInCode_ValidCodeAndEmail(t *testing.T) {+ RegisterT(t)++ action := actions.VerifySignInCode{Email: "[email protected]", Code: "123456"}+ result := action.Validate(context.Background(), nil)+ ExpectSuccess(result)+}diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 389cb1888..0e35a4222 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -123,6 +123,8 @@ func routes(r *web.Engine) *web.Engine {r.Get("/invite/verify", handlers.VerifySignInKey(enum.EmailVerificationKindUserInvitation))r.Post("/_api/signin/complete", handlers.CompleteSignInProfile())r.Post("/_api/signin", handlers.SignInByEmail())+ r.Post("/_api/signin/verify", handlers.VerifySignInCode())+ r.Post("/_api/signin/resend", handlers.ResendSignInCode())// Block if it's private tenant with unauthenticated userr.Use(middlewares.CheckTenantPrivacy())diff --git a/app/handlers/signin.go b/app/handlers/signin.goindex 1f2812019..1c55ba916 100644--- a/app/handlers/signin.go+++ b/app/handlers/signin.go@@ -57,7 +57,7 @@ func NotInvitedPage() web.HandlerFunc {}}-// SignInByEmail sends a new email with verification key+// SignInByEmail sends a new email with verification codefunc SignInByEmail() web.HandlerFunc {return func(c *web.Context) error {action := actions.NewSignInByEmail()@@ -66,15 +66,115 @@ func SignInByEmail() web.HandlerFunc {}err := bus.Dispatch(c, &cmd.SaveVerificationKey{- Key: action.VerificationKey,- Duration: 30 * time.Minute,+ Key: action.VerificationCode,+ Duration: 15 * time.Minute,Request: action,})if err != nil {return c.Failure(err)}- c.Enqueue(tasks.SendSignInEmail(action.Email, action.VerificationKey))+ c.Enqueue(tasks.SendSignInEmail(action.Email, action.VerificationCode))++ return c.Ok(web.Map{})+ }+}++// VerifySignInCode verifies the code entered by the user and signs them in+func VerifySignInCode() web.HandlerFunc {+ return func(c *web.Context) error {+ action := &actions.VerifySignInCode{}+ if result := c.BindTo(action); !result.Ok {+ return c.HandleValidation(result)+ }++ // Get verification by email and code+ verification := &query.GetVerificationByEmailAndCode{+ Email: action.Email,+ Code: action.Code,+ Kind: enum.EmailVerificationKindSignIn,+ }+ err := bus.Dispatch(c, verification)+ if err != nil {+ if errors.Cause(err) == app.ErrNotFound {+ return c.BadRequest(web.Map{+ "code": "Invalid or expired verification code",+ })+ }+ return c.Failure(err)+ }++ result := verification.Result++ // Check if already verified (with grace period)+ if result.VerifiedAt != nil {+ if time.Since(*result.VerifiedAt) > 5*time.Minute {+ return c.Gone()+ }+ } else {+ // Check if expired+ if time.Now().After(result.ExpiresAt) {+ // Mark as verified to prevent reuse+ _ = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: action.Code})+ return c.Gone()+ }+ }++ // Check if user exists+ userByEmail := &query.GetUserByEmail{Email: result.Email}+ err = bus.Dispatch(c, userByEmail)+ if err != nil {+ if errors.Cause(err) == app.ErrNotFound {+ // User doesn't exist, need to complete profile+ if c.Tenant().IsPrivate {+ return c.Forbidden()+ }+ return c.Ok(web.Map{+ "showProfileCompletion": true,+ })+ }+ return c.Failure(err)+ }++ // Mark code as verified+ err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: action.Code})+ if err != nil {+ return c.Failure(err)+ }++ // Authenticate user+ webutil.AddAuthUserCookie(c, userByEmail.Result)++ return c.Ok(web.Map{})+ }+}++// ResendSignInCode invalidates the previous code and sends a new one+func ResendSignInCode() web.HandlerFunc {+ return func(c *web.Context) error {+ // Create new sign-in action with new code+ action := actions.NewSignInByEmail()+ if result := c.BindTo(action); !result.Ok {+ return c.HandleValidation(result)+ }++ // Authorization check+ if !action.IsAuthorized(c, c.User()) {+ return c.Forbidden()+ }++ // Save new verification code+ err := bus.Dispatch(c, &cmd.SaveVerificationKey{+ Key: action.VerificationCode,+ Duration: 15 * time.Minute,+ Request: action,+ })+ if err != nil {+ return c.Failure(err)+ }++ // Send new email+ c.Enqueue(tasks.SendSignInEmail(action.Email, action.VerificationCode))return c.Ok(web.Map{})}diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.goindex 0bff24c2b..01c508a70 100644--- a/app/handlers/signin_test.go+++ b/app/handlers/signin_test.go@@ -49,7 +49,7 @@ func TestSignInByEmailHandler_WithEmail(t *testing.T) {ExecutePost(handlers.SignInByEmail(), `{ "email": "[email protected]" }`)Expect(code).Equals(http.StatusOK)- Expect(saveKeyCmd.Key).HasLen(64)+ Expect(saveKeyCmd.Key).HasLen(6)Expect(saveKeyCmd.Request.GetKind()).Equals(enum.EmailVerificationKindSignIn)Expect(saveKeyCmd.Request.GetEmail()).Equals("[email protected]")Expect(saveKeyCmd.Request.GetName()).Equals("")@@ -642,6 +642,161 @@ func TestSignInPageHandler_PrivateTenant_UnauthenticatedUser(t *testing.T) {Expect(code).Equals(http.StatusOK)}+func TestVerifySignInCodeHandler_InvalidCode(t *testing.T) {+ RegisterT(t)++ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {+ return app.ErrNotFound+ })++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "999999" }`)++ Expect(code).Equals(http.StatusBadRequest)+}++func TestVerifySignInCodeHandler_ExpiredCode(t *testing.T) {+ RegisterT(t)++ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {+ q.Result = &entity.EmailVerification{+ Email: "[email protected]",+ Key: "123456",+ CreatedAt: time.Now().Add(-20 * time.Minute),+ ExpiresAt: time.Now().Add(-5 * time.Minute),+ }+ return nil+ })++ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {+ return nil+ })++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "123456" }`)++ Expect(code).Equals(http.StatusGone)+}++func TestVerifySignInCodeHandler_CorrectCode_ExistingUser(t *testing.T) {+ RegisterT(t)++ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {+ q.Result = &entity.EmailVerification{+ Email: "[email protected]",+ Key: "123456",+ CreatedAt: time.Now(),+ ExpiresAt: time.Now().Add(15 * time.Minute),+ }+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {+ q.Result = mock.JonSnow+ return nil+ })++ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {+ return nil+ })++ server := mock.NewServer()+ code, response := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "123456" }`)++ Expect(code).Equals(http.StatusOK)+ ExpectFiderAuthCookie(response, mock.JonSnow)+}++func TestVerifySignInCodeHandler_CorrectCode_NewUser(t *testing.T) {+ RegisterT(t)++ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {+ q.Result = &entity.EmailVerification{+ Email: "[email protected]",+ Key: "123456",+ CreatedAt: time.Now(),+ ExpiresAt: time.Now().Add(15 * time.Minute),+ }+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {+ return app.ErrNotFound+ })++ server := mock.NewServer()+ code, response := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "123456" }`)++ Expect(code).Equals(http.StatusOK)+ Expect(response.Body.String()).ContainsSubstring(`"showProfileCompletion":true`)+}++func TestVerifySignInCodeHandler_CorrectCode_NewUser_PrivateTenant(t *testing.T) {+ RegisterT(t)++ server := mock.NewServer()+ mock.DemoTenant.IsPrivate = true++ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {+ q.Result = &entity.EmailVerification{+ Email: "[email protected]",+ Key: "123456",+ CreatedAt: time.Now(),+ ExpiresAt: time.Now().Add(15 * time.Minute),+ }+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {+ return app.ErrNotFound+ })++ code, _ := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.VerifySignInCode(), `{ "email": "[email protected]", "code": "123456" }`)++ Expect(code).Equals(http.StatusForbidden)+}++func TestResendSignInCodeHandler_ValidEmail(t *testing.T) {+ RegisterT(t)++ var saveKeyCmd *cmd.SaveVerificationKey+ bus.AddHandler(func(ctx context.Context, c *cmd.SaveVerificationKey) error {+ saveKeyCmd = c+ return nil+ })++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.ResendSignInCode(), `{ "email": "[email protected]" }`)++ Expect(code).Equals(http.StatusOK)+ Expect(saveKeyCmd.Key).HasLen(6)+ Expect(saveKeyCmd.Request.GetKind()).Equals(enum.EmailVerificationKindSignIn)+ Expect(saveKeyCmd.Request.GetEmail()).Equals("[email protected]")+}++func TestResendSignInCodeHandler_InvalidEmail(t *testing.T) {+ RegisterT(t)++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ ExecutePost(handlers.ResendSignInCode(), `{ "email": "invalid" }`)++ Expect(code).Equals(http.StatusBadRequest)+}+func ExpectFiderAuthCookie(response *httptest.ResponseRecorder, expected *entity.User) {cookies := response.Header()["Set-Cookie"]if expected == nil {diff --git a/app/models/entity/email_verification.go b/app/models/entity/email_verification.goindex 639f6707b..06825b395 100644--- a/app/models/entity/email_verification.go+++ b/app/models/entity/email_verification.go@@ -23,3 +23,8 @@ type EmailVerification struct {func GenerateEmailVerificationKey() string {return rand.String(64)}++// GenerateEmailVerificationCode returns a 6 digit numeric code+func GenerateEmailVerificationCode() string {+ return rand.StringNumeric(6)+}diff --git a/app/models/query/tenant.go b/app/models/query/tenant.goindex 41c9db5ff..fddc71c7a 100644--- a/app/models/query/tenant.go+++ b/app/models/query/tenant.go@@ -29,6 +29,15 @@ type GetVerificationByKey struct {Result *entity.EmailVerification}+type GetVerificationByEmailAndCode struct {+ Email string+ Code string+ Kind enum.EmailVerificationKind++ // Output+ Result *entity.EmailVerification+}+type GetFirstTenant struct {// Outputdiff --git a/app/pkg/rand/random.go b/app/pkg/rand/random.goindex 42c6e0267..fd4782a9b 100644--- a/app/pkg/rand/random.go+++ b/app/pkg/rand/random.go@@ -6,6 +6,7 @@ import ()var chars = []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")+var numericChars = []byte("0123456789")// String returns a random string of given lengthfunc String(n int) string {@@ -25,3 +26,22 @@ func String(n int) string {return string(bytes)}++// StringNumeric returns a random numeric string of given length+func StringNumeric(n int) string {+ if n <= 0 {+ return ""+ }++ bytes := make([]byte, n)+ charsetLen := big.NewInt(int64(len(numericChars)))+ for i := 0; i < n; i++ {+ c, err := rand.Int(rand.Reader, charsetLen)+ if err != nil {+ panic(err)+ }+ bytes[i] = numericChars[c.Int64()]+ }++ return string(bytes)+}diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.goindex e628494fb..f2247702a 100644--- a/app/services/sqlstore/postgres/postgres.go+++ b/app/services/sqlstore/postgres/postgres.go@@ -114,6 +114,7 @@ func (s Service) Init() {bus.AddHandler(updateTenantAdvancedSettings)bus.AddHandler(getVerificationByKey)+ bus.AddHandler(getVerificationByEmailAndCode)bus.AddHandler(saveVerificationKey)bus.AddHandler(setKeyAsVerified)bus.AddHandler(getPendingSignUpVerification)diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.goindex 31ae9fdf5..5473ad2c4 100644--- a/app/services/sqlstore/postgres/tenant.go+++ b/app/services/sqlstore/postgres/tenant.go@@ -213,6 +213,21 @@ func getVerificationByKey(ctx context.Context, q *query.GetVerificationByKey) er})}+func getVerificationByEmailAndCode(ctx context.Context, q *query.GetVerificationByEmailAndCode) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ verification := dbEmailVerification{}++ 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 key = $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")+ }++ q.Result = verification.toModel()+ return nil+ })+}+func saveVerificationKey(ctx context.Context, c *cmd.SaveVerificationKey) error {return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {var userID anydiff --git a/app/tasks/signin.go b/app/tasks/signin.goindex 4980f4914..0b66f6776 100644--- a/app/tasks/signin.go+++ b/app/tasks/signin.go@@ -9,11 +9,12 @@ import ()// SendSignInEmail is used to send the sign in email to requestor-func SendSignInEmail(email, verificationKey string) worker.Task {+func SendSignInEmail(email, verificationCode string) worker.Task {return describe("Send sign in email", func(c *worker.Context) error {to := dto.NewRecipient("", email, dto.Props{"siteName": c.Tenant().Name,- "link": link(web.BaseURL(c), "/signin/verify?k=%s", verificationKey),+ "code": verificationCode,+ "link": link(web.BaseURL(c), "/signin/verify?k=%s", verificationCode),})bus.Publish(c, &cmd.SendMail{diff --git a/app/tasks/signin_test.go b/app/tasks/signin_test.goindex ee3ce22da..a554c487f 100644--- a/app/tasks/signin_test.go+++ b/app/tasks/signin_test.go@@ -39,6 +39,7 @@ func TestSendSignInEmailTask(t *testing.T) {Address: "[email protected]",Props: dto.Props{"siteName": mock.DemoTenant.Name,+ "code": "9876","link": "<a href='http://domain.com/signin/verify?k=9876'>http://domain.com/signin/verify?k=9876</a>",},})diff --git a/e2e/step_definitions/fns.ts b/e2e/step_definitions/fns.tsindex 03096b022..acb118196 100644--- a/e2e/step_definitions/fns.ts+++ b/e2e/step_definitions/fns.ts@@ -29,3 +29,19 @@ export async function getLatestLinkSentTo(address: string): Promise<string> {return result[0]}++export async function getLatestCodeSentTo(address: string): Promise<string> {+ await delay(1000)++ const response = await fetch(`http://localhost:8025/api/v2/search?kind=to&query=${address}`)+ const responseBody = await response.json()+ const emailHtml = responseBody.items[0].Content.Body+ // Look for 6-digit code in the email+ const reg = /\b\d{6}\b/+ const result = reg.exec(emailHtml)+ if (!result) {+ throw new Error("Could not find a 6-digit code in email content.")+ }++ return result[0]+}diff --git a/e2e/step_definitions/home.steps.ts b/e2e/step_definitions/home.steps.tsindex 8ca282a53..3b3059701 100644--- a/e2e/step_definitions/home.steps.ts+++ b/e2e/step_definitions/home.steps.ts@@ -1,7 +1,7 @@import { Given, Then } from "@cucumber/cucumber"import { FiderWorld } from "../world"import expect from "expect"-import { getLatestLinkSentTo } from "./fns"+import { getLatestCodeSentTo } from "./fns"Given("I go to the home page", async function (this: FiderWorld) {await this.page.goto(`https://${this.tenantName}.dev.fider.io:3000/`)@@ -50,8 +50,14 @@ Given("I click submit your feedback", async function () {Given("I click on the confirmation link", async function (this: FiderWorld) {const userEmail = `$user-${this.tenantName}@fider.io`- const activationLink = await getLatestLinkSentTo(userEmail)- await this.page.goto(activationLink)+ const code = await getLatestCodeSentTo(userEmail)++ // Enter the code in the UI+ await this.page.type("#input-code", code)+ await this.page.click("button[type='submit']")++ // Wait for navigation after successful code verification+ await this.page.waitForLoadState("networkidle")})Then("I should be on the complete profile page", async function (this: FiderWorld) {@@ -74,7 +80,8 @@ Given("I click submit", async function () {Then("I should be on the confirmation link page", async function (this: FiderWorld) {const userEmail = `$user-${this.tenantName}@fider.io`- await expect(this.page.getByText(`We have just sent a confirmation link to ${userEmail}`)).toBeVisible()+ // Updated to check for code entry message instead of link message+ await expect(this.page.getByText(`Please type in the code we just sent to ${userEmail}`)).toBeVisible()})Then("I should see {string} as the draft post title", async function (this: FiderWorld, title: string) {diff --git a/e2e/step_definitions/user.steps.ts b/e2e/step_definitions/user.steps.tsindex 6d61c2b58..7efe85103 100644--- a/e2e/step_definitions/user.steps.ts+++ b/e2e/step_definitions/user.steps.ts@@ -1,6 +1,6 @@import { Given } from "@cucumber/cucumber"import { FiderWorld } from "e2e/world"-import { getLatestLinkSentTo, isAuthenticated, isAuthenticatedAsUser } from "./fns"+import { getLatestCodeSentTo, isAuthenticated, isAuthenticatedAsUser } from "./fns"Given("I sign in as {string}", async function (this: FiderWorld, userName: string) {if (await isAuthenticatedAsUser(this.page, userName)) {@@ -17,6 +17,11 @@ Given("I sign in as {string}", async function (this: FiderWorld, userName: strinawait this.page.type(".c-signin-control #input-email", userEmail)await this.page.click(".c-signin-control .c-button--primary")- const activationLink = await getLatestLinkSentTo(userEmail)- await this.page.goto(activationLink)+ // Get the code from email and enter it+ const code = await getLatestCodeSentTo(userEmail)+ await this.page.type("#input-code", code)+ await this.page.click("button[type='submit']")++ // Wait for navigation after successful code verification+ await this.page.waitForLoadState("networkidle")})diff --git a/locale/en/client.json b/locale/en/client.jsonindex 7df12f02f..ec03a924a 100644--- a/locale/en/client.json+++ b/locale/en/client.json@@ -91,6 +91,10 @@"label.voters": "Voters","labels.notagsavailable": "No tags available","labels.notagsselected": "No tags selected",+ "legal.agreement": "I have read and agree to the <0/> and <1/>.",+ "legal.notice": "By signing in, you agree to the <2/><0/> and <1/>.",+ "legal.privacypolicy": "Privacy Policy",+ "legal.termsofservice": "Terms of Service","linkmodal.insert": "Insert Link","linkmodal.text.label": "Text to display","linkmodal.text.placeholder": "Enter link text",@@ -100,10 +104,6 @@"linkmodal.url.label": "URL","linkmodal.url.placeholder": "https://example.com","linkmodal.url.required": "URL is required",- "legal.agreement": "I have read and agree to the <0/> and <1/>.",- "legal.notice": "By signing in, you agree to the <2/><0/> and <1/>.",- "legal.privacypolicy": "Privacy Policy",- "legal.termsofservice": "Terms of Service","menu.administration": "Administration","menu.mysettings": "My Settings","menu.signout": "Sign out",@@ -200,6 +200,14 @@"showpost.responseform.text.placeholder": "What's going on with this post? Let your users know what are your plans...","showpost.votespanel.more": "+{extraVotesCount} more","showpost.votespanel.seedetails": "see details",+ "signin.code.edit": "Edit",+ "signin.code.expired": "This code has expired. Please request a new one.",+ "signin.code.getnew": "Get a new code",+ "signin.code.instruction": "Please type in the code we just sent to <0>{email}</0>",+ "signin.code.invalid": "The code you entered is invalid. Please try again.",+ "signin.code.placeholder": "Type in the code here",+ "signin.code.sent": "A new code has been sent to your email.",+ "signin.code.submit": "Submit","signin.email.placeholder": "Email address","signin.message.email": "Continue with Email","signin.message.emaildisabled": "Email authentication has been disabled by an administrator. If you have an administrator account and need to bypass this restriction, please <0>click here</0>.",diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsxindex 6044e8c4e..4d417320c 100644--- a/public/components/common/SignInControl.tsx+++ b/public/components/common/SignInControl.tsx@@ -19,8 +19,11 @@ interface SignInControlProps {export const SignInControl: React.FunctionComponent<SignInControlProps> = (props) => {const fider = useFider()const [showEmailForm, setShowEmailForm] = useState(fider.session.tenant ? fider.session.tenant.isEmailAuthAllowed : true)+ const [showCodeEntry, setShowCodeEntry] = useState(false)const [email, setEmail] = useState("")+ const [code, setCode] = useState("")const [error, setError] = useState<Failure | undefined>(undefined)+ const [resendMessage, setResendMessage] = useState("")const signInText = props.signInButtonText || i18n._({ id: "action.signin", message: "Sign in" })@@ -39,20 +42,53 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (propsdoPreSigninAction()}+ const editEmail = () => {+ setShowCodeEntry(false)+ setCode("")+ setError(undefined)+ setResendMessage("")+ }+const signIn = async () => {await doPreSigninAction()const result = await actions.signIn(email)if (result.ok) {- setEmail("")setError(undefined)- if (props.onEmailSent) {- props.onEmailSent(email)+ setShowCodeEntry(true)+ // Don't call onEmailSent - we're showing code entry inline now+ } else if (result.error) {+ setError(result.error)+ }+ }++ const verifyCode = async () => {+ const result = await actions.verifySignInCode(email, code)+ if (result.ok) {+ const data = result.data as { showProfileCompletion?: boolean } | undefined+ if (data && data.showProfileCompletion) {+ // User needs to complete profile - reload to show profile completion+ location.reload()+ } else {+ // User is authenticated - reload to refresh the page+ location.reload()}} else if (result.error) {setError(result.error)}}+ const resendCode = async () => {+ setResendMessage("")+ const result = await actions.resendSignInCode(email)+ if (result.ok) {+ setError(undefined)+ setCode("")+ setResendMessage(i18n._({ id: "signin.code.sent", message: "A new code has been sent to your email." }))+ } else if (result.error) {+ setError(result.error)+ }+ }+const providersLen = fider.settings.oauth.lengthif (!isCookieEnabled()) {@@ -82,23 +118,58 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = (props{props.useEmail &&(showEmailForm ? (<div className="pt-3">- <Form error={error}>- <Input- className="text-left"- field="email"- value={email}- autoFocus={!device.isTouch()}- onChange={setEmail}- placeholder={i18n._({ id: "signin.email.placeholder", message: "Email address" })}- />- <Button className="w-full justify-center" type="submit" variant="primary" disabled={email === ""} onClick={signIn}>- {signInText}- </Button>- </Form>- {!fider.session.tenant.isEmailAuthAllowed && (- <p className="text-red-700 mt-1">- <Trans id="signin.message.onlyadmins">Currently only allowed to sign in to an administrator account</Trans>- </p>+ {!showCodeEntry ? (+ <Form error={error}>+ <Input+ className="text-left"+ field="email"+ value={email}+ autoFocus={!device.isTouch()}+ onChange={setEmail}+ placeholder={i18n._({ id: "signin.email.placeholder", message: "Email address" })}+ />+ <Button className="w-full justify-center" type="submit" variant="primary" disabled={email === ""} onClick={signIn}>+ {signInText}+ </Button>+ {!fider.session.tenant.isEmailAuthAllowed && (+ <p className="text-red-700 mt-1">+ <Trans id="signin.message.onlyadmins">Currently only allowed to sign in to an administrator account</Trans>+ </p>+ )}+ </Form>+ ) : (+ <div>+ <p className="text-muted mb-2">+ <Trans id="signin.code.instruction">+ Please type in the code we just sent to <strong>{email}</strong>+ </Trans>{" "}+ <a href="#" className="text-link" onClick={(e) => { e.preventDefault(); editEmail(); }}>+ <Trans id="signin.code.edit">Edit</Trans>+ </a>+ </p>+ <Form error={error}>+ <Input+ className="text-left"+ field="code"+ value={code}+ autoFocus={!device.isTouch()}+ onChange={setCode}+ placeholder={i18n._({ id: "signin.code.placeholder", message: "Type in the code here" })}+ maxLength={6}+ />+ <Button className="w-full justify-center" type="submit" variant="primary" disabled={code.length !== 6} onClick={verifyCode}>+ <Trans id="signin.code.submit">Submit</Trans>+ </Button>+ </Form>+ {resendMessage && (+ <p className="text-green-700 mt-2">{resendMessage}</p>+ )}+ <p className="text-center mt-2">+ <a href="#" className="text-link" onClick={(e) => { e.preventDefault(); resendCode(); }}>+ <Trans id="signin.code.getnew">Get a new code</Trans>+ </a>+ </p>+ </div>)}</div>) : (diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.tsindex 8e71231c6..fbbbf3578 100644--- a/public/services/actions/tenant.ts+++ b/public/services/actions/tenant.ts@@ -54,11 +54,16 @@ export const checkAvailability = async (subdomain: string): Promise<Result<Checkreturn await http.get<CheckAvailabilityResponse>(`/_api/tenants/${subdomain}/availability`)}-export const signIn = async (email: string, code?: string): Promise<Result> => {- return await http.post("/_api/signin", {- email,- code,- })+export const signIn = async (email: string): Promise<Result> => {+ return await http.post("/_api/signin", { email })+}++export const verifySignInCode = async (email: string, code: string): Promise<Result> => {+ return await http.post("/_api/signin/verify", { email, code })+}++export const resendSignInCode = async (email: string): Promise<Result> => {+ return await http.post("/_api/signin/resend", { email })}export const completeProfile = async (kind: EmailVerificationKind, key: string, name: string): Promise<Result> => {diff --git a/views/email/signin_email.html b/views/email/signin_email.htmlindex 63d17b932..20eb26bd3 100644--- a/views/email/signin_email.html+++ b/views/email/signin_email.html@@ -6,7 +6,16 @@<h2 style="color:#1c262d">{{ "email.greetings" | translate }}</h2><p style="color:#1c262d">{{ "email.signin_email.text" | translate }}</p><p style="color:#1c262d">{{ translate "email.signin_email.confirmation" (dict "siteName" (.siteName | stripHtml)) | html }}</p>- <p>{{ .link | html }}</p>++ <div style="margin: 30px 0; text-align: center;">+ <p style="color:#1c262d; font-size: 14px; margin-bottom: 10px;"><strong>{{ "email.signin_email.your_code" | translate }}</strong></p>+ <div style="background: #f5f7f9; border: 2px solid #dfe3e8; border-radius: 8px; padding: 20px; display: inline-block;">+ <p style="font-size: 36px; font-weight: bold; letter-spacing: 8px; color: #1c262d; margin: 0; font-family: 'Courier New', monospace;">{{ .code }}</p>+ </div>+ <p style="color:#6c757d; font-size: 12px; margin-top: 10px;">{{ "email.signin_email.code_expires" | translate }}</p>+ </div>++ <p style="color:#6c757d; font-size: 12px;">{{ "email.signin_email.alternative" | translate }}<br>{{ .link | html }}</p></td></tr>{{end}}\ No newline at end of file