Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

enhancement: add email verification grace period

goenning37f2d15924da
diff --git a/app/actions/signin.go b/app/actions/signin.go
index 5d7983ccd..e69c6ba49 100644
--- a/app/actions/signin.go
+++ b/app/actions/signin.go
@@ -2,6 +2,7 @@ package actions
import (
"context"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/entity"
@@ -75,9 +76,9 @@ func (action *SignInByEmail) GetKind() enum.EmailVerificationKind {
// CompleteProfile happens when users completes their profile during first time sign in
type CompleteProfile struct {
- Key string `json:"key"`
- Name string `json:"name"`
- Email string
+ Kind enum.EmailVerificationKind `json:"kind"`
+ Key string `json:"key"`
+ Name string `json:"name"`
}
// IsAuthorized returns true if current user is authorized to perform this action
@@ -97,20 +98,6 @@ func (action *CompleteProfile) Validate(ctx context.Context, user *entity.User)
if action.Key == "" {
result.AddFieldFailure("key", propertyIsRequired(ctx, "key"))
- } else {
- findBySignIn := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindSignIn, Key: action.Key}
- err1 := bus.Dispatch(ctx, findBySignIn)
-
- findByUserInvitation := &query.GetVerificationByKey{Kind: enum.EmailVerificationKindUserInvitation, Key: action.Key}
- err2 := bus.Dispatch(ctx, findByUserInvitation)
-
- if err1 == nil {
- action.Email = findBySignIn.Result.Email
- } else if err2 == nil {
- action.Email = findByUserInvitation.Result.Email
- } else {
- result.AddFieldFailure("key", propertyIsInvalid(ctx, "key"))
- }
}
return result
diff --git a/app/actions/signin_test.go b/app/actions/signin_test.go
index 75caec163..156ba5952 100644
--- a/app/actions/signin_test.go
+++ b/app/actions/signin_test.go
@@ -4,14 +4,8 @@ import (
"context"
"testing"
- "github.com/getfider/fider/app/models/entity"
- "github.com/getfider/fider/app/models/enum"
- "github.com/getfider/fider/app/models/query"
-
- "github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/bus"
)
func TestSignInByEmail_EmptyEmail(t *testing.T) {
@@ -58,61 +52,3 @@ func TestCompleteProfile_LongName(t *testing.T) {
result := action.Validate(context.Background(), nil)
ExpectFailed(result, "name", "key")
}
-
-func TestCompleteProfile_UnknownKey(t *testing.T) {
- RegisterT(t)
-
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
- return app.ErrNotFound
- })
-
- action := actions.CompleteProfile{Name: "Jon Snow", Key: "1234567890"}
- result := action.Validate(context.Background(), nil)
- ExpectFailed(result, "key")
-}
-
-func TestCompleteProfile_ValidKey(t *testing.T) {
- RegisterT(t)
-
- key := "1234567890"
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
- if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
- q.Result = &entity.EmailVerification{
- Key: q.Key,
- Kind: q.Kind,
- Email: "[email protected]",
- }
- return nil
- }
- return app.ErrNotFound
- })
-
- action := actions.CompleteProfile{Name: "Jon Snow", Key: key}
- result := action.Validate(context.Background(), nil)
-
- ExpectSuccess(result)
- Expect(action.Email).Equals("[email protected]")
-}
-
-func TestCompleteProfile_UserInvitation_ValidKey(t *testing.T) {
- RegisterT(t)
-
- key := "1234567890"
- bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
- if q.Key == key && q.Kind == enum.EmailVerificationKindUserInvitation {
- q.Result = &entity.EmailVerification{
- Key: q.Key,
- Kind: q.Kind,
- Email: "[email protected]",
- }
- return nil
- }
- return app.ErrNotFound
- })
-
- action := actions.CompleteProfile{Name: "Jon Snow", Key: key}
- result := action.Validate(context.Background(), nil)
-
- ExpectSuccess(result)
- Expect(action.Email).Equals("[email protected]")
-}
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index daf32d93d..22d97361a 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -95,7 +95,7 @@ func routes(r *web.Engine) *web.Engine {
//If tenant is pending, block it from using any other route
r.Use(middlewares.BlockPendingTenants())
- r.Get("/signin", handlers.SignInPage("SignIn/SignIn.page"))
+ r.Get("/signin", handlers.SignInPage())
r.Get("/not-invited", handlers.NotInvitedPage())
r.Get("/signin/verify", handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
r.Get("/invite/verify", handlers.VerifySignInKey(enum.EmailVerificationKindUserInvitation))
@@ -105,7 +105,7 @@ func routes(r *web.Engine) *web.Engine {
//Block if it's private tenant with unauthenticated user
r.Use(middlewares.CheckTenantPrivacy())
- r.Get("/", handlers.Index("Home/Home.page"))
+ r.Get("/", handlers.Index())
r.Get("/posts/:number", handlers.PostDetails())
r.Get("/posts/:number/:slug", handlers.PostDetails())
diff --git a/app/handlers/common.go b/app/handlers/common.go
index 6eeb03839..db361c287 100644
--- a/app/handlers/common.go
+++ b/app/handlers/common.go
@@ -124,9 +124,7 @@ func LogError() web.HandlerFunc {
}
}
-func validateKey(kind enum.EmailVerificationKind, c *web.Context) (*entity.EmailVerification, error) {
- key := c.QueryParam("k")
-
+func validateKey(kind enum.EmailVerificationKind, key string, c *web.Context) (*entity.EmailVerification, error) {
//If key has been used, return NotFound
findByKey := &query.GetVerificationByKey{Kind: kind, Key: key}
err := bus.Dispatch(c, findByKey)
@@ -137,13 +135,18 @@ func validateKey(kind enum.EmailVerificationKind, c *web.Context) (*entity.Email
return nil, c.Failure(err)
}
- //If key has been used, return Gone
- if findByKey.Result.VerifiedAt != nil {
+ now := time.Now()
+ res := findByKey.Result
+
+ // If key has been used more than 5 minutes ago, deny usage
+ // The 5 minutes grace period is to avoid issues with email clients that preview the link
+ // Examples: Outlook Smart Preview, corporate email protection software
+ if res.VerifiedAt != nil && now.Sub(*res.VerifiedAt) > 5*time.Minute {
return nil, c.Gone()
}
- //If key expired, return Gone
- if time.Now().After(findByKey.Result.ExpiresAt) {
+ //If key expired, deny usage
+ if now.After(res.ExpiresAt) {
err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: key})
if err != nil {
return nil, c.Failure(err)
@@ -151,7 +154,7 @@ func validateKey(kind enum.EmailVerificationKind, c *web.Context) (*entity.Email
return nil, c.Gone()
}
- return findByKey.Result, nil
+ return res, nil
}
func between(n, min, max int) int {
diff --git a/app/handlers/post.go b/app/handlers/post.go
index 977099e8f..65769b452 100644
--- a/app/handlers/post.go
+++ b/app/handlers/post.go
@@ -12,7 +12,7 @@ import (
)
// Index is the default home page
-func Index(page string) web.HandlerFunc {
+func Index() web.HandlerFunc {
return func(c *web.Context) error {
c.SetCanonicalURL("")
@@ -37,8 +37,8 @@ func Index(page string) web.HandlerFunc {
}
return c.Page(http.StatusOK, web.Props{
+ Page: "Home/Home.page",
Description: description,
- Page: page,
Data: web.Map{
"posts": searchPosts.Result,
"tags": getAllTags.Result,
diff --git a/app/handlers/post_test.go b/app/handlers/post_test.go
index af6f1a10e..59733b1a4 100644
--- a/app/handlers/post_test.go
+++ b/app/handlers/post_test.go
@@ -34,7 +34,7 @@ func TestIndexHandler(t *testing.T) {
server := mock.NewServer()
code, _ := server.OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
- Execute(handlers.Index("Home/Home.page"))
+ Execute(handlers.Index())
Expect(code).Equals(http.StatusOK)
}
diff --git a/app/handlers/settings.go b/app/handlers/settings.go
index 7481c8ad6..4080e2e75 100644
--- a/app/handlers/settings.go
+++ b/app/handlers/settings.go
@@ -42,7 +42,8 @@ func ChangeUserEmail() web.HandlerFunc {
// VerifyChangeEmailKey checks if key is correct and update user's email
func VerifyChangeEmailKey() web.HandlerFunc {
return func(c *web.Context) error {
- result, err := validateKey(enum.EmailVerificationKindChangeEmail, c)
+ key := c.QueryParam("k")
+ result, err := validateKey(enum.EmailVerificationKindChangeEmail, key, c)
if result == nil {
return err
}
@@ -59,10 +60,11 @@ func VerifyChangeEmailKey() web.HandlerFunc {
return c.Failure(err)
}
- err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: result.Key})
+ err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: key})
if err != nil {
return c.Failure(err)
}
+
return c.Redirect(c.BaseURL() + "/settings")
}
}
diff --git a/app/handlers/settings_test.go b/app/handlers/settings_test.go
index fc63a42d8..c4524245d 100644
--- a/app/handlers/settings_test.go
+++ b/app/handlers/settings_test.go
@@ -217,33 +217,29 @@ func TestVerifyChangeEmailKeyHandler_Success(t *testing.T) {
RegisterT(t)
server := mock.NewServer()
-
key := "th3-s3cr3t"
+
bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
- if q.Key == key && q.Kind == enum.EmailVerificationKindChangeEmail {
- q.Result = &entity.EmailVerification{
- UserID: mock.JonSnow.ID,
- Key: q.Key,
- Kind: q.Kind,
- ExpiresAt: time.Now().Add(10 * time.Minute),
- Email: "[email protected]",
- }
- return nil
+ Expect(q.Key).Equals(key)
+ Expect(q.Kind).Equals(enum.EmailVerificationKindChangeEmail)
+ q.Result = &entity.EmailVerification{
+ UserID: mock.JonSnow.ID,
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: time.Now().Add(10 * time.Minute),
+ Email: "[email protected]",
}
- return app.ErrNotFound
+ return nil
})
- var changeEmailCmd *cmd.ChangeUserEmail
bus.AddHandler(func(ctx context.Context, c *cmd.ChangeUserEmail) error {
- changeEmailCmd = c
+ Expect(c.UserID).Equals(mock.JonSnow.ID)
+ Expect(c.Email).Equals("[email protected]")
return nil
})
- verified := false
bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
- if c.Key == key {
- verified = true
- }
+ Expect(c.Key).Equals(key)
return nil
})
@@ -254,9 +250,9 @@ func TestVerifyChangeEmailKeyHandler_Success(t *testing.T) {
Execute(handlers.VerifyChangeEmailKey())
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(changeEmailCmd.UserID).Equals(mock.JonSnow.ID)
- Expect(changeEmailCmd.Email).Equals("[email protected]")
- Expect(verified).IsTrue()
+ ExpectHandler(&query.GetVerificationByKey{}).CalledOnce()
+ ExpectHandler(&cmd.ChangeUserEmail{}).CalledOnce()
+ ExpectHandler(&cmd.SetKeyAsVerified{}).CalledOnce()
}
func TestVerifyChangeEmailKeyHandler_DifferentUser(t *testing.T) {
diff --git a/app/handlers/signin.go b/app/handlers/signin.go
index 38ed822fd..19d15699c 100644
--- a/app/handlers/signin.go
+++ b/app/handlers/signin.go
@@ -19,12 +19,12 @@ import (
)
// SignInPage renders the sign in page
-func SignInPage(page string) web.HandlerFunc {
+func SignInPage() web.HandlerFunc {
return func(c *web.Context) error {
if c.Tenant().IsPrivate {
return c.Page(http.StatusOK, web.Props{
- Page: page,
+ Page: "SignIn/SignIn.page",
Title: "Sign in",
})
}
@@ -70,63 +70,38 @@ func SignInByEmail() web.HandlerFunc {
// VerifySignInKey checks if verify key is correct and sign in user
func VerifySignInKey(kind enum.EmailVerificationKind) web.HandlerFunc {
return func(c *web.Context) error {
- result, err := validateKey(kind, c)
+ key := c.QueryParam("k")
+ result, err := validateKey(kind, key, c)
if result == nil {
return err
}
- var user *entity.User
- if kind == enum.EmailVerificationKindSignUp && c.Tenant().Status == enum.TenantPending {
- if err = bus.Dispatch(c, &cmd.ActivateTenant{TenantID: c.Tenant().ID}); err != nil {
- return c.Failure(err)
- }
-
- user = &entity.User{
- Name: result.Name,
- Email: result.Email,
- Tenant: c.Tenant(),
- Role: enum.RoleAdministrator,
- }
-
- if err = bus.Dispatch(c, &cmd.RegisterUser{User: user}); err != nil {
- return c.Failure(err)
- }
- } else if kind == enum.EmailVerificationKindSignIn {
- userByEmail := &query.GetUserByEmail{Email: result.Email}
- err = bus.Dispatch(c, userByEmail)
- user = userByEmail.Result
- if err != nil {
- if errors.Cause(err) == app.ErrNotFound {
- if c.Tenant().IsPrivate {
- return NotInvitedPage()(c)
- }
- return Index("CompleteSignInProfile/CompleteSignInProfile.page")(c)
- }
- return c.Failure(err)
- }
- } else if kind == enum.EmailVerificationKindUserInvitation {
- userByEmail := &query.GetUserByEmail{Email: result.Email}
- err = bus.Dispatch(c, userByEmail)
- user = userByEmail.Result
- if err != nil {
- if errors.Cause(err) == app.ErrNotFound {
- if c.Tenant().IsPrivate {
- return SignInPage("CompleteSignInProfile/CompleteSignInProfile.page")(c)
- }
- return Index("CompleteSignInProfile/CompleteSignInProfile.page")(c)
+ userByEmail := &query.GetUserByEmail{Email: result.Email}
+ err = bus.Dispatch(c, userByEmail)
+ if err != nil {
+ if errors.Cause(err) == app.ErrNotFound {
+ if kind == enum.EmailVerificationKindSignIn && c.Tenant().IsPrivate {
+ return NotInvitedPage()(c)
}
- return c.Failure(err)
+
+ return c.Page(http.StatusOK, web.Props{
+ Page: "SignIn/CompleteSignInProfile.page",
+ Title: "Complete Sign In Profile",
+ Data: web.Map{
+ "kind": kind,
+ "k": key,
+ },
+ })
}
- } else {
- return c.NotFound()
+ return c.Failure(err)
}
- err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: result.Key})
+ err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: key})
if err != nil {
return c.Failure(err)
}
- webutil.AddAuthUserCookie(c, user)
+ webutil.AddAuthUserCookie(c, userByEmail.Result)
return c.Redirect(c.BaseURL())
}
@@ -140,14 +115,20 @@ func CompleteSignInProfile() web.HandlerFunc {
return c.HandleValidation(result)
}
- err := bus.Dispatch(c, &query.GetUserByEmail{Email: action.Email})
+ result, err := validateKey(action.Kind, action.Key, c)
+ if result == nil {
+ return err
+ }
+
+ err = bus.Dispatch(c, &query.GetUserByEmail{Email: result.Email})
if errors.Cause(err) != app.ErrNotFound {
- return c.Ok(web.Map{})
+ // Not possible to create user that already exists
+ return c.BadRequest(web.Map{})
}
user := &entity.User{
Name: action.Name,
- Email: action.Email,
+ Email: result.Email,
Tenant: c.Tenant(),
Role: enum.RoleVisitor,
}
diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go
index 22fd6756d..0bff24c2b 100644
--- a/app/handlers/signin_test.go
+++ b/app/handlers/signin_test.go
@@ -2,6 +2,7 @@ package handlers_test
import (
"context"
+ "fmt"
"testing"
"time"
@@ -70,7 +71,7 @@ func TestVerifySignInKeyHandler_UnknownKey(t *testing.T) {
Expect(code).Equals(http.StatusNotFound)
}
-func TestVerifySignInKeyHandler_UsedKey(t *testing.T) {
+func TestVerifySignInKeyHandler_ExpiredKey(t *testing.T) {
RegisterT(t)
server := mock.NewServer()
@@ -78,50 +79,52 @@ func TestVerifySignInKeyHandler_UsedKey(t *testing.T) {
key := "1234567890"
bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
- now := time.Now()
+ now := time.Now().Add(-5 * time.Minute)
q.Result = &entity.EmailVerification{
- Key: q.Key,
- Kind: q.Kind,
- VerifiedAt: &now,
- Email: "[email protected]",
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: now,
+ Email: "[email protected]",
}
return nil
}
return app.ErrNotFound
})
+ verified := false
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ if c.Key == key {
+ verified = true
+ }
+ return nil
+ })
+
code, _ := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin/verify?k=" + key).
Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
Expect(code).Equals(http.StatusGone)
+ Expect(verified).IsTrue()
}
-func TestVerifySignInKeyHandler_ExpiredKey(t *testing.T) {
+func TestVerifySignInKeyHandler_KeyUsedLongAgo_ShouldReturnGone(t *testing.T) {
RegisterT(t)
server := mock.NewServer()
key := "1234567890"
bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
- if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
- now := time.Now().Add(-5 * time.Minute)
- q.Result = &entity.EmailVerification{
- Key: q.Key,
- Kind: q.Kind,
- ExpiresAt: now,
- Email: "[email protected]",
- }
- return nil
- }
- return app.ErrNotFound
- })
-
- verified := false
- bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
- if c.Key == key {
- verified = true
+ Expect(q.Key).Equals(key)
+ Expect(q.Kind).Equals(enum.EmailVerificationKindSignIn)
+
+ verifiedAt := time.Now().Add(-1 * time.Hour)
+ q.Result = &entity.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ VerifiedAt: &verifiedAt,
+ ExpiresAt: time.Now().Add(1 * time.Hour),
+ Email: "[email protected]",
}
return nil
})
@@ -132,7 +135,6 @@ func TestVerifySignInKeyHandler_ExpiredKey(t *testing.T) {
Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
Expect(code).Equals(http.StatusGone)
- Expect(verified).IsTrue()
}
func TestVerifySignInKeyHandler_CorrectKey_ExistingUser(t *testing.T) {
@@ -142,35 +144,73 @@ func TestVerifySignInKeyHandler_CorrectKey_ExistingUser(t *testing.T) {
key := "1234567890"
bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
- if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
- expiresAt := time.Now().Add(5 * time.Minute)
- q.Result = &entity.EmailVerification{
- Key: q.Key,
- Kind: q.Kind,
- ExpiresAt: expiresAt,
- Email: "[email protected]",
- }
- return nil
+ Expect(q.Key).Equals(key)
+ Expect(q.Kind).Equals(enum.EmailVerificationKindSignIn)
+
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &entity.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: "[email protected]",
}
- return app.ErrNotFound
+ return nil
})
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
- if q.Email == mock.JonSnow.Email {
- q.Result = mock.JonSnow
- return nil
- }
- return app.ErrNotFound
+ Expect(q.Email).Equals(mock.JonSnow.Email)
+ q.Result = mock.JonSnow
+ return nil
})
- verified := false
bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
- if c.Key == key {
- verified = true
+ Expect(c.Key).Equals(key)
+ return nil
+ })
+
+ code, response := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://demo.test.fider.io/signin/verify?k=" + key).
+ Execute(handlers.VerifySignInKey(enum.EmailVerificationKindSignIn))
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
+
+ ExpectFiderAuthCookie(response, mock.JonSnow)
+}
+
+func TestVerifySignInKeyHandler_RecentlyUsedKey_ShouldAllowReuse(t *testing.T) {
+ RegisterT(t)
+
+ server := mock.NewServer()
+
+ key := "1234567890"
+ bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
+ Expect(q.Key).Equals(key)
+ Expect(q.Kind).Equals(enum.EmailVerificationKindSignIn)
+
+ verifiedAt := time.Now().Add(-4 * time.Minute)
+ q.Result = &entity.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ VerifiedAt: &verifiedAt,
+ ExpiresAt: time.Now().Add(1 * time.Hour),
+ Email: "[email protected]",
}
return nil
})
+ bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
+ Expect(c.Key).Equals(key)
+ return nil
+ })
+
+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
+ Expect(q.Email).Equals(mock.JonSnow.Email)
+ q.Result = mock.JonSnow
+ return nil
+ })
+
code, response := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin/verify?k=" + key).
@@ -179,7 +219,6 @@ func TestVerifySignInKeyHandler_CorrectKey_ExistingUser(t *testing.T) {
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
- Expect(verified).IsTrue()
ExpectFiderAuthCookie(response, mock.JonSnow)
}
@@ -471,45 +510,53 @@ func TestCompleteSignInProfileHandler_ExistingUser_CorrectKey(t *testing.T) {
RegisterT(t)
server := mock.NewServer()
+ key := "1234567890"
bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error {
- if q.Email == mock.JonSnow.Email {
- q.Result = mock.JonSnow
- return nil
- }
- return app.ErrNotFound
+ Expect(q.Email).Equals(mock.JonSnow.Email)
+ q.Result = mock.JonSnow
+ return nil
})
- key := "1234567890"
bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
- if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
- expiresAt := time.Now().Add(5 * time.Minute)
- q.Result = &entity.EmailVerification{
- Key: q.Key,
- Kind: q.Kind,
- ExpiresAt: expiresAt,
- Email: mock.JonSnow.Email,
- }
- return nil
+ Expect(q.Key).Equals(key)
+ Expect(q.Kind).Equals(enum.EmailVerificationKindSignIn)
+
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &entity.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: mock.JonSnow.Email,
}
- return app.ErrNotFound
+ return nil
})
code, _ := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin/complete").
- ExecutePost(handlers.CompleteSignInProfile(), `{ "name": "Hot Pie", "key": "`+key+`" }`)
+ ExecutePost(handlers.CompleteSignInProfile(), fmt.Sprintf(`
+ {
+ "name": "Hot Pie",
+ "kind": %d,
+ "key": "%s"
+ }`, enum.EmailVerificationKindSignIn, key))
- Expect(code).Equals(http.StatusOK)
+ Expect(code).Equals(http.StatusBadRequest)
+ ExpectHandler(&query.GetVerificationByKey{}).CalledOnce()
+ ExpectHandler(&query.GetUserByEmail{}).CalledOnce()
}
func TestCompleteSignInProfileHandler_CorrectKey(t *testing.T) {
RegisterT(t)
server := mock.NewServer()
+ key := "1234567890"
var newUser *entity.User
bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error {
+ Expect(c.User.Name).Equals("Hot Pie")
+ Expect(c.User.Email).Equals("[email protected]")
newUser = c.User
return nil
})
@@ -518,39 +565,39 @@ func TestCompleteSignInProfileHandler_CorrectKey(t *testing.T) {
return app.ErrNotFound
})
- key := "1234567890"
bus.AddHandler(func(ctx context.Context, q *query.GetVerificationByKey) error {
- if q.Key == key && q.Kind == enum.EmailVerificationKindSignIn {
- expiresAt := time.Now().Add(5 * time.Minute)
- q.Result = &entity.EmailVerification{
- Key: q.Key,
- Kind: q.Kind,
- ExpiresAt: expiresAt,
- Email: "[email protected]",
- }
- return nil
+ Expect(q.Key).Equals(key)
+ Expect(q.Kind).Equals(enum.EmailVerificationKindSignIn)
+
+ expiresAt := time.Now().Add(5 * time.Minute)
+ q.Result = &entity.EmailVerification{
+ Key: q.Key,
+ Kind: q.Kind,
+ ExpiresAt: expiresAt,
+ Email: "[email protected]",
}
- return app.ErrNotFound
+ return nil
})
- verified := false
bus.AddHandler(func(ctx context.Context, c *cmd.SetKeyAsVerified) error {
- if c.Key == key {
- verified = true
- }
+ Expect(c.Key).Equals(key)
return nil
})
code, response := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin/complete").
- ExecutePost(handlers.CompleteSignInProfile(), `{ "name": "Hot Pie", "key": "`+key+`" }`)
- Expect(code).Equals(http.StatusOK)
-
- Expect(newUser.Name).Equals("Hot Pie")
- Expect(newUser.Email).Equals("[email protected]")
- Expect(verified).IsTrue()
+ ExecutePost(handlers.CompleteSignInProfile(), fmt.Sprintf(`
+ {
+ "name": "Hot Pie",
+ "kind": %d,
+ "key": "%s"
+ }`, enum.EmailVerificationKindSignIn, key))
+ Expect(code).Equals(http.StatusOK)
+ ExpectHandler(&cmd.SetKeyAsVerified{}).CalledOnce()
+ ExpectHandler(&query.GetVerificationByKey{}).CalledOnce()
+ ExpectHandler(&query.GetUserByEmail{}).CalledOnce()
ExpectFiderAuthCookie(response, newUser)
}
@@ -562,7 +609,7 @@ func TestSignInPageHandler_AuthenticatedUser(t *testing.T) {
OnTenant(mock.DemoTenant).
AsUser(mock.AryaStark).
WithURL("http://demo.test.fider.io/signin").
- Execute(handlers.SignInPage("SignIn/SignIn.page"))
+ Execute(handlers.SignInPage())
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
@@ -575,7 +622,7 @@ func TestSignInPageHandler_NonPrivateTenant(t *testing.T) {
code, response := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin").
- Execute(handlers.SignInPage("SignIn/SignIn.page"))
+ Execute(handlers.SignInPage())
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("http://demo.test.fider.io")
@@ -590,7 +637,7 @@ func TestSignInPageHandler_PrivateTenant_UnauthenticatedUser(t *testing.T) {
code, _ := server.
OnTenant(mock.DemoTenant).
WithURL("http://demo.test.fider.io/signin").
- Execute(handlers.SignInPage("SignIn/SignIn.page"))
+ Execute(handlers.SignInPage())
Expect(code).Equals(http.StatusOK)
}
diff --git a/app/handlers/signup.go b/app/handlers/signup.go
index 40d505750..a8df45d24 100644
--- a/app/handlers/signup.go
+++ b/app/handlers/signup.go
@@ -154,9 +154,38 @@ func SignUp() web.HandlerFunc {
// VerifySignUpKey checks if verify key is correct, activate the tenant and sign in user
func VerifySignUpKey() web.HandlerFunc {
return func(c *web.Context) error {
- if c.Tenant().Status == enum.TenantPending {
- return VerifySignInKey(enum.EmailVerificationKindSignUp)(c)
+ if c.Tenant().Status != enum.TenantPending {
+ return c.NotFound()
+ }
+
+ key := c.QueryParam("k")
+ result, err := validateKey(enum.EmailVerificationKindSignUp, key, c)
+ if result == nil {
+ return err
+ }
+
+ if err = bus.Dispatch(c, &cmd.ActivateTenant{TenantID: c.Tenant().ID}); err != nil {
+ return c.Failure(err)
+ }
+
+ user := &entity.User{
+ Name: result.Name,
+ Email: result.Email,
+ Tenant: c.Tenant(),
+ Role: enum.RoleAdministrator,
}
- return c.NotFound()
+
+ if err = bus.Dispatch(c, &cmd.RegisterUser{User: user}); err != nil {
+ return c.Failure(err)
+ }
+
+ err = bus.Dispatch(c, &cmd.SetKeyAsVerified{Key: key})
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ webutil.AddAuthUserCookie(c, user)
+
+ return c.Redirect(c.BaseURL())
}
}
diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.go
index dd701992f..eae510df7 100644
--- a/app/services/sqlstore/postgres/tenant.go
+++ b/app/services/sqlstore/postgres/tenant.go
@@ -215,7 +215,7 @@ func saveVerificationKey(ctx context.Context, c *cmd.SaveVerificationKey) error
func setKeyAsVerified(ctx context.Context, c *cmd.SetKeyAsVerified) error {
return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
- query := "UPDATE email_verifications SET verified_at = $1 WHERE tenant_id = $2 AND key = $3"
+ query := "UPDATE email_verifications SET verified_at = $1 WHERE tenant_id = $2 AND key = $3 AND verified_at IS NULL"
_, err := trx.Execute(query, time.Now(), tenant.ID, c.Key)
if err != nil {
return errors.Wrap(err, "failed to update verified date of email verification request")
diff --git a/locale/en/server.json b/locale/en/server.json
index b48c4f323..aac2d1e7b 100644
--- a/locale/en/server.json
+++ b/locale/en/server.json
@@ -44,8 +44,6 @@
"email.greetings": "Hello!",
"email.greetings_name": "Hello, {name}!",
"email.operation_confirmation": "Click the link below to confirm this operation.",
- "email.expire_note_hours": "Note: This link will expire in {hours} hours and can only be used one time.",
- "email.expire_note_minutes": "Note: This link will expire in {minutes} minutes and can only be used one time.",
"email.footer.noreply": "This email was sent from a notification-only address that cannot accept incoming email. Please do not reply to this message.",
"email.change_status.duplicate": "<strong>{title} ({postLink})</strong> has been closed as a <strong>duplicate</strong> of {duplicate}.",
"email.change_status.others": "Status of <strong>{title} ({postLink})</strong> has changed to <strong>{status}</strong>.",
diff --git a/public/models/identity.ts b/public/models/identity.ts
index 936ee42d6..8b561fbd9 100644
--- a/public/models/identity.ts
+++ b/public/models/identity.ts
@@ -16,6 +16,7 @@ export enum TenantStatus {
Active = 1,
Pending = 2,
Locked = 3,
+ Disabled = 4,
}
export interface User {
diff --git a/public/models/settings.ts b/public/models/settings.ts
index cd023aee6..6bfcc2a9c 100644
--- a/public/models/settings.ts
+++ b/public/models/settings.ts
@@ -56,3 +56,10 @@ export interface ImageUpload {
}
remove: boolean
}
+
+export enum EmailVerificationKind {
+ SignIn = 1,
+ SignUp = 2,
+ ChangeEmail = 3,
+ UserInvitation = 4,
+}
diff --git a/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx b/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx
deleted file mode 100644
index 9ea1dd32f..000000000
--- a/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import React from "react"
-
-import HomePage, { HomePageProps } from "../Home/Home.page"
-import SignInPage from "../SignIn/SignIn.page"
-import { Modal, Button, Form, Input, LegalFooter } from "@fider/components"
-import { actions, Failure, querystring, Fider } from "@fider/services"
-import { t, Trans } from "@lingui/macro"
-
-interface CompleteSignInProfilePageState {
- name: string
- error?: Failure
-}
-
-export default class CompleteSignInProfilePage extends React.Component<HomePageProps, CompleteSignInProfilePageState> {
- private key: string
-
- constructor(props: HomePageProps) {
- super(props)
- this.key = querystring.get("k")
- this.state = {
- name: "",
- }
- }
-
- private submit = async () => {
- const result = await actions.completeProfile(this.key, this.state.name)
- if (result.ok) {
- location.href = "/"
- } else if (result.error) {
- this.setState({ error: result.error })
- }
- }
-
- private setName = (name: string) => {
- this.setState({ name })
- }
-
- private noop = () => {
- // do nothing
- }
-
- public render() {
- return (
- <>
- <Modal.Window canClose={false} isOpen={true} onClose={this.noop}>
- <Modal.Header>
- <Trans id="modal.completeprofile.header">Complete your profile</Trans>
- </Modal.Header>
- <Modal.Content>
- <p>
- <Trans id="modal.completeprofile.text">Because this is your first sign in, please enter your name.</Trans>
- </p>
- <Form error={this.state.error}>
- <Input
- field="name"
- onChange={this.setName}
- maxLength={100}
- placeholder={t({ id: "modal.completeprofile.name.placeholder", message: "Name" })}
- suffix={
- <Button type="submit" onClick={this.submit} variant="primary" disabled={this.state.name === ""}>
- <Trans id="action.submit">Submit</Trans>
- </Button>
- }
- />
- </Form>
- </Modal.Content>
- <LegalFooter />
- </Modal.Window>
- {Fider.session.tenant.isPrivate ? React.createElement(SignInPage, this.props) : React.createElement(HomePage, this.props)}
- </>
- )
- }
-}
diff --git a/public/pages/CompleteSignInProfile/index.ts b/public/pages/CompleteSignInProfile/index.ts
deleted file mode 100644
index 140ec0c8a..000000000
--- a/public/pages/CompleteSignInProfile/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./CompleteSignInProfile.page"
diff --git a/public/pages/SignIn/CompleteSignInProfile.page.scss b/public/pages/SignIn/CompleteSignInProfile.page.scss
new file mode 100644
index 000000000..3b82fd44a
--- /dev/null
+++ b/public/pages/SignIn/CompleteSignInProfile.page.scss
@@ -0,0 +1,7 @@
+#p-complete-profile {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ align-items: center;
+ height: 80vh;
+}
diff --git a/public/pages/SignIn/CompleteSignInProfile.page.tsx b/public/pages/SignIn/CompleteSignInProfile.page.tsx
new file mode 100644
index 000000000..f430495ff
--- /dev/null
+++ b/public/pages/SignIn/CompleteSignInProfile.page.tsx
@@ -0,0 +1,64 @@
+import React, { useState } from "react"
+
+import { Button, Form, Input, LegalFooter, TenantLogo } from "@fider/components"
+import { actions, Failure } from "@fider/services"
+import { t, Trans } from "@lingui/macro"
+import { EmailVerificationKind } from "@fider/models"
+
+import "./CompleteSignInProfile.page.scss"
+
+interface CompleteSignInProfilePageProps {
+ kind: EmailVerificationKind
+ k: string
+}
+
+const CompleteSignInProfilePage = (props: CompleteSignInProfilePageProps) => {
+ const [name, setName] = useState("")
+ const [error, setError] = useState<Failure | undefined>()
+
+ const submit = async () => {
+ const result = await actions.completeProfile(props.kind, props.k, name)
+ if (result.ok) {
+ location.href = "/"
+ } else if (result.error) {
+ setError(result.error)
+ }
+ }
+
+ return (
+ <>
+ <div id="p-complete-profile" className="page container w-max-6xl">
+ <div>
+ <div className="h-20 text-center mb-4">
+ <TenantLogo size={100} />
+ </div>
+
+ <p className="text-title">
+ <Trans id="modal.completeprofile.header">Complete your profile</Trans>
+ </p>
+
+ <p>
+ <Trans id="modal.completeprofile.text">Because this is your first sign in, please enter your name.</Trans>
+ </p>
+ <Form error={error}>
+ <Input
+ field="name"
+ onChange={setName}
+ maxLength={100}
+ placeholder={t({ id: "modal.completeprofile.name.placeholder", message: "Name" })}
+ suffix={
+ <Button type="submit" onClick={submit} variant="primary" disabled={name === ""}>
+ <Trans id="action.submit">Submit</Trans>
+ </Button>
+ }
+ />
+ </Form>
+
+ <LegalFooter />
+ </div>
+ </div>
+ </>
+ )
+}
+
+export default CompleteSignInProfilePage
diff --git a/public/pages/SignIn/index.ts b/public/pages/SignIn/index.ts
index a525ad381..de8327669 100644
--- a/public/pages/SignIn/index.ts
+++ b/public/pages/SignIn/index.ts
@@ -1 +1,2 @@
export * from "./SignIn.page"
+export * from "./CompleteSignInProfile.page"
diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.ts
index e21af42e6..22f4217a5 100644
--- a/public/services/actions/tenant.ts
+++ b/public/services/actions/tenant.ts
@@ -1,5 +1,5 @@
import { http, Result } from "@fider/services/http"
-import { UserRole, OAuthConfig, ImageUpload } from "@fider/models"
+import { UserRole, OAuthConfig, ImageUpload, EmailVerificationKind } from "@fider/models"
export interface CheckAvailabilityResponse {
message: string
@@ -61,8 +61,9 @@ export const signIn = async (email: string): Promise<Result> => {
})
}
-export const completeProfile = async (key: string, name: string): Promise<Result> => {
+export const completeProfile = async (kind: EmailVerificationKind, key: string, name: string): Promise<Result> => {
return await http.post("/_api/signin/complete", {
+ kind,
key,
name,
})
diff --git a/views/email/change_emailaddress_email.html b/views/email/change_emailaddress_email.html
index 1bee1df8b..0f86ca80e 100644
--- a/views/email/change_emailaddress_email.html
+++ b/views/email/change_emailaddress_email.html
@@ -7,7 +7,6 @@
<p style="color:#1c262d">{{ translate "email.change_emailaddress.request" (dict "oldEmail" .oldEmail "newEmail" .newEmail) }}</p>
<p style="color:#1c262d">{{ "email.operation_confirmation" | translate }}</p>
<p>{{ .link | html }}</p>
- <p style="color:#666;font-size:14px">{{ translate "email.expire_note_hours" (dict "hours" 24) }}</p>
</td>
</tr>
{{end}}
\ No newline at end of file
diff --git a/views/email/signin_email.html b/views/email/signin_email.html
index 1c45738c2..63d17b932 100644
--- a/views/email/signin_email.html
+++ b/views/email/signin_email.html
@@ -7,7 +7,6 @@
<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>
- <p style="color:#666;font-size:14px">{{ translate "email.expire_note_minutes" (dict "minutes" 30) }}</p>
</td>
</tr>
{{end}}
\ No newline at end of file
diff --git a/views/email/signup_email.html b/views/email/signup_email.html
index a94d395d5..12856883d 100644
--- a/views/email/signup_email.html
+++ b/views/email/signup_email.html
@@ -7,7 +7,6 @@
<p style="color:#1c262d">{{ "email.signup_email.text" | translate }}</p>
<p style="color:#1c262d">{{ "email.signup_email.confirmation" | translate }}</p>
<p>{{ .link | html }}</p>
- <p style="color:#666;font-size:14px">{{ translate "email.expire_note_hours" (dict "hours" 48) }}</p>
</td>
</tr>
{{end}}
\ No newline at end of file