You've already forked golang-saas-starter-kit
mirror of
https://github.com/raseels-repos/golang-saas-starter-kit.git
synced 2025-06-17 00:17:59 +02:00
completed unittests for users package
This commit is contained in:
@ -100,7 +100,7 @@ func migrationList(db *sqlx.DB, log *log.Logger) []*sqlxmigrate.Migration {
|
|||||||
return errors.WithMessagef(err, "Query failed %s", q1)
|
return errors.WithMessagef(err, "Query failed %s", q1)
|
||||||
}
|
}
|
||||||
|
|
||||||
q2 := `CREATE TYPE user_account_status_t as enum('active','disabled')`
|
q2 := `CREATE TYPE user_account_status_t as enum('active', 'invited','disabled')`
|
||||||
if _, err := tx.Exec(q2); err != nil {
|
if _, err := tx.Exec(q2); err != nil {
|
||||||
return errors.WithMessagef(err, "Query failed %s", q2)
|
return errors.WithMessagef(err, "Query failed %s", q2)
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,7 @@ package user
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"gopkg.in/go-playground/validator.v9"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
||||||
@ -12,23 +13,27 @@ import (
|
|||||||
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
|
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TokenGenerator is the behavior we need in our Authenticate to generate
|
// TokenGenerator is the behavior we need in our Authenticate to generate tokens for
|
||||||
// tokens for authenticated users.
|
// authenticated users.
|
||||||
type TokenGenerator interface {
|
type TokenGenerator interface {
|
||||||
GenerateToken(auth.Claims) (string, error)
|
GenerateToken(auth.Claims) (string, error)
|
||||||
|
ParseClaims(string) (auth.Claims, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Authenticate finds a user by their email and verifies their password. On
|
// Authenticate finds a user by their email and verifies their password. On success
|
||||||
// success it returns a Token that can be used to authenticate in the future.
|
// it returns a Token that can be used to authenticate access to the application in
|
||||||
func Authenticate(ctx context.Context, dbConn *sqlx.DB, tknGen TokenGenerator, now time.Time, email, password string) (Token, error) {
|
// the future.
|
||||||
|
func Authenticate(ctx context.Context, dbConn *sqlx.DB, tknGen TokenGenerator, email, password string, expires time.Duration, now time.Time) (Token, error) {
|
||||||
span, ctx := tracer.StartSpanFromContext(ctx, "internal.user.Authenticate")
|
span, ctx := tracer.StartSpanFromContext(ctx, "internal.user.Authenticate")
|
||||||
defer span.Finish()
|
defer span.Finish()
|
||||||
|
|
||||||
// Generate sql query to select user by email address
|
// Generate sql query to select user by email address.
|
||||||
query := sqlbuilder.NewSelectBuilder()
|
query := sqlbuilder.NewSelectBuilder()
|
||||||
query.Where(query.Equal("email", email))
|
query.Where(query.Equal("email", email))
|
||||||
|
|
||||||
// Run the find, use empty claims to bypass ACLs
|
// Run the find, use empty claims to bypass ACLs since this in an internal request
|
||||||
|
// and the current user is not authenticated at this point. If the email is
|
||||||
|
// invalid, return the same error as when an invalid password is supplied.
|
||||||
res, err := find(ctx, auth.Claims{}, dbConn, query, []interface{}{}, false)
|
res, err := find(ctx, auth.Claims{}, dbConn, query, []interface{}{}, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Token{}, err
|
return Token{}, err
|
||||||
@ -39,43 +44,104 @@ func Authenticate(ctx context.Context, dbConn *sqlx.DB, tknGen TokenGenerator, n
|
|||||||
u := res[0]
|
u := res[0]
|
||||||
|
|
||||||
// Append the salt from the user record to the supplied password.
|
// Append the salt from the user record to the supplied password.
|
||||||
saltedPassword := password + string(u.PasswordSalt)
|
saltedPassword := password + u.PasswordSalt
|
||||||
|
|
||||||
// Compare the provided password with the saved hash. Use the bcrypt
|
// Compare the provided password with the saved hash. Use the bcrypt comparison
|
||||||
// comparison function so it is cryptographically secure.
|
// function so it is cryptographically secure. Return authentication error for
|
||||||
|
// invalid password.
|
||||||
if err := bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(saltedPassword)); err != nil {
|
if err := bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(saltedPassword)); err != nil {
|
||||||
err = errors.WithStack(ErrAuthenticationFailure)
|
err = errors.WithStack(ErrAuthenticationFailure)
|
||||||
return Token{}, err
|
return Token{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get a list of all the account ids associated with the user.
|
// The user is successfully authenticated with the supplied email and password.
|
||||||
accounts, err := FindAccountsByUserID(ctx, auth.Claims{}, dbConn, u.ID, false)
|
return generateToken(ctx, dbConn, tknGen, auth.Claims{}, u.ID, "", expires, now)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authenticate finds a user by their email and verifies their password. On success
|
||||||
|
// it returns a Token that can be used to authenticate access to the application in
|
||||||
|
// the future.
|
||||||
|
func SwitchAccount(ctx context.Context, dbConn *sqlx.DB, tknGen TokenGenerator, claims auth.Claims, accountID string, expires time.Duration, now time.Time) (Token, error) {
|
||||||
|
span, ctx := tracer.StartSpanFromContext(ctx, "internal.user.SwitchAccount")
|
||||||
|
defer span.Finish()
|
||||||
|
|
||||||
|
// Defines struct to apply validation for the supplied claims and account ID.
|
||||||
|
req := struct {
|
||||||
|
UserID string `validate:"required,uuid"`
|
||||||
|
AccountID string `validate:"required,uuid"`
|
||||||
|
}{
|
||||||
|
UserID: claims.Subject,
|
||||||
|
AccountID: accountID,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate the request.
|
||||||
|
err := validator.New().Struct(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Token{}, err
|
return Token{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Claims needs an audience, select the first account associated with
|
// Generate a token for the user ID in supplied in claims as the Subject. Pass
|
||||||
// the user.
|
// in the supplied claims as well to enforce ACLs when finding the current
|
||||||
var (
|
// list of accounts for the user.
|
||||||
accountId string
|
return generateToken(ctx, dbConn, tknGen, claims, req.UserID, req.AccountID, expires, now)
|
||||||
roles []string
|
}
|
||||||
)
|
|
||||||
|
// generateToken generates claims for the supplied user ID and account ID and then
|
||||||
|
// returns the token for the generated claims used for authentication.
|
||||||
|
func generateToken(ctx context.Context, dbConn *sqlx.DB, tknGen TokenGenerator, claims auth.Claims, userID, accountID string, expires time.Duration, now time.Time) (Token, error) {
|
||||||
|
// Get a list of all the accounts associated with the user.
|
||||||
|
accounts, err := FindAccountsByUserID(ctx, auth.Claims{}, dbConn, userID, false)
|
||||||
|
if err != nil {
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load the user account entry for the specifed account ID. If none provided,
|
||||||
|
// choose the first.
|
||||||
|
var account *UserAccount
|
||||||
|
if accountID == "" {
|
||||||
|
// Select the first account associated with the user. For the login flow,
|
||||||
|
// users could be forced to select a specific account to override this.
|
||||||
if len(accounts) > 0 {
|
if len(accounts) > 0 {
|
||||||
accountId = accounts[0].AccountID
|
account = accounts[0]
|
||||||
for _, r := range accounts[0].Roles {
|
accountID = account.AccountID
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Loop through all the accounts found for the user and select the specified
|
||||||
|
// account.
|
||||||
|
for _, a := range accounts {
|
||||||
|
if a.AccountID == accountID {
|
||||||
|
account = a
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no matching entry was found for the specified account ID throw an error.
|
||||||
|
if account == nil {
|
||||||
|
err = errors.WithStack(ErrAuthenticationFailure)
|
||||||
|
return Token{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate list of user defined roles for accessing the account.
|
||||||
|
var roles []string
|
||||||
|
if account != nil {
|
||||||
|
for _, r := range account.Roles {
|
||||||
roles = append(roles, r.String())
|
roles = append(roles, r.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate a list of all the account IDs associated with the user so
|
// Generate a list of all the account IDs associated with the user so the use
|
||||||
// the use has the ability to switch between accounts.
|
// has the ability to switch between accounts.
|
||||||
accountIds := []string{}
|
var accountIds []string
|
||||||
for _, a := range accounts {
|
for _, a := range accounts {
|
||||||
accountIds = append(accountIds, a.AccountID)
|
accountIds = append(accountIds, a.AccountID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we are this far the request is valid. Create some claims for the user.
|
// JWT claims requires both an audience and a subject. For this application:
|
||||||
claims := auth.NewClaims(u.ID, accountId, accountIds, roles, now, time.Hour)
|
// Subject: The ID of the user authenticated.
|
||||||
|
// Audience: The ID of the account the user is accessing. A list of account IDs
|
||||||
|
// will also be included to support the user switching between them.
|
||||||
|
claims = auth.NewClaims(userID, accountID, accountIds, roles, now, expires)
|
||||||
|
|
||||||
// Generate a token for the user with the defined claims.
|
// Generate a token for the user with the defined claims.
|
||||||
tkn, err := tknGen.GenerateToken(claims)
|
tkn, err := tknGen.GenerateToken(claims)
|
||||||
|
@ -15,31 +15,33 @@ import (
|
|||||||
|
|
||||||
// mockTokenGenerator is used for testing that Authenticate calls its provided
|
// mockTokenGenerator is used for testing that Authenticate calls its provided
|
||||||
// token generator in a specific way.
|
// token generator in a specific way.
|
||||||
type mockTokenGenerator struct{}
|
type mockTokenGenerator struct {
|
||||||
|
// Private key generated by GenerateToken that is need for ParseClaims
|
||||||
// Private key generated by GenerateToken that is need for ParseClaims
|
key *rsa.PrivateKey
|
||||||
var mockTokenKey *rsa.PrivateKey
|
// algorithm is the method used to generate the private key.
|
||||||
|
algorithm string
|
||||||
|
}
|
||||||
|
|
||||||
// GenerateToken implements the TokenGenerator interface. It returns a "token"
|
// GenerateToken implements the TokenGenerator interface. It returns a "token"
|
||||||
// that includes some information about the claims it was passed.
|
// that includes some information about the claims it was passed.
|
||||||
func (g mockTokenGenerator) GenerateToken(claims auth.Claims) (string, error) {
|
func (g *mockTokenGenerator) GenerateToken(claims auth.Claims) (string, error) {
|
||||||
privateKey, err := auth.Keygen()
|
privateKey, err := auth.Keygen()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
mockTokenKey, err = jwt.ParseRSAPrivateKeyFromPEM(privateKey)
|
g.key, err = jwt.ParseRSAPrivateKeyFromPEM(privateKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
algorithm := "RS256"
|
g.algorithm = "RS256"
|
||||||
method := jwt.GetSigningMethod(algorithm)
|
method := jwt.GetSigningMethod(g.algorithm)
|
||||||
|
|
||||||
tkn := jwt.NewWithClaims(method, claims)
|
tkn := jwt.NewWithClaims(method, claims)
|
||||||
tkn.Header["kid"] = "1"
|
tkn.Header["kid"] = "1"
|
||||||
|
|
||||||
str, err := tkn.SignedString(mockTokenKey)
|
str, err := tkn.SignedString(g.key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@ -49,18 +51,17 @@ func (g mockTokenGenerator) GenerateToken(claims auth.Claims) (string, error) {
|
|||||||
|
|
||||||
// ParseClaims recreates the Claims that were used to generate a token. It
|
// ParseClaims recreates the Claims that were used to generate a token. It
|
||||||
// verifies that the token was signed using our key.
|
// verifies that the token was signed using our key.
|
||||||
func (g mockTokenGenerator) ParseClaims(tknStr string) (auth.Claims, error) {
|
func (g *mockTokenGenerator) ParseClaims(tknStr string) (auth.Claims, error) {
|
||||||
algorithm := "RS256"
|
|
||||||
parser := jwt.Parser{
|
parser := jwt.Parser{
|
||||||
ValidMethods: []string{algorithm},
|
ValidMethods: []string{g.algorithm},
|
||||||
}
|
}
|
||||||
|
|
||||||
if mockTokenKey == nil {
|
if g.key == nil {
|
||||||
panic("key is nil")
|
return auth.Claims{}, errors.New("Private key is empty.")
|
||||||
}
|
}
|
||||||
|
|
||||||
f := func(t *jwt.Token) (interface{}, error) {
|
f := func(t *jwt.Token) (interface{}, error) {
|
||||||
return mockTokenKey.Public().(*rsa.PublicKey), nil
|
return g.key.Public().(*rsa.PublicKey), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var claims auth.Claims
|
var claims auth.Claims
|
||||||
@ -93,7 +94,7 @@ func TestAuthenticate(t *testing.T) {
|
|||||||
now := time.Now().Add(time.Hour * -1)
|
now := time.Now().Add(time.Hour * -1)
|
||||||
|
|
||||||
// Try to authenticate an invalid user.
|
// Try to authenticate an invalid user.
|
||||||
_, err := Authenticate(ctx, test.MasterDB, tknGen, now, "doesnotexist@gmail.com", "xy7")
|
_, err := Authenticate(ctx, test.MasterDB, tknGen, "doesnotexist@gmail.com", "xy7", time.Hour, now)
|
||||||
if errors.Cause(err) != ErrAuthenticationFailure {
|
if errors.Cause(err) != ErrAuthenticationFailure {
|
||||||
t.Logf("\t\tGot : %+v", err)
|
t.Logf("\t\tGot : %+v", err)
|
||||||
t.Logf("\t\tWant: %+v", ErrAuthenticationFailure)
|
t.Logf("\t\tWant: %+v", ErrAuthenticationFailure)
|
||||||
@ -117,23 +118,36 @@ func TestAuthenticate(t *testing.T) {
|
|||||||
|
|
||||||
// Create a new random account and associate that with the user.
|
// Create a new random account and associate that with the user.
|
||||||
// This defined role should be the claims.
|
// This defined role should be the claims.
|
||||||
accountId := uuid.NewRandom().String()
|
account1Id := uuid.NewRandom().String()
|
||||||
accountRole := UserAccountRole_Admin
|
account1Role := UserAccountRole_Admin
|
||||||
_, err = AddAccount(tests.Context(), auth.Claims{}, test.MasterDB, AddAccountRequest{
|
_, err = AddAccount(tests.Context(), auth.Claims{}, test.MasterDB, AddAccountRequest{
|
||||||
UserID: user.ID,
|
UserID: user.ID,
|
||||||
AccountID: accountId,
|
AccountID: account1Id,
|
||||||
Roles: []UserAccountRole{accountRole},
|
Roles: []UserAccountRole{account1Role},
|
||||||
}, now)
|
}, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Log("\t\tGot :", err)
|
t.Log("\t\tGot :", err)
|
||||||
t.Fatalf("\t%s\tAddAccount failed.", tests.Failed)
|
t.Fatalf("\t%s\tAddAccount failed.", tests.Failed)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create a second new random account and associate that with the user.
|
||||||
|
account2Id := uuid.NewRandom().String()
|
||||||
|
account2Role := UserAccountRole_User
|
||||||
|
_, err = AddAccount(tests.Context(), auth.Claims{}, test.MasterDB, AddAccountRequest{
|
||||||
|
UserID: user.ID,
|
||||||
|
AccountID: account2Id,
|
||||||
|
Roles: []UserAccountRole{account2Role},
|
||||||
|
}, now.Add(time.Second))
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tAddAccount failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
// Add 30 minutes to now to simulate time passing.
|
// Add 30 minutes to now to simulate time passing.
|
||||||
now = now.Add(time.Minute * 30)
|
now = now.Add(time.Minute * 30)
|
||||||
|
|
||||||
// Try to authenticate valid user with invalid password.
|
// Try to authenticate valid user with invalid password.
|
||||||
_, err = Authenticate(ctx, test.MasterDB, tknGen, now, user.Email, "xy7")
|
_, err = Authenticate(ctx, test.MasterDB, tknGen, user.Email, "xy7", time.Hour, now)
|
||||||
if errors.Cause(err) != ErrAuthenticationFailure {
|
if errors.Cause(err) != ErrAuthenticationFailure {
|
||||||
t.Logf("\t\tGot : %+v", err)
|
t.Logf("\t\tGot : %+v", err)
|
||||||
t.Logf("\t\tWant: %+v", ErrAuthenticationFailure)
|
t.Logf("\t\tWant: %+v", ErrAuthenticationFailure)
|
||||||
@ -142,7 +156,7 @@ func TestAuthenticate(t *testing.T) {
|
|||||||
t.Logf("\t%s\tAuthenticate user w/invalid password ok.", tests.Success)
|
t.Logf("\t%s\tAuthenticate user w/invalid password ok.", tests.Success)
|
||||||
|
|
||||||
// Verify that the user can be authenticated with the created user.
|
// Verify that the user can be authenticated with the created user.
|
||||||
tkn, err := Authenticate(ctx, test.MasterDB, tknGen, now, user.Email, initPass)
|
tkn1, err := Authenticate(ctx, test.MasterDB, tknGen, user.Email, initPass, time.Hour, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Log("\t\tGot :", err)
|
t.Log("\t\tGot :", err)
|
||||||
t.Fatalf("\t%s\tAuthenticate user failed.", tests.Failed)
|
t.Fatalf("\t%s\tAuthenticate user failed.", tests.Failed)
|
||||||
@ -150,18 +164,40 @@ func TestAuthenticate(t *testing.T) {
|
|||||||
t.Logf("\t%s\tAuthenticate user ok.", tests.Success)
|
t.Logf("\t%s\tAuthenticate user ok.", tests.Success)
|
||||||
|
|
||||||
// Ensure the token string was correctly generated.
|
// Ensure the token string was correctly generated.
|
||||||
claims, err := tknGen.ParseClaims(tkn.Token)
|
claims1, err := tknGen.ParseClaims(tkn1.Token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Log("\t\tGot :", err)
|
t.Log("\t\tGot :", err)
|
||||||
t.Fatalf("\t%s\tParse claims from token failed.", tests.Failed)
|
t.Fatalf("\t%s\tParse claims from token failed.", tests.Failed)
|
||||||
} else if diff := cmp.Diff(claims, tkn.claims); diff != "" {
|
} else if diff := cmp.Diff(claims1, tkn1.claims); diff != "" {
|
||||||
t.Fatalf("\t%s\tExpected parsed claims to match from token. Diff:\n%s", tests.Failed, diff)
|
t.Fatalf("\t%s\tExpected parsed claims to match from token. Diff:\n%s", tests.Failed, diff)
|
||||||
} else if diff := cmp.Diff(claims.Roles, []string{accountRole.String()}); diff != "" {
|
} else if diff := cmp.Diff(claims1.Roles, []string{account1Role.String()}); diff != "" {
|
||||||
t.Fatalf("\t%s\tExpected parsed claims roles to match user account. Diff:\n%s", tests.Failed, diff)
|
t.Fatalf("\t%s\tExpected parsed claims roles to match user account. Diff:\n%s", tests.Failed, diff)
|
||||||
} else if diff := cmp.Diff(claims.AccountIds, []string{accountId}); diff != "" {
|
} else if diff := cmp.Diff(claims1.AccountIds, []string{account1Id, account2Id}); diff != "" {
|
||||||
t.Fatalf("\t%s\tExpected parsed claims account IDs to match the single user account. Diff:\n%s", tests.Failed, diff)
|
t.Fatalf("\t%s\tExpected parsed claims account IDs to match the single user account. Diff:\n%s", tests.Failed, diff)
|
||||||
}
|
}
|
||||||
t.Logf("\t%s\tParse claims from token ok.", tests.Success)
|
t.Logf("\t%s\tAuthenticate parse claims from token ok.", tests.Success)
|
||||||
|
|
||||||
|
// Try switching to a second account using the first set of claims.
|
||||||
|
tkn2, err := SwitchAccount(ctx, test.MasterDB, tknGen, claims1, account2Id, time.Hour, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tSwitchAccount user failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tSwitchAccount user ok.", tests.Success)
|
||||||
|
|
||||||
|
// Ensure the token string was correctly generated.
|
||||||
|
claims2, err := tknGen.ParseClaims(tkn2.Token)
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tParse claims from token failed.", tests.Failed)
|
||||||
|
} else if diff := cmp.Diff(claims2, tkn2.claims); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tExpected parsed claims to match from token. Diff:\n%s", tests.Failed, diff)
|
||||||
|
} else if diff := cmp.Diff(claims2.Roles, []string{account2Role.String()}); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tExpected parsed claims roles to match user account. Diff:\n%s", tests.Failed, diff)
|
||||||
|
} else if diff := cmp.Diff(claims2.AccountIds, []string{account1Id, account2Id}); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tExpected parsed claims account IDs to match the single user account. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tSwitchAccount parse claims from token ok.", tests.Success)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -50,14 +50,15 @@ type UpdateUserRequest struct {
|
|||||||
Timezone *string `json:"timezone" validate:"omitempty"`
|
Timezone *string `json:"timezone" validate:"omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdatePassword defines what information may be provided to update user password.
|
// UpdatePassword defines what information is required to update a user password.
|
||||||
type UpdatePasswordRequest struct {
|
type UpdatePasswordRequest struct {
|
||||||
ID string `validate:"required,uuid"`
|
ID string `validate:"required,uuid"`
|
||||||
Password string `json:"password" validate:"required"`
|
Password string `json:"password" validate:"required"`
|
||||||
PasswordConfirm string `json:"password_confirm" validate:"omitempty,eqfield=Password"`
|
PasswordConfirm string `json:"password_confirm" validate:"omitempty,eqfield=Password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserFindRequest defines the possible options for search for users
|
// UserFindRequest defines the possible options to search for users. By default
|
||||||
|
// archived users will be excluded from response.
|
||||||
type UserFindRequest struct {
|
type UserFindRequest struct {
|
||||||
Where *string
|
Where *string
|
||||||
Args []interface{}
|
Args []interface{}
|
||||||
@ -67,9 +68,12 @@ type UserFindRequest struct {
|
|||||||
IncludedArchived bool
|
IncludedArchived bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserAccount defines the one to many relationship of an user to an account.
|
// UserAccount defines the one to many relationship of an user to an account. This
|
||||||
// Each association of an user to an account has a set of roles defined for the user
|
// will enable a single user access to multiple accounts without having duplicate
|
||||||
// that will be applied when accessing the account.
|
// users. Each association of a user to an account has a set of roles and a status
|
||||||
|
// defined for the user. The roles will be applied to enforce ACLs across the
|
||||||
|
// application. The status will allow users to be managed on by account with users
|
||||||
|
// being global to the application.
|
||||||
type UserAccount struct {
|
type UserAccount struct {
|
||||||
ID string `db:"id" json:"id"`
|
ID string `db:"id" json:"id"`
|
||||||
UserID string `db:"user_id" json:"user_id"`
|
UserID string `db:"user_id" json:"user_id"`
|
||||||
@ -81,39 +85,43 @@ type UserAccount struct {
|
|||||||
ArchivedAt pq.NullTime `db:"archived_at" json:"archived_at"`
|
ArchivedAt pq.NullTime `db:"archived_at" json:"archived_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddAccountRequest defines the information needed to add a new account to a user.
|
// AddAccountRequest defines the information is needed to associate a user to an
|
||||||
|
// account. Users are global to the application and each users access can be managed
|
||||||
|
// on an account level. If a current entry exists in the database but is archived,
|
||||||
|
// it will be un-archived.
|
||||||
type AddAccountRequest struct {
|
type AddAccountRequest struct {
|
||||||
UserID string `validate:"required,uuid"`
|
UserID string `validate:"required,uuid"`
|
||||||
AccountID string `validate:"required,uuid"`
|
AccountID string `validate:"required,uuid"`
|
||||||
Roles UserAccountRoles `json:"roles" validate:"required,dive,oneof=admin user"`
|
Roles UserAccountRoles `json:"roles" validate:"required,dive,oneof=admin user"`
|
||||||
Status *UserAccountStatus `json:"status" validate:"omitempty,oneof=active disabled"`
|
Status *UserAccountStatus `json:"status" validate:"omitempty,oneof=active invited disabled"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateAccountRequest defines the information needed to update the roles for
|
// UpdateAccountRequest defines the information needed to update the roles or the
|
||||||
// an existing user account.
|
// status for an existing user account.
|
||||||
type UpdateAccountRequest struct {
|
type UpdateAccountRequest struct {
|
||||||
UserID string `validate:"required,uuid"`
|
UserID string `validate:"required,uuid"`
|
||||||
AccountID string `validate:"required,uuid"`
|
AccountID string `validate:"required,uuid"`
|
||||||
Roles *UserAccountRoles `json:"roles" validate:"required,dive,oneof=admin user"`
|
Roles *UserAccountRoles `json:"roles" validate:"required,dive,oneof=admin user"`
|
||||||
Status *UserAccountStatus `json:"status" validate:"omitempty,oneof=active disabled"`
|
Status *UserAccountStatus `json:"status" validate:"omitempty,oneof=active invited disabled"`
|
||||||
unArchive bool
|
unArchive bool `json:"-"` // Internal use only.
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoveAccountRequest defines the information needed to remove an existing
|
// RemoveAccountRequest defines the information needed to remove an existing account
|
||||||
// account for a user. This will archive (soft-delete) the existing database entry.
|
// for a user. This will archive (soft-delete) the existing database entry.
|
||||||
type RemoveAccountRequest struct {
|
type RemoveAccountRequest struct {
|
||||||
UserID string `validate:"required,uuid"`
|
UserID string `validate:"required,uuid"`
|
||||||
AccountID string `validate:"required,uuid"`
|
AccountID string `validate:"required,uuid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAccountRequest defines the information needed to delete an existing
|
// DeleteAccountRequest defines the information needed to delete an existing account
|
||||||
// account for a user. This will hard delete the existing database entry.
|
// for a user. This will hard delete the existing database entry.
|
||||||
type DeleteAccountRequest struct {
|
type DeleteAccountRequest struct {
|
||||||
UserID string `validate:"required,uuid"`
|
UserID string `validate:"required,uuid"`
|
||||||
AccountID string `validate:"required,uuid"`
|
AccountID string `validate:"required,uuid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserAccountFindRequest defines the possible options for search for users accounts
|
// UserAccountFindRequest defines the possible options to search for users accounts.
|
||||||
|
// By default archived user accounts will be excluded from response.
|
||||||
type UserAccountFindRequest struct {
|
type UserAccountFindRequest struct {
|
||||||
Where *string
|
Where *string
|
||||||
Args []interface{}
|
Args []interface{}
|
||||||
@ -123,18 +131,25 @@ type UserAccountFindRequest struct {
|
|||||||
IncludedArchived bool
|
IncludedArchived bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserAccountStatus represents the status of a user.
|
// UserAccountStatus represents the status of a user for an account.
|
||||||
type UserAccountStatus string
|
type UserAccountStatus string
|
||||||
|
|
||||||
// UserAccountStatus values
|
// UserAccountStatus values define the status field of a user account.
|
||||||
const (
|
const (
|
||||||
|
// UserAccountStatus_Active defines the state when a user can access an account.
|
||||||
UserAccountStatus_Active UserAccountStatus = "active"
|
UserAccountStatus_Active UserAccountStatus = "active"
|
||||||
|
// UserAccountStatus_Invited defined the state when a user has been invited to an
|
||||||
|
// account.
|
||||||
|
UserAccountStatus_Invited UserAccountStatus = "invited"
|
||||||
|
// UserAccountStatus_Disabled defines the state when a user has been disabled from
|
||||||
|
// accessing an account.
|
||||||
UserAccountStatus_Disabled UserAccountStatus = "disabled"
|
UserAccountStatus_Disabled UserAccountStatus = "disabled"
|
||||||
)
|
)
|
||||||
|
|
||||||
// UserAccountStatus_Values provides list of valid UserAccountStatus values
|
// UserAccountStatus_Values provides list of valid UserAccountStatus values.
|
||||||
var UserAccountStatus_Values = []UserAccountStatus{
|
var UserAccountStatus_Values = []UserAccountStatus{
|
||||||
UserAccountStatus_Active,
|
UserAccountStatus_Active,
|
||||||
|
UserAccountStatus_Invited,
|
||||||
UserAccountStatus_Disabled,
|
UserAccountStatus_Disabled,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -152,7 +167,7 @@ func (s *UserAccountStatus) Scan(value interface{}) error {
|
|||||||
func (s UserAccountStatus) Value() (driver.Value, error) {
|
func (s UserAccountStatus) Value() (driver.Value, error) {
|
||||||
v := validator.New()
|
v := validator.New()
|
||||||
|
|
||||||
errs := v.Var(s, "required,oneof=active disabled")
|
errs := v.Var(s, "required,oneof=active invited disabled")
|
||||||
if errs != nil {
|
if errs != nil {
|
||||||
return nil, errs
|
return nil, errs
|
||||||
}
|
}
|
||||||
@ -168,13 +183,19 @@ func (s UserAccountStatus) String() string {
|
|||||||
// UserAccountRole represents the role of a user for an account.
|
// UserAccountRole represents the role of a user for an account.
|
||||||
type UserAccountRole string
|
type UserAccountRole string
|
||||||
|
|
||||||
// UserAccountRole values
|
// UserAccountRole values define the role field of a user account.
|
||||||
const (
|
const (
|
||||||
|
// UserAccountRole_Admin defines the state of a user when they have admin
|
||||||
|
// privileges for accessing an account. This role provides a user with full
|
||||||
|
// access to an account.
|
||||||
UserAccountRole_Admin UserAccountRole = auth.RoleAdmin
|
UserAccountRole_Admin UserAccountRole = auth.RoleAdmin
|
||||||
|
// UserAccountRole_User defines the state of a user when they have basic
|
||||||
|
// privileges for accessing an account. This role provies a user with the most
|
||||||
|
// limited access to an account.
|
||||||
UserAccountRole_User UserAccountRole = auth.RoleUser
|
UserAccountRole_User UserAccountRole = auth.RoleUser
|
||||||
)
|
)
|
||||||
|
|
||||||
// UserAccountRole_Values provides list of valid UserAccountRole values
|
// UserAccountRole_Values provides list of valid UserAccountRole values.
|
||||||
var UserAccountRole_Values = []UserAccountRole{
|
var UserAccountRole_Values = []UserAccountRole{
|
||||||
UserAccountRole_Admin,
|
UserAccountRole_Admin,
|
||||||
UserAccountRole_User,
|
UserAccountRole_User,
|
||||||
|
@ -335,7 +335,7 @@ func Create(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req Create
|
|||||||
// Build the insert SQL statement.
|
// Build the insert SQL statement.
|
||||||
query := sqlbuilder.NewInsertBuilder()
|
query := sqlbuilder.NewInsertBuilder()
|
||||||
query.InsertInto(usersTableName)
|
query.InsertInto(usersTableName)
|
||||||
query.Cols("id", "name", "email", "password_hash", "password_salt","timezone", "created_at", "updated_at")
|
query.Cols("id", "name", "email", "password_hash", "password_salt", "timezone", "created_at", "updated_at")
|
||||||
query.Values(u.ID, u.Name, u.Email, u.PasswordHash, u.PasswordSalt, u.Timezone, u.CreatedAt, u.UpdatedAt)
|
query.Values(u.ID, u.Name, u.Email, u.PasswordHash, u.PasswordSalt, u.Timezone, u.CreatedAt, u.UpdatedAt)
|
||||||
|
|
||||||
// Execute the query with the provided context.
|
// Execute the query with the provided context.
|
||||||
|
@ -61,7 +61,6 @@ func CanModifyUserAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// applyClaimsUserAccountSelect applies a sub query to enforce ACL for
|
// applyClaimsUserAccountSelect applies a sub query to enforce ACL for
|
||||||
// the supplied claims. If claims is empty then request must be internal and
|
// the supplied claims. If claims is empty then request must be internal and
|
||||||
// no sub-query is applied. Else a list of user IDs is found all associated
|
// no sub-query is applied. Else a list of user IDs is found all associated
|
||||||
@ -175,7 +174,7 @@ func FindAccountsByUserID(ctx context.Context, claims auth.Claims, dbConn *sqlx.
|
|||||||
// Filter base select query by ID
|
// Filter base select query by ID
|
||||||
query := sqlbuilder.NewSelectBuilder()
|
query := sqlbuilder.NewSelectBuilder()
|
||||||
query.Where(query.Equal("user_id", userID))
|
query.Where(query.Equal("user_id", userID))
|
||||||
query.OrderBy("id")
|
query.OrderBy("created_at")
|
||||||
|
|
||||||
// Execute the find accounts method.
|
// Execute the find accounts method.
|
||||||
res, err := findAccounts(ctx, claims, dbConn, query, []interface{}{}, includedArchived)
|
res, err := findAccounts(ctx, claims, dbConn, query, []interface{}{}, includedArchived)
|
||||||
|
@ -8,11 +8,11 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
||||||
|
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/tests"
|
||||||
"github.com/dgrijalva/jwt-go"
|
"github.com/dgrijalva/jwt-go"
|
||||||
|
"github.com/google/go-cmp/cmp"
|
||||||
"github.com/huandu/go-sqlbuilder"
|
"github.com/huandu/go-sqlbuilder"
|
||||||
"github.com/pborman/uuid"
|
"github.com/pborman/uuid"
|
||||||
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/tests"
|
|
||||||
"github.com/google/go-cmp/cmp"
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -127,7 +127,6 @@ func TestAddAccountValidation(t *testing.T) {
|
|||||||
invalidRole := UserAccountRole("moon")
|
invalidRole := UserAccountRole("moon")
|
||||||
invalidStatus := UserAccountStatus("moon")
|
invalidStatus := UserAccountStatus("moon")
|
||||||
|
|
||||||
|
|
||||||
var accountTests = []struct {
|
var accountTests = []struct {
|
||||||
name string
|
name string
|
||||||
req AddAccountRequest
|
req AddAccountRequest
|
||||||
@ -139,8 +138,8 @@ func TestAddAccountValidation(t *testing.T) {
|
|||||||
func(req AddAccountRequest, res *UserAccount) *UserAccount {
|
func(req AddAccountRequest, res *UserAccount) *UserAccount {
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
errors.New("Key: 'AddAccountRequest.UserID' Error:Field validation for 'UserID' failed on the 'required' tag\n"+
|
errors.New("Key: 'AddAccountRequest.UserID' Error:Field validation for 'UserID' failed on the 'required' tag\n" +
|
||||||
"Key: 'AddAccountRequest.AccountID' Error:Field validation for 'AccountID' failed on the 'required' tag\n"+
|
"Key: 'AddAccountRequest.AccountID' Error:Field validation for 'AccountID' failed on the 'required' tag\n" +
|
||||||
"Key: 'AddAccountRequest.Roles' Error:Field validation for 'Roles' failed on the 'required' tag"),
|
"Key: 'AddAccountRequest.Roles' Error:Field validation for 'Roles' failed on the 'required' tag"),
|
||||||
},
|
},
|
||||||
{"Valid Role",
|
{"Valid Role",
|
||||||
@ -506,7 +505,7 @@ func TestAccountCrud(t *testing.T) {
|
|||||||
AccountID: ua.AccountID,
|
AccountID: ua.AccountID,
|
||||||
Roles: *updateReq.Roles,
|
Roles: *updateReq.Roles,
|
||||||
Status: ua.Status,
|
Status: ua.Status,
|
||||||
CreatedAt:ua.CreatedAt,
|
CreatedAt: ua.CreatedAt,
|
||||||
UpdatedAt: now,
|
UpdatedAt: now,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@ -548,9 +547,9 @@ func TestAccountCrud(t *testing.T) {
|
|||||||
AccountID: ua.AccountID,
|
AccountID: ua.AccountID,
|
||||||
Roles: *updateReq.Roles,
|
Roles: *updateReq.Roles,
|
||||||
Status: ua.Status,
|
Status: ua.Status,
|
||||||
CreatedAt:ua.CreatedAt,
|
CreatedAt: ua.CreatedAt,
|
||||||
UpdatedAt: now,
|
UpdatedAt: now,
|
||||||
ArchivedAt: pq.NullTime{Time: now, Valid:true},
|
ArchivedAt: pq.NullTime{Time: now, Valid: true},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if diff := cmp.Diff(findRes, expected); diff != "" {
|
if diff := cmp.Diff(findRes, expected); diff != "" {
|
||||||
@ -586,23 +585,10 @@ func TestAccountCrud(t *testing.T) {
|
|||||||
// TestAccountFind validates all the request params are correctly parsed into a select query.
|
// TestAccountFind validates all the request params are correctly parsed into a select query.
|
||||||
func TestAccountFind(t *testing.T) {
|
func TestAccountFind(t *testing.T) {
|
||||||
|
|
||||||
// Ensure all the existing user accounts are deleted.
|
now := time.Now().Add(time.Hour * -2).UTC()
|
||||||
{
|
|
||||||
// Build the delete SQL statement.
|
|
||||||
query := sqlbuilder.NewDeleteBuilder()
|
|
||||||
query.DeleteFrom(usersAccountsTableName)
|
|
||||||
|
|
||||||
// Execute the query with the provided context.
|
startTime := now.Truncate(time.Millisecond)
|
||||||
sql, args := query.Build()
|
var endTime time.Time
|
||||||
sql = test.MasterDB.Rebind(sql)
|
|
||||||
_, err := test.MasterDB.ExecContext(tests.Context(), sql, args...)
|
|
||||||
if err != nil {
|
|
||||||
t.Logf("\t\tGot : %+v", err)
|
|
||||||
t.Fatalf("\t%s\tDelete failed.", tests.Failed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
|
|
||||||
|
|
||||||
var userAccounts []*UserAccount
|
var userAccounts []*UserAccount
|
||||||
for i := 0; i <= 4; i++ {
|
for i := 0; i <= 4; i++ {
|
||||||
@ -630,6 +616,7 @@ func TestAccountFind(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
userAccounts = append(userAccounts, ua)
|
userAccounts = append(userAccounts, ua)
|
||||||
|
endTime = user.CreatedAt
|
||||||
}
|
}
|
||||||
|
|
||||||
type accountTest struct {
|
type accountTest struct {
|
||||||
@ -641,9 +628,13 @@ func TestAccountFind(t *testing.T) {
|
|||||||
|
|
||||||
var accountTests []accountTest
|
var accountTests []accountTest
|
||||||
|
|
||||||
|
createdFilter := "created_at BETWEEN ? AND ?"
|
||||||
|
|
||||||
// Test sort users.
|
// Test sort users.
|
||||||
accountTests = append(accountTests, accountTest{"Find all order by created_at asx",
|
accountTests = append(accountTests, accountTest{"Find all order by created_at asx",
|
||||||
UserAccountFindRequest{
|
UserAccountFindRequest{
|
||||||
|
Where: &createdFilter,
|
||||||
|
Args: []interface{}{startTime, endTime},
|
||||||
Order: []string{"created_at"},
|
Order: []string{"created_at"},
|
||||||
},
|
},
|
||||||
userAccounts,
|
userAccounts,
|
||||||
@ -657,6 +648,8 @@ func TestAccountFind(t *testing.T) {
|
|||||||
}
|
}
|
||||||
accountTests = append(accountTests, accountTest{"Find all order by created_at desc",
|
accountTests = append(accountTests, accountTest{"Find all order by created_at desc",
|
||||||
UserAccountFindRequest{
|
UserAccountFindRequest{
|
||||||
|
Where: &createdFilter,
|
||||||
|
Args: []interface{}{startTime, endTime},
|
||||||
Order: []string{"created_at desc"},
|
Order: []string{"created_at desc"},
|
||||||
},
|
},
|
||||||
expected,
|
expected,
|
||||||
@ -667,6 +660,8 @@ func TestAccountFind(t *testing.T) {
|
|||||||
var limit uint = 2
|
var limit uint = 2
|
||||||
accountTests = append(accountTests, accountTest{"Find limit",
|
accountTests = append(accountTests, accountTest{"Find limit",
|
||||||
UserAccountFindRequest{
|
UserAccountFindRequest{
|
||||||
|
Where: &createdFilter,
|
||||||
|
Args: []interface{}{startTime, endTime},
|
||||||
Order: []string{"created_at"},
|
Order: []string{"created_at"},
|
||||||
Limit: &limit,
|
Limit: &limit,
|
||||||
},
|
},
|
||||||
@ -678,6 +673,8 @@ func TestAccountFind(t *testing.T) {
|
|||||||
var offset uint = 3
|
var offset uint = 3
|
||||||
accountTests = append(accountTests, accountTest{"Find limit, offset",
|
accountTests = append(accountTests, accountTest{"Find limit, offset",
|
||||||
UserAccountFindRequest{
|
UserAccountFindRequest{
|
||||||
|
Where: &createdFilter,
|
||||||
|
Args: []interface{}{startTime, endTime},
|
||||||
Order: []string{"created_at"},
|
Order: []string{"created_at"},
|
||||||
Limit: &limit,
|
Limit: &limit,
|
||||||
Offset: &offset,
|
Offset: &offset,
|
||||||
@ -688,27 +685,24 @@ func TestAccountFind(t *testing.T) {
|
|||||||
|
|
||||||
// Test where filter.
|
// Test where filter.
|
||||||
whereParts := []string{}
|
whereParts := []string{}
|
||||||
whereArgs := []interface{}{}
|
whereArgs := []interface{}{startTime, endTime}
|
||||||
expected = []*UserAccount{}
|
expected = []*UserAccount{}
|
||||||
selected := make(map[string]bool)
|
for i := 0; i <= len(userAccounts); i++ {
|
||||||
for i := 0; i <= 2; i++ {
|
if rand.Intn(100) < 50 {
|
||||||
ranIdx := rand.Intn(len(userAccounts))
|
|
||||||
|
|
||||||
id := userAccounts[ranIdx].ID
|
|
||||||
if selected[id] {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
selected[id] = true
|
ua := *userAccounts[i]
|
||||||
|
|
||||||
whereParts = append(whereParts, "id = ?")
|
whereParts = append(whereParts, "id = ?")
|
||||||
whereArgs = append(whereArgs, id)
|
whereArgs = append(whereArgs, ua.ID)
|
||||||
expected = append(expected, userAccounts[ranIdx])
|
expected = append(expected, &ua)
|
||||||
}
|
}
|
||||||
where := strings.Join(whereParts, " OR ")
|
where := createdFilter + " AND (" + strings.Join(whereParts, " OR ") + ")"
|
||||||
accountTests = append(accountTests, accountTest{"Find where",
|
accountTests = append(accountTests, accountTest{"Find where",
|
||||||
UserAccountFindRequest{
|
UserAccountFindRequest{
|
||||||
Where: &where,
|
Where: &where,
|
||||||
Args: whereArgs,
|
Args: whereArgs,
|
||||||
|
Order: []string{"created_at"},
|
||||||
},
|
},
|
||||||
expected,
|
expected,
|
||||||
nil,
|
nil,
|
||||||
|
@ -137,7 +137,6 @@ func TestApplyClaimsUserSelect(t *testing.T) {
|
|||||||
// TestCreateUser ensures all the validation tags work on Create
|
// TestCreateUser ensures all the validation tags work on Create
|
||||||
func TestCreateUserValidation(t *testing.T) {
|
func TestCreateUserValidation(t *testing.T) {
|
||||||
|
|
||||||
|
|
||||||
var userTests = []struct {
|
var userTests = []struct {
|
||||||
name string
|
name string
|
||||||
req CreateUserRequest
|
req CreateUserRequest
|
||||||
@ -495,7 +494,7 @@ func TestUpdateUserPassword(t *testing.T) {
|
|||||||
|
|
||||||
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
|
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
var tknGen mockTokenGenerator
|
tknGen := &mockTokenGenerator{}
|
||||||
|
|
||||||
// Create a new user for testing.
|
// Create a new user for testing.
|
||||||
initPass := uuid.NewRandom().String()
|
initPass := uuid.NewRandom().String()
|
||||||
@ -523,7 +522,7 @@ func TestUpdateUserPassword(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Verify that the user can be authenticated with the created user.
|
// Verify that the user can be authenticated with the created user.
|
||||||
_, err = Authenticate(ctx, test.MasterDB, tknGen, now, user.Email, initPass)
|
_, err = Authenticate(ctx, test.MasterDB, tknGen, user.Email, initPass, time.Hour, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Log("\t\tGot :", err)
|
t.Log("\t\tGot :", err)
|
||||||
t.Fatalf("\t%s\tAuthenticate failed.", tests.Failed)
|
t.Fatalf("\t%s\tAuthenticate failed.", tests.Failed)
|
||||||
@ -557,7 +556,7 @@ func TestUpdateUserPassword(t *testing.T) {
|
|||||||
t.Logf("\t%s\tUpdatePassword ok.", tests.Success)
|
t.Logf("\t%s\tUpdatePassword ok.", tests.Success)
|
||||||
|
|
||||||
// Verify that the user can be authenticated with the updated password.
|
// Verify that the user can be authenticated with the updated password.
|
||||||
_, err = Authenticate(ctx, test.MasterDB, tknGen, now, user.Email, newPass)
|
_, err = Authenticate(ctx, test.MasterDB, tknGen, user.Email, newPass, time.Hour, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Log("\t\tGot :", err)
|
t.Log("\t\tGot :", err)
|
||||||
t.Fatalf("\t%s\tAuthenticate failed.", tests.Failed)
|
t.Fatalf("\t%s\tAuthenticate failed.", tests.Failed)
|
||||||
@ -868,23 +867,10 @@ func TestUserCrud(t *testing.T) {
|
|||||||
// TestUserFind validates all the request params are correctly parsed into a select query.
|
// TestUserFind validates all the request params are correctly parsed into a select query.
|
||||||
func TestUserFind(t *testing.T) {
|
func TestUserFind(t *testing.T) {
|
||||||
|
|
||||||
// Ensure all the existing users are deleted.
|
now := time.Now().Add(time.Hour * -1).UTC()
|
||||||
{
|
|
||||||
// Build the delete SQL statement.
|
|
||||||
query := sqlbuilder.NewDeleteBuilder()
|
|
||||||
query.DeleteFrom(usersTableName)
|
|
||||||
|
|
||||||
// Execute the query with the provided context.
|
startTime := now.Truncate(time.Millisecond)
|
||||||
sql, args := query.Build()
|
var endTime time.Time
|
||||||
sql = test.MasterDB.Rebind(sql)
|
|
||||||
_, err := test.MasterDB.ExecContext(tests.Context(), sql, args...)
|
|
||||||
if err != nil {
|
|
||||||
t.Logf("\t\tGot : %+v", err)
|
|
||||||
t.Fatalf("\t%s\tDelete failed.", tests.Failed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
|
|
||||||
|
|
||||||
var users []*User
|
var users []*User
|
||||||
for i := 0; i <= 4; i++ {
|
for i := 0; i <= 4; i++ {
|
||||||
@ -899,6 +885,7 @@ func TestUserFind(t *testing.T) {
|
|||||||
t.Fatalf("\t%s\tCreate failed.", tests.Failed)
|
t.Fatalf("\t%s\tCreate failed.", tests.Failed)
|
||||||
}
|
}
|
||||||
users = append(users, user)
|
users = append(users, user)
|
||||||
|
endTime = user.CreatedAt
|
||||||
}
|
}
|
||||||
|
|
||||||
type userTest struct {
|
type userTest struct {
|
||||||
@ -910,9 +897,13 @@ func TestUserFind(t *testing.T) {
|
|||||||
|
|
||||||
var userTests []userTest
|
var userTests []userTest
|
||||||
|
|
||||||
|
createdFilter := "created_at BETWEEN ? AND ?"
|
||||||
|
|
||||||
// Test sort users.
|
// Test sort users.
|
||||||
userTests = append(userTests, userTest{"Find all order by created_at asx",
|
userTests = append(userTests, userTest{"Find all order by created_at asc",
|
||||||
UserFindRequest{
|
UserFindRequest{
|
||||||
|
Where: &createdFilter,
|
||||||
|
Args: []interface{}{startTime, endTime},
|
||||||
Order: []string{"created_at"},
|
Order: []string{"created_at"},
|
||||||
},
|
},
|
||||||
users,
|
users,
|
||||||
@ -926,6 +917,8 @@ func TestUserFind(t *testing.T) {
|
|||||||
}
|
}
|
||||||
userTests = append(userTests, userTest{"Find all order by created_at desc",
|
userTests = append(userTests, userTest{"Find all order by created_at desc",
|
||||||
UserFindRequest{
|
UserFindRequest{
|
||||||
|
Where: &createdFilter,
|
||||||
|
Args: []interface{}{startTime, endTime},
|
||||||
Order: []string{"created_at desc"},
|
Order: []string{"created_at desc"},
|
||||||
},
|
},
|
||||||
expected,
|
expected,
|
||||||
@ -936,6 +929,8 @@ func TestUserFind(t *testing.T) {
|
|||||||
var limit uint = 2
|
var limit uint = 2
|
||||||
userTests = append(userTests, userTest{"Find limit",
|
userTests = append(userTests, userTest{"Find limit",
|
||||||
UserFindRequest{
|
UserFindRequest{
|
||||||
|
Where: &createdFilter,
|
||||||
|
Args: []interface{}{startTime, endTime},
|
||||||
Order: []string{"created_at"},
|
Order: []string{"created_at"},
|
||||||
Limit: &limit,
|
Limit: &limit,
|
||||||
},
|
},
|
||||||
@ -947,6 +942,8 @@ func TestUserFind(t *testing.T) {
|
|||||||
var offset uint = 3
|
var offset uint = 3
|
||||||
userTests = append(userTests, userTest{"Find limit, offset",
|
userTests = append(userTests, userTest{"Find limit, offset",
|
||||||
UserFindRequest{
|
UserFindRequest{
|
||||||
|
Where: &createdFilter,
|
||||||
|
Args: []interface{}{startTime, endTime},
|
||||||
Order: []string{"created_at"},
|
Order: []string{"created_at"},
|
||||||
Limit: &limit,
|
Limit: &limit,
|
||||||
Offset: &offset,
|
Offset: &offset,
|
||||||
@ -957,27 +954,25 @@ func TestUserFind(t *testing.T) {
|
|||||||
|
|
||||||
// Test where filter.
|
// Test where filter.
|
||||||
whereParts := []string{}
|
whereParts := []string{}
|
||||||
whereArgs := []interface{}{}
|
whereArgs := []interface{}{startTime, endTime}
|
||||||
expected = []*User{}
|
expected = []*User{}
|
||||||
selected := make(map[string]bool)
|
for i := 0; i <= len(users); i++ {
|
||||||
for i := 0; i <= 2; i++ {
|
if rand.Intn(100) < 50 {
|
||||||
ranIdx := rand.Intn(len(users))
|
|
||||||
|
|
||||||
email := users[ranIdx].Email
|
|
||||||
if selected[email] {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
selected[email] = true
|
u := *users[i]
|
||||||
|
|
||||||
whereParts = append(whereParts, "email = ?")
|
whereParts = append(whereParts, "email = ?")
|
||||||
whereArgs = append(whereArgs, email)
|
whereArgs = append(whereArgs, u.Email)
|
||||||
expected = append(expected, users[ranIdx])
|
expected = append(expected, &u)
|
||||||
}
|
}
|
||||||
where := strings.Join(whereParts, " OR ")
|
|
||||||
|
where := createdFilter + " AND (" + strings.Join(whereParts, " OR ") + ")"
|
||||||
userTests = append(userTests, userTest{"Find where",
|
userTests = append(userTests, userTest{"Find where",
|
||||||
UserFindRequest{
|
UserFindRequest{
|
||||||
Where: &where,
|
Where: &where,
|
||||||
Args: whereArgs,
|
Args: whereArgs,
|
||||||
|
Order: []string{"created_at"},
|
||||||
},
|
},
|
||||||
expected,
|
expected,
|
||||||
nil,
|
nil,
|
||||||
@ -998,6 +993,14 @@ func TestUserFind(t *testing.T) {
|
|||||||
} else if diff := cmp.Diff(res, tt.expected); diff != "" {
|
} else if diff := cmp.Diff(res, tt.expected); diff != "" {
|
||||||
t.Logf("\t\tGot: %d items", len(res))
|
t.Logf("\t\tGot: %d items", len(res))
|
||||||
t.Logf("\t\tWant: %d items", len(tt.expected))
|
t.Logf("\t\tWant: %d items", len(tt.expected))
|
||||||
|
|
||||||
|
for _, u := range res {
|
||||||
|
t.Logf("\t\tGot: %s ID", u.ID)
|
||||||
|
}
|
||||||
|
for _, u := range tt.expected {
|
||||||
|
t.Logf("\t\tExpected: %s ID", u.ID)
|
||||||
|
}
|
||||||
|
|
||||||
t.Fatalf("\t%s\tExpected find result to match expected. Diff:\n%s", tests.Failed, diff)
|
t.Fatalf("\t%s\tExpected find result to match expected. Diff:\n%s", tests.Failed, diff)
|
||||||
}
|
}
|
||||||
t.Logf("\t%s\tFind ok.", tests.Success)
|
t.Logf("\t%s\tFind ok.", tests.Success)
|
||||||
|
Reference in New Issue
Block a user