package accountserviceimp import ( "context" "errors" "fmt" customermodel "git.sendico.io/tech/sxchnge/product/customers/model" verificationmodel "git.sendico.io/tech/sxchnge/product/verification/model" "time" "unicode" "git.sendico.io/tech/sxchnge/product/auth/config" authstorage "git.sendico.io/tech/sxchnge/product/auth/storage" "git.sendico.io/tech/sxchnge/product/customers/store" "git.sendico.io/tech/sxchnge/product/sessions/store" "git.sendico.io/tech/sxchnge/product/verification/store" "git.sendico.io/tech/sxchnge/shared/database" "git.sendico.io/tech/sxchnge/shared/database/transaction" "git.sendico.io/tech/sxchnge/shared/errors" "git.sendico.io/tech/sxchnge/shared/logging" "git.sendico.io/tech/sxchnge/shared/logging/fields" "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 *customermodel.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 *customermodel.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.Email(acct.Login)) return err } if err := acct.HashPassword(); err != nil { s.logger.Warn("Failed to hash password", zap.Error(err), mzap.Email(acct.Login)) return err } return nil } func (s *service) CreateAccount( ctx context.Context, acct *customermodel.Account, ) (string, error) { return s.createAccount(ctx, acct, "") } func (s *service) CreateAccountWithActivationKey(ctx context.Context, acct *customermodel.Account, key string) (string, error) { if len(key) < 32 || len(key) > 128 { return "", merrors.InvalidArgument("server activation key required") } return s.createAccount(ctx, acct, key) } func (s *service) createAccount(ctx context.Context, acct *customermodel.Account, key string) (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 = customermodel.AccountPendingVerification // The customer and activation token either both commit or neither does. var saved *customermodel.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.vdb.Create(tx, verification.NewLinkRequest(saved.ID, verificationmodel.PurposeAccountActivation, "").WithTTL(24*time.Hour).WithIdempotencyKey(key)) }) 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 *customermodel.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(), verificationmodel.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 *customermodel.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(), verificationmodel.PurposePasswordReset, ""). WithTTL(time.Hour), ) } func (s *service) UpdateLogin( ctx context.Context, acct *customermodel.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(), verificationmodel.PurposeEmailChange, newLogin). WithTTL(time.Hour), ) } func NewAccountService( l mlogger.Logger, dbf db.Factory, config *middleware.PasswordConfig, storageConfig *middleware.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 FromStores(l, config, stores, dbf.TransactionFactory()) } func FromStores(l mlogger.Logger, config *middleware.PasswordConfig, stores *authstorage.Stores, transactions transaction.Factory) (*service, error) { if config == nil || stores == nil || transactions == nil { return nil, merrors.InvalidArgument("customer dependencies are required") } return &service{logger: l.Named("account_service"), config: config, accountDB: stores.Accounts, vdb: stores.Verification, sessions: stores.RefreshTokens, transactions: transactions}, nil }