Organize backend into product executable and shared Go modules
This commit is contained in:
1 parent
981e84a4b4
commit
f0720ec66b
382 files changed
+1944
-6989
No files matched your search
@@ -0,0 +1,131 @@
|
||||
package accountserviceimp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.sendico.io/tech/sxchnge/product/auth/config"
|
||||
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
|
||||
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
|
||||
verificationmodel "git.sendico.io/tech/sxchnge/product/verification/model"
|
||||
"git.sendico.io/tech/sxchnge/product/verification/store"
|
||||
"git.sendico.io/tech/sxchnge/shared/database"
|
||||
edgemongo "git.sendico.io/tech/sxchnge/shared/database/dependencies"
|
||||
"git.sendico.io/tech/sxchnge/shared/errors"
|
||||
sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/testcontainers/testcontainers-go/modules/mongodb"
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
"go.uber.org/zap"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func customer(login string) *customermodel.Account {
|
||||
return (&customermodel.AccountData{LoginData: customermodel.LoginData{UserDataBase: customermodel.UserDataBase{Login: login}, Password: "CustomerPassword1!"}, Describable: sharedmodel.Describable{Name: "Customer"}}).ToAccount()
|
||||
}
|
||||
|
||||
// Uses the actual copied repositories against an empty SXCHNGE database.
|
||||
// There is deliberately no seed, organization, role, policy or Sendico connection.
|
||||
func TestCustomerLifecycleWithoutTenancy(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
container, err := mongodb.Run(ctx, "mongo:8", mongodb.WithReplicaSet("rs"))
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, container.Terminate(context.Background())) })
|
||||
uri, err := container.ConnectionString(ctx)
|
||||
require.NoError(t, err)
|
||||
endpoint, err := url.Parse(uri)
|
||||
require.NoError(t, err)
|
||||
query := endpoint.Query()
|
||||
query.Set("directConnection", "true")
|
||||
endpoint.RawQuery = query.Encode()
|
||||
uri = endpoint.String()
|
||||
factory, err := db.NewConnection(zap.NewNop(), &db.Config{Driver: db.Mongo, Settings: sharedmodel.SettingsT{"uri": uri, "database": "sxchnge_customers"}})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(factory.CloseConnection)
|
||||
// Custom collections prove lifecycle and login storage select the same data.
|
||||
config := &middleware.AuthStorageConfig{AccountsCollection: "customers", VerificationTokensCollection: "customer_verification", RefreshTokensCollection: "customer_sessions"}
|
||||
svc, err := NewAccountService(zap.NewNop(), factory, &middleware.PasswordConfig{Check: middleware.PasswordChecks{MinLength: 12}}, config)
|
||||
require.NoError(t, err)
|
||||
first, second := customer("first@example.test"), customer("second@example.test")
|
||||
firstToken, err := svc.CreateAccount(ctx, first)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, firstToken)
|
||||
require.Equal(t, customermodel.AccountPendingVerification, first.Status)
|
||||
require.True(t, first.MatchPassword("CustomerPassword1!"))
|
||||
_, err = svc.CreateAccount(ctx, second)
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, first.ID, second.ID)
|
||||
// Activation tokens cannot be used as another customer's token.
|
||||
_, err = svc.vdb.Consume(ctx, second.ID, verificationmodel.PurposeAccountActivation, "", firstToken)
|
||||
require.Error(t, err)
|
||||
_, err = svc.vdb.Consume(ctx, first.ID, verificationmodel.PurposeAccountActivation, "", firstToken)
|
||||
require.NoError(t, err)
|
||||
_, err = svc.CreateAccount(ctx, customer("first@example.test"))
|
||||
require.ErrorIs(t, err, merrors.ErrDataConflict)
|
||||
require.NoError(t, svc.ValidateAccount(customer("validate@example.test")))
|
||||
require.ErrorIs(t, svc.ValidateAccount(nil), merrors.ErrInvalidArg)
|
||||
_, err = svc.CreateAccount(ctx, nil)
|
||||
require.ErrorIs(t, err, merrors.ErrInvalidArg)
|
||||
require.ErrorIs(t, svc.DeleteAccount(ctx, bson.NilObjectID), merrors.ErrInvalidArg)
|
||||
|
||||
for _, c := range []*customermodel.Account{first, second} {
|
||||
require.NoError(t, svc.sessions.Create(ctx, &sessionmodel.RefreshToken{AccountRef: &c.ID, ExpiresAt: time.Now().Add(time.Hour), ClientRefreshToken: sessionmodel.ClientRefreshToken{SessionIdentifier: sessionmodel.SessionIdentifier{ClientID: "web", DeviceID: "device", SessionVersion: "v1"}, RefreshToken: c.ID.Hex()}}))
|
||||
}
|
||||
require.NoError(t, svc.DeleteAccount(ctx, first.ID))
|
||||
var stored customermodel.Account
|
||||
require.ErrorIs(t, svc.accountDB.Get(ctx, first.ID, &stored), merrors.ErrNoData)
|
||||
require.NoError(t, svc.accountDB.Get(ctx, second.ID, &stored))
|
||||
session := &sessionmodel.SessionIdentifier{ClientID: "web", DeviceID: "device", SessionVersion: "v1"}
|
||||
_, err = svc.sessions.GetSession(ctx, first.ID, session)
|
||||
require.Error(t, err)
|
||||
_, err = svc.sessions.GetSession(ctx, second.ID, session)
|
||||
require.NoError(t, err)
|
||||
// The final local customer can be deleted; there is no sole-member restriction.
|
||||
require.NoError(t, svc.DeleteAccount(ctx, second.ID))
|
||||
|
||||
deps, err := edgemongo.ResolveDependencies(factory)
|
||||
require.NoError(t, err)
|
||||
collections, err := deps.Database.ListCollectionNames(ctx, bson.D{})
|
||||
require.NoError(t, err)
|
||||
for _, forbidden := range []string{"organizations", "roles", "policies", "policy_assignments", "invitations", "accounts"} {
|
||||
require.NotContains(t, collections, forbidden)
|
||||
}
|
||||
|
||||
// A token issuance failure must roll back the preceding customer insert.
|
||||
realVerification := svc.vdb
|
||||
failure := merrors.Internal("injected verification failure")
|
||||
svc.vdb = &failingVerification{DB: realVerification, failure: failure}
|
||||
candidate := customer("rollback@example.test")
|
||||
_, err = svc.CreateAccount(ctx, candidate)
|
||||
require.ErrorIs(t, err, failure)
|
||||
require.True(t, candidate.ID.IsZero())
|
||||
_, err = svc.accountDB.GetByEmail(ctx, candidate.Login)
|
||||
require.ErrorIs(t, err, merrors.ErrNoData)
|
||||
svc.vdb = realVerification
|
||||
|
||||
// If an outer workflow fails after token issuance, neither write may commit.
|
||||
outerFailure := merrors.Internal("injected outer failure")
|
||||
_, err = factory.TransactionFactory().CreateTransaction().Execute(ctx, func(tx context.Context) (any, error) {
|
||||
_, e := svc.CreateAccount(tx, customer("outer@example.test"))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return nil, outerFailure
|
||||
})
|
||||
require.ErrorIs(t, err, outerFailure)
|
||||
_, err = svc.accountDB.GetByEmail(ctx, "outer@example.test")
|
||||
require.ErrorIs(t, err, merrors.ErrNoData)
|
||||
count, err := deps.Database.Collection(config.VerificationTokensCollection).CountDocuments(ctx, bson.D{})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 2, count)
|
||||
}
|
||||
|
||||
type failingVerification struct {
|
||||
verification.DB
|
||||
failure error
|
||||
}
|
||||
|
||||
func (f *failingVerification) Create(context.Context, *verification.Request) (string, error) {
|
||||
return "", f.failure
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
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) {
|
||||
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.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 *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 &service{logger: logger, config: config, accountDB: stores.Accounts,
|
||||
vdb: stores.Verification, sessions: stores.RefreshTokens, transactions: dbf.TransactionFactory()}, nil
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package accountserviceimp
|
||||
|
||||
import (
|
||||
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
|
||||
sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
|
||||
"testing"
|
||||
|
||||
apiconfig "git.sendico.io/tech/sxchnge/product/auth/config"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// TestValidatePassword tests the password validation logic directly
|
||||
func TestValidatePassword(t *testing.T) {
|
||||
config := &apiconfig.PasswordConfig{
|
||||
Check: apiconfig.PasswordChecks{
|
||||
MinLength: 8,
|
||||
Digit: true,
|
||||
Upper: true,
|
||||
Lower: true,
|
||||
Special: true,
|
||||
},
|
||||
TokenLength: 32,
|
||||
}
|
||||
|
||||
// Create a minimal service for testing password validation
|
||||
logger := zap.NewNop() // Use no-op logger for tests
|
||||
service := &service{
|
||||
config: config,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
t.Run("ValidPassword", func(t *testing.T) {
|
||||
err := service.ValidatePassword("TestPassword123!", nil)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("PasswordTooShort", func(t *testing.T) {
|
||||
err := service.ValidatePassword("Test1!", nil)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "at least 8 characters")
|
||||
})
|
||||
|
||||
t.Run("PasswordMissingDigit", func(t *testing.T) {
|
||||
err := service.ValidatePassword("TestPassword!", nil)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "at least one digit")
|
||||
})
|
||||
|
||||
t.Run("PasswordMissingUppercase", func(t *testing.T) {
|
||||
err := service.ValidatePassword("testpassword123!", nil)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "at least one uppercase")
|
||||
})
|
||||
|
||||
t.Run("PasswordMissingLowercase", func(t *testing.T) {
|
||||
err := service.ValidatePassword("TESTPASSWORD123!", nil)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "at least one lowercase")
|
||||
})
|
||||
|
||||
t.Run("PasswordMissingSpecialCharacter", func(t *testing.T) {
|
||||
err := service.ValidatePassword("TestPassword123", nil)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "at least one special character")
|
||||
})
|
||||
|
||||
t.Run("PasswordSameAsOld", func(t *testing.T) {
|
||||
oldPassword := "TestPassword123!"
|
||||
err := service.ValidatePassword("TestPassword123!", &oldPassword)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "cannot be the same as the old password")
|
||||
})
|
||||
}
|
||||
|
||||
// TestValidateAccount tests the account validation logic directly
|
||||
func TestValidateAccount(t *testing.T) {
|
||||
config := &apiconfig.PasswordConfig{
|
||||
Check: apiconfig.PasswordChecks{
|
||||
MinLength: 8,
|
||||
Digit: true,
|
||||
Upper: true,
|
||||
Lower: true,
|
||||
Special: true,
|
||||
},
|
||||
TokenLength: 32,
|
||||
}
|
||||
|
||||
logger := zap.NewNop() // Use no-op logger for tests
|
||||
service := &service{
|
||||
config: config,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
t.Run("ValidAccount", func(t *testing.T) {
|
||||
account := &customermodel.Account{
|
||||
AccountPublic: customermodel.AccountPublic{
|
||||
AccountBase: customermodel.AccountBase{
|
||||
Describable: sharedmodel.Describable{
|
||||
Name: "Test User",
|
||||
},
|
||||
},
|
||||
UserDataBase: customermodel.UserDataBase{
|
||||
Login: "test@example.com",
|
||||
},
|
||||
},
|
||||
Password: "TestPassword123!",
|
||||
}
|
||||
|
||||
originalPassword := account.Password
|
||||
err := service.ValidateAccount(account)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Password should be hashed after validation
|
||||
assert.NotEqual(t, originalPassword, account.Password)
|
||||
})
|
||||
|
||||
t.Run("AccountMissingName", func(t *testing.T) {
|
||||
account := &customermodel.Account{
|
||||
AccountPublic: customermodel.AccountPublic{
|
||||
UserDataBase: customermodel.UserDataBase{
|
||||
Login: "test@example.com",
|
||||
},
|
||||
},
|
||||
Password: "TestPassword123!",
|
||||
}
|
||||
|
||||
err := service.ValidateAccount(account)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "Name must not be empty")
|
||||
})
|
||||
|
||||
t.Run("AccountMissingLogin", func(t *testing.T) {
|
||||
account := &customermodel.Account{
|
||||
AccountPublic: customermodel.AccountPublic{
|
||||
AccountBase: customermodel.AccountBase{
|
||||
Describable: sharedmodel.Describable{
|
||||
Name: "Test User",
|
||||
},
|
||||
},
|
||||
},
|
||||
Password: "TestPassword123!",
|
||||
}
|
||||
|
||||
err := service.ValidateAccount(account)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "Login must not be empty")
|
||||
})
|
||||
|
||||
t.Run("AccountMissingPassword", func(t *testing.T) {
|
||||
account := &customermodel.Account{
|
||||
AccountPublic: customermodel.AccountPublic{
|
||||
AccountBase: customermodel.AccountBase{
|
||||
Describable: sharedmodel.Describable{
|
||||
Name: "Test User",
|
||||
},
|
||||
},
|
||||
UserDataBase: customermodel.UserDataBase{
|
||||
Login: "test@example.com",
|
||||
},
|
||||
},
|
||||
Password: "",
|
||||
}
|
||||
|
||||
err := service.ValidateAccount(account)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "Password must not be empty")
|
||||
})
|
||||
|
||||
t.Run("AccountInvalidPassword", func(t *testing.T) {
|
||||
account := &customermodel.Account{
|
||||
AccountPublic: customermodel.AccountPublic{
|
||||
AccountBase: customermodel.AccountBase{
|
||||
Describable: sharedmodel.Describable{
|
||||
Name: "Test User",
|
||||
},
|
||||
},
|
||||
UserDataBase: customermodel.UserDataBase{
|
||||
Login: "test@example.com",
|
||||
},
|
||||
},
|
||||
Password: "weak", // Should fail validation
|
||||
}
|
||||
|
||||
err := service.ValidateAccount(account)
|
||||
assert.Error(t, err)
|
||||
// Should fail on password validation
|
||||
assert.Contains(t, err.Error(), "at least 8 characters")
|
||||
})
|
||||
}
|
||||
|
||||
// TestPasswordConfiguration verifies different password rule configurations
|
||||
func TestPasswordConfiguration(t *testing.T) {
|
||||
t.Run("MinimalRequirements", func(t *testing.T) {
|
||||
config := &apiconfig.PasswordConfig{
|
||||
Check: apiconfig.PasswordChecks{
|
||||
MinLength: 4,
|
||||
Digit: false,
|
||||
Upper: false,
|
||||
Lower: false,
|
||||
Special: false,
|
||||
},
|
||||
TokenLength: 16,
|
||||
}
|
||||
|
||||
logger := zap.NewNop() // Use no-op logger for tests
|
||||
service := &service{
|
||||
config: config,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
// Should pass with minimal requirements
|
||||
err := service.ValidatePassword("test", nil)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("StrictRequirements", func(t *testing.T) {
|
||||
config := &apiconfig.PasswordConfig{
|
||||
Check: apiconfig.PasswordChecks{
|
||||
MinLength: 12,
|
||||
Digit: true,
|
||||
Upper: true,
|
||||
Lower: true,
|
||||
Special: true,
|
||||
},
|
||||
TokenLength: 64,
|
||||
}
|
||||
|
||||
logger := zap.NewNop() // Use no-op logger for tests
|
||||
service := &service{
|
||||
config: config,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
// Should fail with shorter password
|
||||
err := service.ValidatePassword("Test123!", nil)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "at least 12 characters")
|
||||
|
||||
// Should pass with longer password
|
||||
err = service.ValidatePassword("TestPassword123!", nil)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"git.sendico.io/tech/sxchnge/shared/database/record"
|
||||
sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
|
||||
"git.sendico.io/tech/sxchnge/shared/service"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type Filter int
|
||||
|
||||
type AccountStatus string
|
||||
|
||||
const (
|
||||
AccountPendingVerification AccountStatus = "pending_verification"
|
||||
AccountActive AccountStatus = "active"
|
||||
AccountBlocked AccountStatus = "blocked"
|
||||
)
|
||||
|
||||
type AccountBase struct {
|
||||
storable.Base `bson:",inline" json:",inline"`
|
||||
sharedmodel.ArchivableBase `bson:",inline" json:",inline"`
|
||||
sharedmodel.Describable `bson:",inline" json:",inline"`
|
||||
LastName string `bson:"lastName" json:"lastName"`
|
||||
AvatarURL *string `bson:"avatarUrl,omitempty" json:"avatarUrl,omitempty"`
|
||||
}
|
||||
|
||||
func (*AccountBase) Collection() string {
|
||||
return mservice.Accounts
|
||||
}
|
||||
|
||||
type AccountPublic struct {
|
||||
AccountBase `bson:",inline" json:",inline"`
|
||||
UserDataBase `bson:",inline" json:",inline"`
|
||||
}
|
||||
|
||||
type Account struct {
|
||||
AccountPublic `bson:",inline" json:",inline"`
|
||||
Password string `bson:"password" json:"-"` // password hash
|
||||
Status AccountStatus `bson:"status" json:"-"`
|
||||
}
|
||||
|
||||
func (a *Account) Copy() *Account {
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
copied := *a
|
||||
return &copied
|
||||
}
|
||||
|
||||
func (a *Account) IsActive() bool {
|
||||
return a.Status == AccountActive
|
||||
}
|
||||
|
||||
func (a *Account) HashPassword() error {
|
||||
key, err := bcrypt.GenerateFromPassword([]byte(a.Password), bcrypt.DefaultCost)
|
||||
if err == nil {
|
||||
a.Password = string(key)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *Account) MatchPassword(password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password))
|
||||
|
||||
return err == nil
|
||||
}
|
||||
|
||||
const AccountRefField = "accountRef"
|
||||
@@ -0,0 +1,32 @@
|
||||
package model
|
||||
|
||||
import sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
|
||||
|
||||
type UserDataBase struct {
|
||||
Login string `bson:"login" json:"login"`
|
||||
Locale string `bson:"locale" json:"locale"`
|
||||
}
|
||||
|
||||
type LoginData struct {
|
||||
UserDataBase `bson:",inline" json:",inline"`
|
||||
Password string ` bson:"-" json:"password"`
|
||||
}
|
||||
|
||||
type AccountData struct {
|
||||
LoginData `bson:",inline" json:",inline"`
|
||||
sharedmodel.Describable `bson:",inline" json:",inline"`
|
||||
LastName string `bson:"lastName" json:"lastName"`
|
||||
}
|
||||
|
||||
func (ad *AccountData) ToAccount() *Account {
|
||||
return &Account{
|
||||
AccountPublic: AccountPublic{
|
||||
AccountBase: AccountBase{
|
||||
Describable: ad.Describable,
|
||||
LastName: ad.LastName,
|
||||
},
|
||||
UserDataBase: ad.UserDataBase,
|
||||
},
|
||||
Password: ad.Password,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
|
||||
|
||||
"git.sendico.io/tech/sxchnge/shared/database/template"
|
||||
)
|
||||
|
||||
// DB is the interface which must be implemented by all db drivers
|
||||
type DB interface {
|
||||
template.DB[*customermodel.Account]
|
||||
GetByEmail(ctx context.Context, email string) (*customermodel.Account, error)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package accountdb
|
||||
|
||||
import (
|
||||
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
|
||||
"strings"
|
||||
|
||||
ri "git.sendico.io/tech/sxchnge/shared/database/repository/index"
|
||||
"git.sendico.io/tech/sxchnge/shared/database/template"
|
||||
"git.sendico.io/tech/sxchnge/shared/logging"
|
||||
"git.sendico.io/tech/sxchnge/shared/service"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type AccountDB struct {
|
||||
template.DBImp[*customermodel.Account]
|
||||
}
|
||||
|
||||
func Create(logger mlogger.Logger, db *mongo.Database) (*AccountDB, error) {
|
||||
return CreateWithCollection(logger, db, mservice.Accounts)
|
||||
}
|
||||
|
||||
func CreateWithCollection(logger mlogger.Logger, db *mongo.Database, collection string) (*AccountDB, error) {
|
||||
if normalized := strings.TrimSpace(collection); normalized != "" {
|
||||
collection = normalized
|
||||
} else {
|
||||
collection = mservice.Accounts
|
||||
}
|
||||
|
||||
p := &AccountDB{
|
||||
DBImp: *template.Create[*customermodel.Account](logger, collection, db),
|
||||
}
|
||||
|
||||
if err := p.Repository.CreateIndex(&ri.Definition{
|
||||
Keys: []ri.Key{{Field: "login", Sort: ri.Asc}},
|
||||
Unique: true,
|
||||
}); err != nil {
|
||||
p.Logger.Error("Failed to create account database", zap.Error(err), zap.String("collection", collection))
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package accountdb
|
||||
|
||||
import (
|
||||
"context"
|
||||
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
|
||||
|
||||
"git.sendico.io/tech/sxchnge/shared/database/repository"
|
||||
)
|
||||
|
||||
func (db *AccountDB) GetByEmail(ctx context.Context, email string) (*customermodel.Account, error) {
|
||||
var account customermodel.Account
|
||||
return &account, db.FindOne(ctx, repository.Filter("login", email), &account)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package accountservice
|
||||
|
||||
import (
|
||||
"context"
|
||||
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
|
||||
|
||||
"git.sendico.io/tech/sxchnge/product/auth/config"
|
||||
accountserviceimp "git.sendico.io/tech/sxchnge/product/customers/internal"
|
||||
"git.sendico.io/tech/sxchnge/shared/database"
|
||||
"git.sendico.io/tech/sxchnge/shared/logging"
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
)
|
||||
|
||||
// AccountService defines all account-related workflows.
|
||||
type AccountService interface {
|
||||
// ValidatePassword will:
|
||||
// 1) check passsword conformance
|
||||
ValidatePassword(
|
||||
password string,
|
||||
oldPassword *string,
|
||||
) error
|
||||
|
||||
// ResetPassword will:
|
||||
// 1) generate reset password token
|
||||
ResetPassword(
|
||||
ctx context.Context,
|
||||
acct *customermodel.Account,
|
||||
) (verificationToken string, err error)
|
||||
|
||||
// CreateAccount will:
|
||||
// 1) validate and hash the password, then create the account
|
||||
// 2) issue an activation token
|
||||
CreateAccount(
|
||||
ctx context.Context,
|
||||
acct *customermodel.Account,
|
||||
) (verificationToken string, err error)
|
||||
|
||||
VerifyAccount(
|
||||
ctx context.Context,
|
||||
acct *customermodel.Account,
|
||||
) (verificationToken string, err error)
|
||||
|
||||
UpdateLogin(
|
||||
ctx context.Context,
|
||||
acct *customermodel.Account,
|
||||
newLogin string,
|
||||
) (verificationToken string, err error)
|
||||
|
||||
// DeleteAccount deletes the local customer account.
|
||||
DeleteAccount(
|
||||
ctx context.Context,
|
||||
accountRef bson.ObjectID,
|
||||
) error
|
||||
}
|
||||
|
||||
func NewAccountService(
|
||||
logger mlogger.Logger,
|
||||
dbf db.Factory,
|
||||
config *middleware.PasswordConfig,
|
||||
storageConfig *middleware.AuthStorageConfig,
|
||||
) (AccountService, error) {
|
||||
return accountserviceimp.NewAccountService(logger, dbf, config, storageConfig)
|
||||
}
|
||||
Reference in new issue
Block a user