Open platform to collect and prioritize feedback
Add backend support for resending signup verification email
copilot-swe-agent[bot]95d84f999e81
diff --git a/app/actions/tenant.go b/app/actions/tenant.goindex fcbd1df1a..56ec30849 100644--- a/app/actions/tenant.go+++ b/app/actions/tenant.go@@ -2,6 +2,9 @@ package actionsimport ("context"+ "fmt"+ "time"+"github.com/getfider/fider/app/models/query""github.com/getfider/fider/app/pkg/bus"@@ -33,6 +36,11 @@ func NewCreateTenant() *CreateTenant {}}+// GetVerificationKey returns the verification key+func (action *CreateTenant) GetVerificationKey() string {+ return action.VerificationKey+}+// IsAuthorized returns true if current user is authorized to perform this actionfunc (action *CreateTenant) IsAuthorized(ctx context.Context, user *entity.User) bool {return true@@ -109,6 +117,92 @@ func (action *CreateTenant) GetKind() enum.EmailVerificationKind {return enum.EmailVerificationKindSignUp}+// ResendSignUpEmail is the input model used to resend signup verification email+type ResendSignUpEmail struct {+ VerificationKey string+ email string+ name string+}++func NewResendSignUpEmail() *ResendSignUpEmail {+ return &ResendSignUpEmail{+ VerificationKey: entity.GenerateEmailVerificationKey(),+ }+}++// GetVerificationKey returns the verification key+func (action *ResendSignUpEmail) GetVerificationKey() string {+ return action.VerificationKey+}++// SetEmailAndName sets the email and name from the pending verification+func (action *ResendSignUpEmail) SetEmailAndName(email, name string) {+ action.email = email+ action.name = name+}++// IsAuthorized returns true if current user is authorized to perform this action+func (action *ResendSignUpEmail) IsAuthorized(ctx context.Context, user *entity.User) bool {+ return true+}++// Validate if current model is valid+func (action *ResendSignUpEmail) Validate(ctx context.Context, user *entity.User) *validate.Result {+ result := validate.Success()++ tenant, hasTenant := ctx.Value(app.TenantCtxKey).(*entity.Tenant)+ if !hasTenant || tenant.Status != enum.TenantPending {+ return validate.Failed("This operation is only allowed for pending tenants.")+ }++ // Get the most recent pending signup verification+ pendingVerification := &query.GetPendingSignUpVerification{}+ if err := bus.Dispatch(ctx, pendingVerification); err != nil {+ return validate.Error(err)+ }++ // Check if last resend was within 5 minutes (rate limiting)+ if pendingVerification.Result != nil {+ timeSinceLastSend := time.Since(pendingVerification.Result.CreatedAt)+ if timeSinceLastSend < 5*time.Minute {+ remainingTime := 5*time.Minute - timeSinceLastSend+ remainingMinutes := int(remainingTime.Minutes())+ remainingSeconds := int(remainingTime.Seconds()) % 60++ var message string+ if remainingMinutes > 0 {+ message = fmt.Sprintf("Please wait %d minute(s) and %d second(s) before requesting another verification email.", remainingMinutes, remainingSeconds)+ } else {+ message = fmt.Sprintf("Please wait %d second(s) before requesting another verification email.", remainingSeconds)+ }++ result.AddFieldFailure("", message)+ }+ }++ return result+}++// GetEmail returns the email being verified+func (action *ResendSignUpEmail) GetEmail() string {+ return action.email+}++// GetName returns the name of the email owner+func (action *ResendSignUpEmail) GetName() string {+ return action.name+}++// GetUser returns the current user performing this action+func (action *ResendSignUpEmail) GetUser() *entity.User {+ return nil+}++// GetKind returns EmailVerificationKindSignUp+func (action *ResendSignUpEmail) GetKind() enum.EmailVerificationKind {+ return enum.EmailVerificationKindSignUp+}+// UpdateTenantSettings is the input model used to update tenant settingstype UpdateTenantSettings struct {Logo *dto.ImageUpload `json:"logo"`diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 4fdd01da5..432f82db7 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -108,6 +108,7 @@ func routes(r *web.Engine) *web.Engine {r.Get("/_design", handlers.Page("Design System", "A preview of Fider UI elements", "DesignSystem/DesignSystem.page"))r.Get("/signup/verify", handlers.VerifySignUpKey())+ r.Post("/_api/signup/resend", handlers.ResendSignUpEmail())r.Get("/signout", handlers.SignOut())r.Get("/oauth/:provider/token", handlers.OAuthToken())r.Get("/oauth/:provider/echo", handlers.OAuthEcho())diff --git a/app/handlers/signup.go b/app/handlers/signup.goindex 369bce04e..3ee16692e 100644--- a/app/handlers/signup.go+++ b/app/handlers/signup.go@@ -201,3 +201,78 @@ func VerifySignUpKey() web.HandlerFunc {return c.Redirect(c.BaseURL())}}++// ResendSignUpEmail resends the verification email for pending tenant signup+func ResendSignUpEmail() web.HandlerFunc {+ return func(c *web.Context) error {+ if c.Tenant().Status != enum.TenantPending {+ return c.NotFound()+ }++ // Get the existing verification to get email and name+ pendingVerification := &query.GetPendingSignUpVerification{}+ if err := bus.Dispatch(c, pendingVerification); err != nil {+ return c.Failure(err)+ }++ if pendingVerification.Result == nil {+ return c.NotFound()+ }++ action := actions.NewResendSignUpEmail()+ action.SetEmailAndName(pendingVerification.Result.Email, pendingVerification.Result.Name)++ if result := c.BindTo(action); !result.Ok {+ return c.HandleValidation(result)+ }++ // Invalidate all previous keys+ if err := bus.Dispatch(c, &cmd.InvalidatePreviousSignUpKeys{}); err != nil {+ return c.Failure(err)+ }++ // Create a struct that implements NewEmailVerification interface+ resendRequest := &resendEmailVerificationRequest{+ email: pendingVerification.Result.Email,+ name: pendingVerification.Result.Name,+ }++ // Save new verification key+ err := bus.Dispatch(c, &cmd.SaveVerificationKey{+ Key: action.VerificationKey,+ Duration: 48 * time.Hour,+ Request: resendRequest,+ })+ if err != nil {+ return c.Failure(err)+ }++ // Send email+ siteURL := web.TenantBaseURL(c, c.Tenant())+ c.Enqueue(tasks.SendSignUpEmail(action, siteURL))++ return c.Ok(web.Map{})+ }+}++// resendEmailVerificationRequest is a helper struct for resending verification emails+type resendEmailVerificationRequest struct {+ email string+ name string+}++func (r *resendEmailVerificationRequest) GetEmail() string {+ return r.email+}++func (r *resendEmailVerificationRequest) GetName() string {+ return r.name+}++func (r *resendEmailVerificationRequest) GetUser() *entity.User {+ return nil+}++func (r *resendEmailVerificationRequest) GetKind() enum.EmailVerificationKind {+ return enum.EmailVerificationKindSignUp+}diff --git a/app/models/cmd/tenant.go b/app/models/cmd/tenant.goindex 482514280..62b0006fc 100644--- a/app/models/cmd/tenant.go+++ b/app/models/cmd/tenant.go@@ -60,3 +60,6 @@ type NewEmailVerification interface {type SetKeyAsVerified struct {Key string}++type InvalidatePreviousSignUpKeys struct {+}diff --git a/app/models/query/tenant.go b/app/models/query/tenant.goindex f6061b76d..41c9db5ff 100644--- a/app/models/query/tenant.go+++ b/app/models/query/tenant.go@@ -48,3 +48,8 @@ type GetTrialingTenantContacts struct {// OutputContacts []*entity.User}++type GetPendingSignUpVerification struct {+ // Output+ Result *entity.EmailVerification+}diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.goindex b8bbf9847..1328eaf64 100644--- a/app/services/sqlstore/postgres/postgres.go+++ b/app/services/sqlstore/postgres/postgres.go@@ -116,6 +116,8 @@ func (s Service) Init() {bus.AddHandler(getVerificationByKey)bus.AddHandler(saveVerificationKey)bus.AddHandler(setKeyAsVerified)+ bus.AddHandler(getPendingSignUpVerification)+ bus.AddHandler(invalidatePreviousSignUpKeys)bus.AddHandler(listCustomOAuthConfig)bus.AddHandler(getCustomOAuthConfigByProvider)diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.goindex 63e7c10cd..31ae9fdf5 100644--- a/app/services/sqlstore/postgres/tenant.go+++ b/app/services/sqlstore/postgres/tenant.go@@ -307,3 +307,35 @@ func getTenantByDomain(ctx context.Context, q *query.GetTenantByDomain) error {return nil})}++func getPendingSignUpVerification(ctx context.Context, q *query.GetPendingSignUpVerification) 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 kind = $2 AND verified_at IS NULL+ ORDER BY created_at DESC+ LIMIT 1`+ err := trx.Get(&verification, query, tenant.ID, enum.EmailVerificationKindSignUp)+ if err != nil {+ return errors.Wrap(err, "failed to get pending signup verification for tenant '%d'", tenant.ID)+ }++ q.Result = verification.toModel()+ return nil+ })+}++func invalidatePreviousSignUpKeys(ctx context.Context, c *cmd.InvalidatePreviousSignUpKeys) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ query := `UPDATE email_verifications+ SET expires_at = $1+ WHERE tenant_id = $2 AND kind = $3 AND verified_at IS NULL AND expires_at > $1`+ _, err := trx.Execute(query, time.Now(), tenant.ID, enum.EmailVerificationKindSignUp)+ if err != nil {+ return errors.Wrap(err, "failed to invalidate previous signup keys for tenant '%d'", tenant.ID)+ }+ return nil+ })+}diff --git a/app/tasks/signup.go b/app/tasks/signup.goindex 0827d8101..b655bad34 100644--- a/app/tasks/signup.go+++ b/app/tasks/signup.go@@ -1,7 +1,6 @@package tasksimport (- "github.com/getfider/fider/app/actions""github.com/getfider/fider/app/models/cmd""github.com/getfider/fider/app/models/dto""github.com/getfider/fider/app/pkg/bus"@@ -9,11 +8,18 @@ import ("github.com/getfider/fider/app/pkg/worker")+// SignUpEmailData contains the data needed to send a signup email+type SignUpEmailData interface {+ GetEmail() string+ GetName() string+ GetVerificationKey() string+}+// SendSignUpEmail is used to send the sign up email to requestor-func SendSignUpEmail(action *actions.CreateTenant, baseURL string) worker.Task {+func SendSignUpEmail(data SignUpEmailData, baseURL string) worker.Task {return describe("Send sign up email", func(c *worker.Context) error {- to := dto.NewRecipient(action.Name, action.Email, dto.Props{- "link": link(baseURL, "/signup/verify?k=%s", action.VerificationKey),+ to := dto.NewRecipient(data.GetName(), data.GetEmail(), dto.Props{+ "link": link(baseURL, "/signup/verify?k=%s", data.GetVerificationKey()),})bus.Publish(c, &cmd.SendMail{diff --git a/locale/en/client.json b/locale/en/client.jsonindex 23a14cda0..20cc69c14 100644--- a/locale/en/client.json+++ b/locale/en/client.json@@ -200,5 +200,8 @@"signin.message.socialbutton.intro": "Continue with","validation.custom.maxattachments": "A maximum of {number} attachments are allowed.","validation.custom.maximagesize": "The image size must be smaller than {kilobytes}KB.",- "{count, plural, one {# tag} other {# tags}}": "{count, plural, one {# tag} other {# tags}}"+ "{count, plural, one {# tag} other {# tags}}": "{count, plural, one {# tag} other {# tags}}",+ "page.pendingactivation.didntreceive": "Didn't receive the email?",+ "page.pendingactivation.resend": "Resend verification email",+ "page.pendingactivation.resending": "Resending..."}diff --git a/public/pages/SignUp/PendingActivation.page.tsx b/public/pages/SignUp/PendingActivation.page.tsxindex 8360e62f4..9b389aa89 100644--- a/public/pages/SignUp/PendingActivation.page.tsx+++ b/public/pages/SignUp/PendingActivation.page.tsx@@ -1,8 +1,29 @@-import React from "react"-import { TenantLogo } from "@fider/components"+import React, { useState } from "react"+import { TenantLogo, Button, Message } from "@fider/components"import { Trans } from "@lingui/react/macro"+import { actions, Failure } from "@fider/services"const PendingActivation = () => {+ const [isResending, setIsResending] = useState(false)+ const [successMessage, setSuccessMessage] = useState("")+ const [error, setError] = useState<Failure | undefined>()++ const resendEmail = async () => {+ setIsResending(true)+ setError(undefined)+ setSuccessMessage("")++ const result = await actions.resendSignUpEmail()++ setIsResending(false)++ if (result.ok) {+ setSuccessMessage("Verification email sent successfully! Please check your inbox.")+ } else if (result.error) {+ setError(result.error)+ }+ }+return (<div id="p-notinvited" className="container page"><div className="w-max-7xl mx-auto text-center mt-8">@@ -18,6 +39,34 @@ const PendingActivation = () => {<p><Trans id="page.pendingactivation.text2">Please check your inbox to activate it.</Trans></p>++ <div className="mt-6">+ {successMessage && (+ <Message className="mb-4" type="success" showIcon={true}>+ {successMessage}+ </Message>+ )}++ {error && error.errors && error.errors.length > 0 && (+ <Message className="mb-4" type="error" showIcon={true}>+ {error.errors.map((e, i) => (+ <div key={i}>{e.message}</div>+ ))}+ </Message>+ )}++ <p className="text-muted mb-2">+ <Trans id="page.pendingactivation.didntreceive">Didn't receive the email?</Trans>+ </p>++ <Button variant="primary" onClick={resendEmail} disabled={isResending}>+ {isResending ? (+ <Trans id="page.pendingactivation.resending">Resending...</Trans>+ ) : (+ <Trans id="page.pendingactivation.resend">Resend verification email</Trans>+ )}+ </Button>+ </div></div></div>)diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.tsindex 7fb4979fc..a2acf7842 100644--- a/public/services/actions/tenant.ts+++ b/public/services/actions/tenant.ts@@ -107,3 +107,7 @@ export interface CreateEditOAuthConfigRequest {export const saveOAuthConfig = async (request: CreateEditOAuthConfigRequest): Promise<Result> => {return await http.post("/_api/admin/oauth", request)}++export const resendSignUpEmail = async (): Promise<Result> => {+ return await http.post("/_api/signup/resend", {})+}