Files
sxchnge/backend/edge/product/interface/accountservice/internal/service.go
T

249 lines
6.8 KiB
Go

package accountserviceimp
import (
"context"
"errors"
"fmt"
"time"
"unicode"
authstorage "git.sendico.io/tech/sxchnge/bff/edge/shared/auth/storage"
"git.sendico.io/tech/sxchnge/bff/edge/shared/interface/api"
"git.sendico.io/tech/sxchnge/bff/edge/shared/interface/middleware"
"git.sendico.io/tech/sxchnge/bff/edge/shared/storage/refreshtokens"
"git.sendico.io/tech/sxchnge/bff/edge/shared/storage/verification"
"git.sendico.io/tech/sxchnge/bff/pkg/db"
"git.sendico.io/tech/sxchnge/bff/pkg/db/account"
"git.sendico.io/tech/sxchnge/bff/pkg/db/transaction"
"git.sendico.io/tech/sxchnge/bff/pkg/merrors"
"git.sendico.io/tech/sxchnge/bff/pkg/mlogger"
"git.sendico.io/tech/sxchnge/bff/pkg/model"
"git.sendico.io/tech/sxchnge/bff/pkg/mutil/mzap"
"go.mongodb.org/mongo-driver/v2/bson"
"go.uber.org/zap"
)
type service struct {
logger mlogger.Logger
accountDB account.DB
config *middleware.PasswordConfig
vdb verification.DB
sessions refreshtokens.DB
transactions transaction.Factory
}
func validateUserRequest(u *model.Account) error {
if u == nil {
return merrors.InvalidArgument("account is required")
}
if u.Name == "" {
return merrors.InvalidArgument("Name must not be empty")
}
if u.Login == "" {
return merrors.InvalidArgument("Login must not be empty")
}
if u.Password == "" {
return merrors.InvalidArgument("Password must not be empty")
}
return nil
}
func (s *service) ValidatePassword(
password string,
oldPassword *string,
) error {
var hasDigit, hasUpper, hasLower, hasSpecial bool
if oldPassword != nil {
if *oldPassword == password {
return merrors.InvalidArgument("New password cannot be the same as the old password")
}
}
if len(password) < s.config.Check.MinLength {
return merrors.InvalidArgument(fmt.Sprintf("Password must be at least %d characters long", s.config.Check.MinLength))
}
// Check for digit, uppercase, lowercase, and special character
for _, char := range password {
switch {
case unicode.IsDigit(char):
hasDigit = true
case unicode.IsUpper(char):
hasUpper = true
case unicode.IsLower(char):
hasLower = true
case unicode.IsPunct(char) || unicode.IsSymbol(char):
hasSpecial = true
}
}
if s.config.Check.Digit && !hasDigit {
return merrors.InvalidArgument("Password must contain at least one digit")
}
if s.config.Check.Upper && !hasUpper {
return merrors.InvalidArgument("Password must contain at least one uppercase letter")
}
if s.config.Check.Lower && !hasLower {
return merrors.InvalidArgument("Password must contain at least one lowercase letter")
}
if s.config.Check.Special && !hasSpecial {
return merrors.InvalidArgument("Password must contain at least one special character")
}
// If all checks pass, return nil (no error)
return nil
}
func (s *service) ValidateAccount(acct *model.Account) error {
if err := validateUserRequest(acct); err != nil {
s.logger.Warn("Invalid signup account received", zap.Error(err))
return err
}
if err := s.ValidatePassword(acct.Password, nil); err != nil {
s.logger.Warn("Password validation failed", zap.Error(err), mzap.Login(acct))
return err
}
if err := acct.HashPassword(); err != nil {
s.logger.Warn("Failed to hash password", zap.Error(err), mzap.Login(acct))
return err
}
return nil
}
func (s *service) CreateAccount(
ctx context.Context,
acct *model.Account,
) (string, error) {
if acct == nil {
return "", merrors.InvalidArgument("account is required")
}
if !acct.ID.IsZero() {
return "", merrors.InvalidArgument("new account must not have an ID")
}
candidate := acct.Copy()
if err := s.ValidateAccount(candidate); err != nil {
return "", err
}
candidate.Status = model.AccountPendingVerification
// The customer and activation token either both commit or neither does.
var saved *model.Account
result, err := s.transactions.CreateTransaction().Execute(ctx, func(tx context.Context) (any, error) {
saved = candidate.Copy()
if err := s.accountDB.Create(tx, saved); err != nil {
return nil, err
}
return s.VerifyAccount(tx, saved)
})
if err != nil {
if errors.Is(err, merrors.ErrDataConflict) {
s.logger.Info("Customer login already exists")
} else {
s.logger.Warn("Customer creation failed", zap.Error(err))
}
return "", err
}
token, ok := result.(string)
if !ok {
return "", merrors.Internal("unexpected account creation result")
}
*acct = *saved
s.logger.Info("Customer created pending verification", mzap.AccRef(acct.ID))
return token, nil
}
func (s *service) VerifyAccount(
ctx context.Context,
acct *model.Account,
) (string, error) {
if acct == nil || acct.ID.IsZero() {
return "", merrors.InvalidArgument("customer reference is required")
}
token, err := s.vdb.Create(
ctx,
verification.NewLinkRequest(*acct.GetID(), model.PurposeAccountActivation, "").
WithTTL(time.Hour*24),
)
if err != nil {
s.logger.Warn("Failed to create verification token for new account", zap.Error(err), mzap.StorableRef(acct))
return "", err
}
return token, nil
}
func (s *service) DeleteAccount(
ctx context.Context,
accountRef bson.ObjectID,
) error {
if accountRef.IsZero() {
return merrors.InvalidArgument("account reference is required")
}
_, err := s.transactions.CreateTransaction().Execute(ctx, func(tx context.Context) (any, error) {
if err := s.sessions.RevokeAll(tx, accountRef, ""); err != nil {
return nil, err
}
return nil, s.accountDB.Delete(tx, accountRef)
})
if err != nil {
s.logger.Warn("Customer deletion failed", zap.Error(err), mzap.AccRef(accountRef))
return err
}
s.logger.Info("Customer deleted and sessions revoked", mzap.AccRef(accountRef))
return nil
}
func (s *service) ResetPassword(
ctx context.Context,
acct *model.Account,
) (string, error) {
if acct == nil || acct.ID.IsZero() {
return "", merrors.InvalidArgument("customer reference is required")
}
return s.vdb.Create(
ctx,
verification.NewOTPRequest(*acct.GetID(), model.PurposePasswordReset, "").
WithTTL(time.Hour),
)
}
func (s *service) UpdateLogin(
ctx context.Context,
acct *model.Account,
newLogin string,
) (string, error) {
if acct == nil || acct.ID.IsZero() {
return "", merrors.InvalidArgument("customer reference is required")
}
return s.vdb.Create(
ctx,
verification.NewOTPRequest(*acct.GetID(), model.PurposeEmailChange, newLogin).
WithTTL(time.Hour),
)
}
func NewAccountService(
l mlogger.Logger,
dbf db.Factory,
config *middleware.PasswordConfig,
storageConfig *api.AuthStorageConfig,
) (*service, error) {
logger := l.Named("account_service")
if config == nil {
return nil, merrors.Internal("password configuration is required")
}
stores, err := authstorage.OpenStores(logger, dbf, storageConfig)
if err != nil {
return nil, err
}
return &service{logger: logger, config: config, accountDB: stores.Accounts,
vdb: stores.Verification, sessions: stores.RefreshTokens, transactions: dbf.TransactionFactory()}, nil
}