Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Account verified #453

Merged
merged 2 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions core/account_errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const (
ErrKeyLoginFailed AccountErrorType = "ErrLoginFailed"
ErrKeyHashingFailed AccountErrorType = "ErrHashingFailed"
ErrKeyAccountPendingDeletion AccountErrorType = "ErrAccountPendingDeletion"
ErrKeyAccountNotVerified AccountErrorType = "ErrAccountNotVerified"

// Account update errors
ErrKeyAccountUpdateFailed AccountErrorType = "ErrAccountUpdateFailed"
Expand Down Expand Up @@ -84,6 +85,7 @@ var defaultErrorMessages = map[AccountErrorType]string{
ErrKeyOTPVerificationFailed: "OTP verification failed, please try again.",
ErrKeyLoginFailed: "Login failed due to an internal error.",
ErrKeyAccountPendingDeletion: "This account is pending deletion.",
ErrKeyAccountNotVerified: "The account is not verified.",

// Account update errors
ErrKeyAccountUpdateFailed: "Failed to update account information.",
Expand Down Expand Up @@ -138,6 +140,7 @@ var (
ErrKeyOTPVerificationFailed: http.StatusBadRequest,
ErrKeyLoginFailed: http.StatusInternalServerError,
ErrKeyAccountPendingDeletion: http.StatusForbidden,
ErrKeyAccountNotVerified: http.StatusForbidden,

// Account update errors
ErrKeyAccountUpdateFailed: http.StatusInternalServerError,
Expand Down
3 changes: 3 additions & 0 deletions core/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ type UserService interface {
// It returns an error if any.
VerifyEmail(email string, token string) error

// IsAccountVerified checks if the email of the user with the given ID is verified.
IsAccountVerified(userId uint) (bool, error)

// DeleteAccount deletes the account of the user with the given ID.
DeleteAccount(userId uint) error

Expand Down
35 changes: 35 additions & 0 deletions middleware/account_verified.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package middleware

import (
"go.lumeweb.com/portal/core"
"net/http"
)

func AccountVerifiedMiddleware(ctx core.Context) func(http.Handler) http.Handler {
userService := ctx.Service(core.USER_SERVICE).(core.UserService)

return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

user, err := GetUserFromContext(r.Context())
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}

verified, err := userService.IsAccountVerified(user)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

if !verified {
acctErr := core.NewAccountError(core.ErrKeyAccountNotVerified, nil)
http.Error(w, acctErr.Error(), acctErr.HttpStatus())
return
}

next.ServeHTTP(w, r)
})
}
}
29 changes: 23 additions & 6 deletions service/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,20 +317,20 @@ func (u UserServiceDefault) SendEmailVerification(userId uint) error {
return core.NewAccountError(core.ErrKeyAccountSubdomainNotSet, nil)
}

exists, user, err := u.AccountExists(userId)
exists, _user, err := u.AccountExists(userId)
if !exists || err != nil {
return err
}

if user.Verified {
if _user.Verified {
return core.NewAccountError(core.ErrKeyAccountAlreadyVerified, nil)
}

token := core.GenerateSecurityToken()

var verification models.EmailVerification

verification.UserID = user.ID
verification.UserID = _user.ID
verification.Token = token
verification.ExpiresAt = time.Now().Add(time.Hour)

Expand All @@ -342,14 +342,31 @@ func (u UserServiceDefault) SendEmailVerification(userId uint) error {

verifyUrl := fmt.Sprintf("%s/account/verify?token=%s", fmt.Sprintf("https://%s.%s", u.subdomain, u.config.Config().Core.Domain), token)
vars := map[string]interface{}{
"FirstName": user.FirstName,
"Email": user.Email,
"FirstName": _user.FirstName,
"Email": _user.Email,
"VerificationLink": verifyUrl,
"ExpireTime": time.Until(verification.ExpiresAt).Round(time.Second * 2),
"PortalName": u.config.Config().Core.PortalName,
}

return u.mailer.TemplateSend(core.MAILER_TPL_VERIFY_EMAIL, vars, vars, user.Email)
return u.mailer.TemplateSend(core.MAILER_TPL_VERIFY_EMAIL, vars, vars, _user.Email)
}

func (u UserServiceDefault) IsAccountVerified(userId uint) (bool, error) {
var _user models.User
_user.ID = userId

if err := db.RetryableTransaction(u.ctx, u.db, func(tx *gorm.DB) *gorm.DB {
return tx.Model(&_user).Where(&_user).First(&_user)
}); err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return false, err
}

return false, core.NewAccountError(core.ErrKeyDatabaseOperationFailed, err)
}

return _user.Verified, nil
}

func (u UserServiceDefault) VerifyEmail(email string, token string) error {
Expand Down
Loading