You've already forked golang-saas-starter-kit
mirror of
https://github.com/raseels-repos/golang-saas-starter-kit.git
synced 2025-08-10 22:41:25 +02:00
completed user_account_test
This commit is contained in:
@@ -10,8 +10,8 @@ import (
|
|||||||
|
|
||||||
// These are the expected values for Claims.Roles.
|
// These are the expected values for Claims.Roles.
|
||||||
const (
|
const (
|
||||||
RoleAdmin = "ADMIN"
|
RoleAdmin = "admin"
|
||||||
RoleUser = "USER"
|
RoleUser = "user"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ctxKey represents the type of value for the context key.
|
// ctxKey represents the type of value for the context key.
|
||||||
|
@@ -18,19 +18,13 @@ func migrationList(db *sqlx.DB, log *log.Logger) []*sqlxmigrate.Migration {
|
|||||||
{
|
{
|
||||||
ID: "20190522-01a",
|
ID: "20190522-01a",
|
||||||
Migrate: func(tx *sql.Tx) error {
|
Migrate: func(tx *sql.Tx) error {
|
||||||
q1 := `CREATE TYPE user_status_t as enum('active','disabled')`
|
q1 := `CREATE TABLE IF NOT EXISTS users (
|
||||||
if _, err := tx.Exec(q1); err != nil {
|
|
||||||
return errors.WithMessagef(err, "Query failed %s", q1)
|
|
||||||
}
|
|
||||||
|
|
||||||
q2 := `CREATE TABLE IF NOT EXISTS users (
|
|
||||||
id char(36) NOT NULL,
|
id char(36) NOT NULL,
|
||||||
email varchar(200) NOT NULL,
|
email varchar(200) NOT NULL,
|
||||||
name varchar(200) NOT NULL DEFAULT '',
|
name varchar(200) NOT NULL DEFAULT '',
|
||||||
password_hash varchar(256) NOT NULL,
|
password_hash varchar(256) NOT NULL,
|
||||||
password_salt varchar(36) NOT NULL,
|
password_salt varchar(36) NOT NULL,
|
||||||
password_reset varchar(36) DEFAULT NULL,
|
password_reset varchar(36) DEFAULT NULL,
|
||||||
status user_status_t NOT NULL DEFAULT 'active',
|
|
||||||
timezone varchar(128) NOT NULL DEFAULT 'America/Anchorage',
|
timezone varchar(128) NOT NULL DEFAULT 'America/Anchorage',
|
||||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,
|
||||||
@@ -38,21 +32,16 @@ func migrationList(db *sqlx.DB, log *log.Logger) []*sqlxmigrate.Migration {
|
|||||||
PRIMARY KEY (id),
|
PRIMARY KEY (id),
|
||||||
CONSTRAINT email UNIQUE (email)
|
CONSTRAINT email UNIQUE (email)
|
||||||
) ;`
|
) ;`
|
||||||
if _, err := tx.Exec(q2); err != nil {
|
if _, err := tx.Exec(q1); err != nil {
|
||||||
return errors.WithMessagef(err, "Query failed %s", q2)
|
return errors.WithMessagef(err, "Query failed %s", q1)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
Rollback: func(tx *sql.Tx) error {
|
Rollback: func(tx *sql.Tx) error {
|
||||||
q1 := `DROP TYPE user_status_t`
|
q1 := `DROP TABLE IF EXISTS users`
|
||||||
if _, err := tx.Exec(q1); err != nil {
|
if _, err := tx.Exec(q1); err != nil {
|
||||||
return errors.WithMessagef(err, "Query failed %s", q1)
|
return errors.WithMessagef(err, "Query failed %s", q1)
|
||||||
}
|
}
|
||||||
|
|
||||||
q2 := `DROP TABLE IF EXISTS users`
|
|
||||||
if _, err := tx.Exec(q2); err != nil {
|
|
||||||
return errors.WithMessagef(err, "Query failed %s", q2)
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -106,24 +95,30 @@ func migrationList(db *sqlx.DB, log *log.Logger) []*sqlxmigrate.Migration {
|
|||||||
{
|
{
|
||||||
ID: "20190522-01c",
|
ID: "20190522-01c",
|
||||||
Migrate: func(tx *sql.Tx) error {
|
Migrate: func(tx *sql.Tx) error {
|
||||||
q1 := `CREATE TYPE user_account_role_t as enum('ADMIN', 'USER')`
|
q1 := `CREATE TYPE user_account_role_t as enum('admin', 'user')`
|
||||||
if _, err := tx.Exec(q1); err != nil {
|
if _, err := tx.Exec(q1); err != nil {
|
||||||
return errors.WithMessagef(err, "Query failed %s", q1)
|
return errors.WithMessagef(err, "Query failed %s", q1)
|
||||||
}
|
}
|
||||||
|
|
||||||
q2 := `CREATE TABLE IF NOT EXISTS users_accounts (
|
q2 := `CREATE TYPE user_account_status_t as enum('active','disabled')`
|
||||||
|
if _, err := tx.Exec(q2); err != nil {
|
||||||
|
return errors.WithMessagef(err, "Query failed %s", q2)
|
||||||
|
}
|
||||||
|
|
||||||
|
q3 := `CREATE TABLE IF NOT EXISTS users_accounts (
|
||||||
id char(36) NOT NULL,
|
id char(36) NOT NULL,
|
||||||
account_id char(36) NOT NULL,
|
account_id char(36) NOT NULL,
|
||||||
user_id char(36) NOT NULL,
|
user_id char(36) NOT NULL,
|
||||||
roles user_account_role_t[] NOT NULL,
|
roles user_account_role_t[] NOT NULL,
|
||||||
|
status user_account_status_t NOT NULL DEFAULT 'active',
|
||||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,
|
||||||
archived_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,
|
archived_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,
|
||||||
PRIMARY KEY (id),
|
PRIMARY KEY (id),
|
||||||
CONSTRAINT user_account UNIQUE (user_id,account_id)
|
CONSTRAINT user_account UNIQUE (user_id,account_id)
|
||||||
)`
|
)`
|
||||||
if _, err := tx.Exec(q2); err != nil {
|
if _, err := tx.Exec(q3); err != nil {
|
||||||
return errors.WithMessagef(err, "Query failed %s", q2)
|
return errors.WithMessagef(err, "Query failed %s", q3)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -134,11 +129,16 @@ 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 := `DROP TABLE IF EXISTS users_accounts`
|
q2 := `DROP TYPE userr_account_status_t`
|
||||||
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
q3 := `DROP TABLE IF EXISTS users_accounts`
|
||||||
|
if _, err := tx.Exec(q3); err != nil {
|
||||||
|
return errors.WithMessagef(err, "Query failed %s", q3)
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
167
example-project/internal/user/auth_test.go
Normal file
167
example-project/internal/user/auth_test.go
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rsa"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"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/google/go-cmp/cmp"
|
||||||
|
"github.com/pborman/uuid"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mockTokenGenerator is used for testing that Authenticate calls its provided
|
||||||
|
// token generator in a specific way.
|
||||||
|
type mockTokenGenerator struct{}
|
||||||
|
|
||||||
|
// Private key generated by GenerateToken that is need for ParseClaims
|
||||||
|
var mockTokenKey *rsa.PrivateKey
|
||||||
|
|
||||||
|
// GenerateToken implements the TokenGenerator interface. It returns a "token"
|
||||||
|
// that includes some information about the claims it was passed.
|
||||||
|
func (g mockTokenGenerator) GenerateToken(claims auth.Claims) (string, error) {
|
||||||
|
privateKey, err := auth.Keygen()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
mockTokenKey, err = jwt.ParseRSAPrivateKeyFromPEM(privateKey)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
algorithm := "RS256"
|
||||||
|
method := jwt.GetSigningMethod(algorithm)
|
||||||
|
|
||||||
|
tkn := jwt.NewWithClaims(method, claims)
|
||||||
|
tkn.Header["kid"] = "1"
|
||||||
|
|
||||||
|
str, err := tkn.SignedString(mockTokenKey)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return str, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseClaims recreates the Claims that were used to generate a token. It
|
||||||
|
// verifies that the token was signed using our key.
|
||||||
|
func (g mockTokenGenerator) ParseClaims(tknStr string) (auth.Claims, error) {
|
||||||
|
algorithm := "RS256"
|
||||||
|
parser := jwt.Parser{
|
||||||
|
ValidMethods: []string{algorithm},
|
||||||
|
}
|
||||||
|
|
||||||
|
if mockTokenKey == nil {
|
||||||
|
panic("key is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
f := func(t *jwt.Token) (interface{}, error) {
|
||||||
|
return mockTokenKey.Public().(*rsa.PublicKey), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var claims auth.Claims
|
||||||
|
tkn, err := parser.ParseWithClaims(tknStr, &claims, f)
|
||||||
|
if err != nil {
|
||||||
|
return auth.Claims{}, errors.Wrap(err, "parsing token")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !tkn.Valid {
|
||||||
|
return auth.Claims{}, errors.New("Invalid token")
|
||||||
|
}
|
||||||
|
|
||||||
|
return claims, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAuthenticate validates the behavior around authenticating users.
|
||||||
|
func TestAuthenticate(t *testing.T) {
|
||||||
|
defer tests.Recover(t)
|
||||||
|
|
||||||
|
t.Log("Given the need to authenticate users")
|
||||||
|
{
|
||||||
|
t.Log("\tWhen handling a single User.")
|
||||||
|
{
|
||||||
|
ctx := tests.Context()
|
||||||
|
|
||||||
|
tknGen := &mockTokenGenerator{}
|
||||||
|
|
||||||
|
// Auth tokens are valid for an our and is verified against current time.
|
||||||
|
// Issue the token one hour ago.
|
||||||
|
now := time.Now().Add(time.Hour * -1)
|
||||||
|
|
||||||
|
// Try to authenticate an invalid user.
|
||||||
|
_, err := Authenticate(ctx, test.MasterDB, tknGen, now, "doesnotexist@gmail.com", "xy7")
|
||||||
|
if errors.Cause(err) != ErrAuthenticationFailure {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", ErrAuthenticationFailure)
|
||||||
|
t.Fatalf("\t%s\tAuthenticate non existant user failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tAuthenticate non existant user ok.", tests.Success)
|
||||||
|
|
||||||
|
// Create a new user for testing.
|
||||||
|
initPass := uuid.NewRandom().String()
|
||||||
|
user, err := Create(ctx, auth.Claims{}, test.MasterDB, CreateUserRequest{
|
||||||
|
Name: "Lee Brown",
|
||||||
|
Email: uuid.NewRandom().String() + "@geeksinthewoods.com",
|
||||||
|
Password: initPass,
|
||||||
|
PasswordConfirm: initPass,
|
||||||
|
}, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tCreate user failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tCreate user ok.", tests.Success)
|
||||||
|
|
||||||
|
// Create a new random account and associate that with the user.
|
||||||
|
// This defined role should be the claims.
|
||||||
|
accountId := uuid.NewRandom().String()
|
||||||
|
accountRole := UserAccountRole_Admin
|
||||||
|
_, err = AddAccount(tests.Context(), auth.Claims{}, test.MasterDB, AddAccountRequest{
|
||||||
|
UserID: user.ID,
|
||||||
|
AccountID: accountId,
|
||||||
|
Roles: []UserAccountRole{accountRole},
|
||||||
|
}, now)
|
||||||
|
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.
|
||||||
|
now = now.Add(time.Minute * 30)
|
||||||
|
|
||||||
|
// Try to authenticate valid user with invalid password.
|
||||||
|
_, err = Authenticate(ctx, test.MasterDB, tknGen, now, user.Email, "xy7")
|
||||||
|
if errors.Cause(err) != ErrAuthenticationFailure {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", ErrAuthenticationFailure)
|
||||||
|
t.Fatalf("\t%s\tAuthenticate user w/invalid password failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tAuthenticate user w/invalid password ok.", tests.Success)
|
||||||
|
|
||||||
|
// Verify that the user can be authenticated with the created user.
|
||||||
|
tkn, err := Authenticate(ctx, test.MasterDB, tknGen, now, user.Email, initPass)
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tAuthenticate user failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tAuthenticate user ok.", tests.Success)
|
||||||
|
|
||||||
|
// Ensure the token string was correctly generated.
|
||||||
|
claims, err := tknGen.ParseClaims(tkn.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(claims, tkn.claims); 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 != "" {
|
||||||
|
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 != "" {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -21,7 +21,6 @@ type User struct {
|
|||||||
PasswordHash []byte `db:"password_hash" json:"-"`
|
PasswordHash []byte `db:"password_hash" json:"-"`
|
||||||
PasswordReset sql.NullString `db:"password_reset" json:"-"`
|
PasswordReset sql.NullString `db:"password_reset" json:"-"`
|
||||||
|
|
||||||
Status UserStatus `db:"status" json:"status"`
|
|
||||||
Timezone string `db:"timezone" json:"timezone"`
|
Timezone string `db:"timezone" json:"timezone"`
|
||||||
|
|
||||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||||
@@ -35,7 +34,6 @@ type CreateUserRequest struct {
|
|||||||
Email string `json:"email" validate:"required,email,unique"`
|
Email string `json:"email" validate:"required,email,unique"`
|
||||||
Password string `json:"password" validate:"required"`
|
Password string `json:"password" validate:"required"`
|
||||||
PasswordConfirm string `json:"password_confirm" validate:"eqfield=Password"`
|
PasswordConfirm string `json:"password_confirm" validate:"eqfield=Password"`
|
||||||
Status *UserStatus `json:"status" validate:"omitempty,oneof=active disabled"`
|
|
||||||
Timezone *string `json:"timezone" validate:"omitempty"`
|
Timezone *string `json:"timezone" validate:"omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,7 +47,6 @@ type UpdateUserRequest struct {
|
|||||||
ID string `validate:"required,uuid"`
|
ID string `validate:"required,uuid"`
|
||||||
Name *string `json:"name" validate:"omitempty"`
|
Name *string `json:"name" validate:"omitempty"`
|
||||||
Email *string `json:"email" validate:"omitempty,email,unique"`
|
Email *string `json:"email" validate:"omitempty,email,unique"`
|
||||||
Status *UserStatus `json:"status" validate:"omitempty,oneof=active disabled"`
|
|
||||||
Timezone *string `json:"timezone" validate:"omitempty"`
|
Timezone *string `json:"timezone" validate:"omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,6 +75,7 @@ type UserAccount struct {
|
|||||||
UserID string `db:"user_id" json:"user_id"`
|
UserID string `db:"user_id" json:"user_id"`
|
||||||
AccountID string `db:"account_id" json:"account_id"`
|
AccountID string `db:"account_id" json:"account_id"`
|
||||||
Roles UserAccountRoles `db:"roles" json:"roles"`
|
Roles UserAccountRoles `db:"roles" json:"roles"`
|
||||||
|
Status UserAccountStatus `db:"status" json:"status"`
|
||||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||||
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||||
ArchivedAt pq.NullTime `db:"archived_at" json:"archived_at"`
|
ArchivedAt pq.NullTime `db:"archived_at" json:"archived_at"`
|
||||||
@@ -87,7 +85,8 @@ type UserAccount struct {
|
|||||||
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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateAccountRequest defines the information needed to update the roles for
|
// UpdateAccountRequest defines the information needed to update the roles for
|
||||||
@@ -95,7 +94,8 @@ type AddAccountRequest struct {
|
|||||||
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:"oneof=ADMIN USER"`
|
Roles *UserAccountRoles `json:"roles" validate:"required,dive,oneof=admin user"`
|
||||||
|
Status *UserAccountStatus `json:"status" validate:"omitempty,oneof=active disabled"`
|
||||||
unArchive bool
|
unArchive bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,33 +123,33 @@ type UserAccountFindRequest struct {
|
|||||||
IncludedArchived bool
|
IncludedArchived bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserStatus represents the status of a user.
|
// UserAccountStatus represents the status of a user.
|
||||||
type UserStatus string
|
type UserAccountStatus string
|
||||||
|
|
||||||
// UserStatus values
|
// UserAccountStatus values
|
||||||
const (
|
const (
|
||||||
UserStatus_Active UserStatus = "active"
|
UserAccountStatus_Active UserAccountStatus = "active"
|
||||||
UserStatus_Disabled UserStatus = "disabled"
|
UserAccountStatus_Disabled UserAccountStatus = "disabled"
|
||||||
)
|
)
|
||||||
|
|
||||||
// UserStatus_Values provides list of valid UserStatus values
|
// UserAccountStatus_Values provides list of valid UserAccountStatus values
|
||||||
var UserStatus_Values = []UserStatus{
|
var UserAccountStatus_Values = []UserAccountStatus{
|
||||||
UserStatus_Active,
|
UserAccountStatus_Active,
|
||||||
UserStatus_Disabled,
|
UserAccountStatus_Disabled,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scan supports reading the UserStatus value from the database.
|
// Scan supports reading the UserAccountStatus value from the database.
|
||||||
func (s *UserStatus) Scan(value interface{}) error {
|
func (s *UserAccountStatus) Scan(value interface{}) error {
|
||||||
asBytes, ok := value.([]byte)
|
asBytes, ok := value.([]byte)
|
||||||
if !ok {
|
if !ok {
|
||||||
return errors.New("Scan source is not []byte")
|
return errors.New("Scan source is not []byte")
|
||||||
}
|
}
|
||||||
*s = UserStatus(string(asBytes))
|
*s = UserAccountStatus(string(asBytes))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Value converts the UserStatus value to be stored in the database.
|
// Value converts the UserAccountStatus value to be stored in the database.
|
||||||
func (s UserStatus) 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 disabled")
|
||||||
@@ -160,8 +160,8 @@ func (s UserStatus) Value() (driver.Value, error) {
|
|||||||
return string(s), nil
|
return string(s), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// String converts the UserStatus value to a string.
|
// String converts the UserAccountStatus value to a string.
|
||||||
func (s UserStatus) String() string {
|
func (s UserAccountStatus) String() string {
|
||||||
return string(s)
|
return string(s)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,7 +208,7 @@ func (s UserAccountRoles) Value() (driver.Value, error) {
|
|||||||
|
|
||||||
var arr pq.StringArray
|
var arr pq.StringArray
|
||||||
for _, r := range s {
|
for _, r := range s {
|
||||||
errs := v.Var(r, "required,oneof=ADMIN USER")
|
errs := v.Var(r, "required,oneof=admin user")
|
||||||
if errs != nil {
|
if errs != nil {
|
||||||
return nil, errs
|
return nil, errs
|
||||||
}
|
}
|
||||||
|
@@ -3,7 +3,6 @@ package user
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
||||||
@@ -35,7 +34,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// usersMapColumns is the list of columns needed for mapRowsToUser
|
// usersMapColumns is the list of columns needed for mapRowsToUser
|
||||||
var usersMapColumns = "id,name,email,password_salt,password_hash,password_reset,status,timezone,created_at,updated_at,archived_at"
|
var usersMapColumns = "id,name,email,password_salt,password_hash,password_reset,timezone,created_at,updated_at,archived_at"
|
||||||
|
|
||||||
// mapRowsToUser takes the SQL rows and maps it to the UserAccount struct
|
// mapRowsToUser takes the SQL rows and maps it to the UserAccount struct
|
||||||
// with the columns defined by usersMapColumns
|
// with the columns defined by usersMapColumns
|
||||||
@@ -44,7 +43,7 @@ func mapRowsToUser(rows *sql.Rows) (*User, error) {
|
|||||||
u User
|
u User
|
||||||
err error
|
err error
|
||||||
)
|
)
|
||||||
err = rows.Scan(&u.ID, &u.Name, &u.Email, &u.PasswordSalt, &u.PasswordHash, &u.PasswordReset, &u.Status, &u.Timezone, &u.CreatedAt, &u.UpdatedAt, &u.ArchivedAt)
|
err = rows.Scan(&u.ID, &u.Name, &u.Email, &u.PasswordSalt, &u.PasswordHash, &u.PasswordReset, &u.Timezone, &u.CreatedAt, &u.UpdatedAt, &u.ArchivedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithStack(err)
|
return nil, errors.WithStack(err)
|
||||||
}
|
}
|
||||||
@@ -52,8 +51,8 @@ func mapRowsToUser(rows *sql.Rows) (*User, error) {
|
|||||||
return &u, nil
|
return &u, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CanReadUserId determines if claims has the authority to access the specified user ID.
|
// CanReadUser determines if claims has the authority to access the specified user ID.
|
||||||
func CanReadUserId(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userID string) error {
|
func CanReadUser(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userID string) error {
|
||||||
// If the request has claims from a specific user, ensure that the user
|
// If the request has claims from a specific user, ensure that the user
|
||||||
// has the correct access to the user.
|
// has the correct access to the user.
|
||||||
if claims.Subject != "" {
|
if claims.Subject != "" {
|
||||||
@@ -86,10 +85,10 @@ func CanReadUserId(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, use
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CanModifyUserId determines if claims has the authority to modify the specified user ID.
|
// CanModifyUser determines if claims has the authority to modify the specified user ID.
|
||||||
func CanModifyUserId(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userID string) error {
|
func CanModifyUser(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userID string) error {
|
||||||
// First check to see if claims can read the user ID
|
// First check to see if claims can read the user ID
|
||||||
err := CanReadUserId(ctx, claims, dbConn, userID)
|
err := CanReadUser(ctx, claims, dbConn, userID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -194,9 +193,6 @@ func find(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, query *sqlbu
|
|||||||
queryStr = dbConn.Rebind(queryStr)
|
queryStr = dbConn.Rebind(queryStr)
|
||||||
args = append(args, queryArgs...)
|
args = append(args, queryArgs...)
|
||||||
|
|
||||||
fmt.Println(queryStr)
|
|
||||||
fmt.Println(args)
|
|
||||||
|
|
||||||
// fetch all places from the db
|
// fetch all places from the db
|
||||||
rows, err := dbConn.QueryContext(ctx, queryStr, args...)
|
rows, err := dbConn.QueryContext(ctx, queryStr, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -216,8 +212,6 @@ func find(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, query *sqlbu
|
|||||||
resp = append(resp, u)
|
resp = append(resp, u)
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("len", len(resp))
|
|
||||||
|
|
||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,15 +323,11 @@ func Create(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req Create
|
|||||||
Email: req.Email,
|
Email: req.Email,
|
||||||
PasswordHash: passwordHash,
|
PasswordHash: passwordHash,
|
||||||
PasswordSalt: passwordSalt,
|
PasswordSalt: passwordSalt,
|
||||||
Status: UserStatus_Active,
|
|
||||||
Timezone: "America/Anchorage",
|
Timezone: "America/Anchorage",
|
||||||
CreatedAt: now,
|
CreatedAt: now,
|
||||||
UpdatedAt: now,
|
UpdatedAt: now,
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.Status != nil {
|
|
||||||
u.Status = *req.Status
|
|
||||||
}
|
|
||||||
if req.Timezone != nil {
|
if req.Timezone != nil {
|
||||||
u.Timezone = *req.Timezone
|
u.Timezone = *req.Timezone
|
||||||
}
|
}
|
||||||
@@ -345,8 +335,8 @@ 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", "status", "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.Status.String(), 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.
|
||||||
sql, args := query.Build()
|
sql, args := query.Build()
|
||||||
@@ -390,7 +380,7 @@ func Update(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req Update
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the claims can modify the user specified in the request.
|
// Ensure the claims can modify the user specified in the request.
|
||||||
err = CanModifyUserId(ctx, claims, dbConn, req.ID)
|
err = CanModifyUser(ctx, claims, dbConn, req.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = errors.WithMessagef(err, "Update %s failed", usersTableName)
|
err = errors.WithMessagef(err, "Update %s failed", usersTableName)
|
||||||
return err
|
return err
|
||||||
@@ -419,9 +409,6 @@ func Update(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req Update
|
|||||||
if req.Email != nil {
|
if req.Email != nil {
|
||||||
fields = append(fields, query.Assign("email", req.Email))
|
fields = append(fields, query.Assign("email", req.Email))
|
||||||
}
|
}
|
||||||
if req.Status != nil {
|
|
||||||
fields = append(fields, query.Assign("status", req.Status))
|
|
||||||
}
|
|
||||||
if req.Timezone != nil {
|
if req.Timezone != nil {
|
||||||
fields = append(fields, query.Assign("timezone", req.Timezone))
|
fields = append(fields, query.Assign("timezone", req.Timezone))
|
||||||
}
|
}
|
||||||
@@ -462,7 +449,7 @@ func UpdatePassword(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, re
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the claims can modify the user specified in the request.
|
// Ensure the claims can modify the user specified in the request.
|
||||||
err = CanModifyUserId(ctx, claims, dbConn, req.ID)
|
err = CanModifyUser(ctx, claims, dbConn, req.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -529,7 +516,7 @@ func Archive(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userID st
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the claims can modify the user specified in the request.
|
// Ensure the claims can modify the user specified in the request.
|
||||||
err = CanModifyUserId(ctx, claims, dbConn, req.ID)
|
err = CanModifyUser(ctx, claims, dbConn, req.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -607,7 +594,7 @@ func Delete(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userID str
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the claims can modify the user specified in the request.
|
// Ensure the claims can modify the user specified in the request.
|
||||||
err = CanModifyUserId(ctx, claims, dbConn, req.ID)
|
err = CanModifyUser(ctx, claims, dbConn, req.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@@ -3,6 +3,7 @@ package user
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"github.com/lib/pq"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
||||||
@@ -18,7 +19,7 @@ import (
|
|||||||
const usersAccountsTableName = "users_accounts"
|
const usersAccountsTableName = "users_accounts"
|
||||||
|
|
||||||
// The list of columns needed for mapRowsToUserAccount
|
// The list of columns needed for mapRowsToUserAccount
|
||||||
var usersAccountsMapColumns = "id,user_id,account_id,roles,created_at,updated_at,archived_at"
|
var usersAccountsMapColumns = "id,user_id,account_id,roles,status,created_at,updated_at,archived_at"
|
||||||
|
|
||||||
// mapRowsToUserAccount takes the SQL rows and maps it to the UserAccount struct
|
// mapRowsToUserAccount takes the SQL rows and maps it to the UserAccount struct
|
||||||
// with the columns defined by usersAccountsMapColumns
|
// with the columns defined by usersAccountsMapColumns
|
||||||
@@ -27,7 +28,7 @@ func mapRowsToUserAccount(rows *sql.Rows) (*UserAccount, error) {
|
|||||||
ua UserAccount
|
ua UserAccount
|
||||||
err error
|
err error
|
||||||
)
|
)
|
||||||
err = rows.Scan(&ua.ID, &ua.UserID, &ua.AccountID, &ua.Roles, &ua.CreatedAt, &ua.UpdatedAt, &ua.ArchivedAt)
|
err = rows.Scan(&ua.ID, &ua.UserID, &ua.AccountID, &ua.Roles, &ua.Status, &ua.CreatedAt, &ua.UpdatedAt, &ua.ArchivedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithStack(err)
|
return nil, errors.WithStack(err)
|
||||||
}
|
}
|
||||||
@@ -35,6 +36,32 @@ func mapRowsToUserAccount(rows *sql.Rows) (*UserAccount, error) {
|
|||||||
return &ua, nil
|
return &ua, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CanModifyUserAccount determines if claims has the authority to modify the specified user ID.
|
||||||
|
func CanModifyUserAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userID, accountID string) error {
|
||||||
|
// First check to see if claims can read the user ID
|
||||||
|
err := CanReadUser(ctx, claims, dbConn, userID)
|
||||||
|
if err != nil {
|
||||||
|
if claims.Audience != accountID {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the request has claims from a specific user, ensure that the user
|
||||||
|
// has the correct role for updating an existing user.
|
||||||
|
if claims.Subject != "" {
|
||||||
|
if claims.Subject == userID {
|
||||||
|
// All users are allowed to update their own record
|
||||||
|
} else if claims.HasRole(auth.RoleAdmin) {
|
||||||
|
// Admin users can update users they have access to.
|
||||||
|
} else {
|
||||||
|
return errors.WithStack(ErrForbidden)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
@@ -54,7 +81,7 @@ func applyClaimsUserAccountSelect(ctx context.Context, claims auth.Claims, query
|
|||||||
if claims.Subject != "" {
|
if claims.Subject != "" {
|
||||||
or = append(or, subQuery.Equal("user_id", claims.Subject))
|
or = append(or, subQuery.Equal("user_id", claims.Subject))
|
||||||
}
|
}
|
||||||
subQuery.Where(or...)
|
subQuery.Where(subQuery.Or(or...))
|
||||||
|
|
||||||
// Append sub query
|
// Append sub query
|
||||||
query.Where(query.In("user_id", subQuery))
|
query.Where(query.In("user_id", subQuery))
|
||||||
@@ -76,7 +103,7 @@ func accountSelectQuery() *sqlbuilder.SelectBuilder {
|
|||||||
func accountFindRequestQuery(req UserAccountFindRequest) (*sqlbuilder.SelectBuilder, []interface{}) {
|
func accountFindRequestQuery(req UserAccountFindRequest) (*sqlbuilder.SelectBuilder, []interface{}) {
|
||||||
query := accountSelectQuery()
|
query := accountSelectQuery()
|
||||||
if req.Where != nil {
|
if req.Where != nil {
|
||||||
query.Where(*req.Where)
|
query.Where(query.And(*req.Where))
|
||||||
}
|
}
|
||||||
if len(req.Order) > 0 {
|
if len(req.Order) > 0 {
|
||||||
query.OrderBy(req.Order...)
|
query.OrderBy(req.Order...)
|
||||||
@@ -85,12 +112,9 @@ func accountFindRequestQuery(req UserAccountFindRequest) (*sqlbuilder.SelectBuil
|
|||||||
query.Limit(int(*req.Limit))
|
query.Limit(int(*req.Limit))
|
||||||
}
|
}
|
||||||
if req.Offset != nil {
|
if req.Offset != nil {
|
||||||
query.Limit(int(*req.Offset))
|
query.Offset(int(*req.Offset))
|
||||||
}
|
}
|
||||||
|
|
||||||
b := sqlbuilder.Buildf(query.String(), req.Args...)
|
|
||||||
query.BuilderAs(b, usersAccountsMapColumns)
|
|
||||||
|
|
||||||
return query, req.Args
|
return query, req.Args
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,26 +181,29 @@ func FindAccountsByUserID(ctx context.Context, claims auth.Claims, dbConn *sqlx.
|
|||||||
res, err := findAccounts(ctx, claims, dbConn, query, []interface{}{}, includedArchived)
|
res, err := findAccounts(ctx, claims, dbConn, query, []interface{}{}, includedArchived)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if res == nil || len(res) == 0 {
|
||||||
|
err = errors.WithMessagef(ErrNotFound, "no accounts for user %s found", userID)
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return res, nil
|
return res, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddAccount an account for a given user with specified roles.
|
// AddAccount an account for a given user with specified roles.
|
||||||
func AddAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req AddAccountRequest, now time.Time) error {
|
func AddAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req AddAccountRequest, now time.Time) (*UserAccount, error) {
|
||||||
span, ctx := tracer.StartSpanFromContext(ctx, "internal.user.AddAccount")
|
span, ctx := tracer.StartSpanFromContext(ctx, "internal.user.AddAccount")
|
||||||
defer span.Finish()
|
defer span.Finish()
|
||||||
|
|
||||||
// Validate the request.
|
// Validate the request.
|
||||||
err := validator.New().Struct(req)
|
err := validator.New().Struct(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the claims can modify the user specified in the request.
|
// Ensure the claims can modify the user specified in the request.
|
||||||
err = CanModifyUserId(ctx, claims, dbConn, req.UserID)
|
err = CanModifyUserAccount(ctx, claims, dbConn, req.UserID, req.AccountID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// If now empty set it to the current time.
|
// If now empty set it to the current time.
|
||||||
@@ -199,7 +226,7 @@ func AddAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req Ad
|
|||||||
))
|
))
|
||||||
existing, err := findAccounts(ctx, claims, dbConn, existQuery, []interface{}{}, true)
|
existing, err := findAccounts(ctx, claims, dbConn, existQuery, []interface{}{}, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// If there is an existing entry, then update instead of insert.
|
// If there is an existing entry, then update instead of insert.
|
||||||
@@ -207,20 +234,41 @@ func AddAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req Ad
|
|||||||
upReq := UpdateAccountRequest{
|
upReq := UpdateAccountRequest{
|
||||||
UserID: req.UserID,
|
UserID: req.UserID,
|
||||||
AccountID: req.AccountID,
|
AccountID: req.AccountID,
|
||||||
Roles: req.Roles,
|
Roles: &req.Roles,
|
||||||
unArchive: true,
|
unArchive: true,
|
||||||
}
|
}
|
||||||
return UpdateAccount(ctx, claims, dbConn, upReq, now)
|
err = UpdateAccount(ctx, claims, dbConn, upReq, now)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// New auto-generated uuid for the record
|
ua := existing[0]
|
||||||
id := uuid.NewRandom().String()
|
ua.Roles = req.Roles
|
||||||
|
ua.UpdatedAt = now
|
||||||
|
ua.ArchivedAt = pq.NullTime{}
|
||||||
|
|
||||||
|
return ua, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
ua := UserAccount{
|
||||||
|
ID: uuid.NewRandom().String(),
|
||||||
|
UserID: req.UserID,
|
||||||
|
AccountID: req.AccountID,
|
||||||
|
Roles: req.Roles,
|
||||||
|
Status: UserAccountStatus_Active,
|
||||||
|
CreatedAt: now,
|
||||||
|
UpdatedAt: now,
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Status != nil {
|
||||||
|
ua.Status = *req.Status
|
||||||
|
}
|
||||||
|
|
||||||
// Build the insert SQL statement.
|
// Build the insert SQL statement.
|
||||||
query := sqlbuilder.NewInsertBuilder()
|
query := sqlbuilder.NewInsertBuilder()
|
||||||
query.InsertInto(usersAccountsTableName)
|
query.InsertInto(usersAccountsTableName)
|
||||||
query.Cols("id", "user_id", "account_id", "roles", "created_at", "updated_at")
|
query.Cols("id", "user_id", "account_id", "roles", "status", "created_at", "updated_at")
|
||||||
query.Values(id, req.UserID, req.AccountID, req.Roles, now, now)
|
query.Values(ua.ID, ua.UserID, ua.AccountID, ua.Roles, ua.Status.String(), ua.CreatedAt, ua.UpdatedAt)
|
||||||
|
|
||||||
// Execute the query with the provided context.
|
// Execute the query with the provided context.
|
||||||
sql, args := query.Build()
|
sql, args := query.Build()
|
||||||
@@ -229,10 +277,10 @@ func AddAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req Ad
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
err = errors.Wrapf(err, "query - %s", query.String())
|
err = errors.Wrapf(err, "query - %s", query.String())
|
||||||
err = errors.WithMessagef(err, "add account %s to user %s failed", req.AccountID, req.UserID)
|
err = errors.WithMessagef(err, "add account %s to user %s failed", req.AccountID, req.UserID)
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return &ua, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateAccount...
|
// UpdateAccount...
|
||||||
@@ -247,7 +295,7 @@ func UpdateAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the claims can modify the user specified in the request.
|
// Ensure the claims can modify the user specified in the request.
|
||||||
err = CanModifyUserId(ctx, claims, dbConn, req.UserID)
|
err = CanModifyUserAccount(ctx, claims, dbConn, req.UserID, req.AccountID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -266,11 +314,26 @@ func UpdateAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req
|
|||||||
|
|
||||||
// Build the update SQL statement.
|
// Build the update SQL statement.
|
||||||
query := sqlbuilder.NewUpdateBuilder()
|
query := sqlbuilder.NewUpdateBuilder()
|
||||||
query.Update(usersTableName)
|
query.Update(usersAccountsTableName)
|
||||||
query.Set(
|
|
||||||
query.Assign("roles", req.Roles),
|
fields := []string{}
|
||||||
query.Assign("updated_at", now),
|
if req.Roles != nil {
|
||||||
)
|
fields = append(fields, query.Assign("roles", req.Roles))
|
||||||
|
}
|
||||||
|
if req.Status != nil {
|
||||||
|
fields = append(fields, query.Assign("status", req.Status))
|
||||||
|
}
|
||||||
|
|
||||||
|
// If there's nothing to update we can quit early.
|
||||||
|
if len(fields) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append the updated_at field
|
||||||
|
fields = append(fields, query.Assign("updated_at", now))
|
||||||
|
|
||||||
|
query.Set(fields...)
|
||||||
|
|
||||||
query.Where(query.And(
|
query.Where(query.And(
|
||||||
query.Equal("user_id", req.UserID),
|
query.Equal("user_id", req.UserID),
|
||||||
query.Equal("account_id", req.AccountID),
|
query.Equal("account_id", req.AccountID),
|
||||||
@@ -301,7 +364,7 @@ func RemoveAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the claims can modify the user specified in the request.
|
// Ensure the claims can modify the user specified in the request.
|
||||||
err = CanModifyUserId(ctx, claims, dbConn, req.UserID)
|
err = CanModifyUserAccount(ctx, claims, dbConn, req.UserID, req.AccountID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -341,7 +404,7 @@ func RemoveAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAccount...
|
// DeleteAccount...
|
||||||
func DeleteAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req DeleteAccountRequest, now time.Time) error {
|
func DeleteAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req DeleteAccountRequest) error {
|
||||||
span, ctx := tracer.StartSpanFromContext(ctx, "internal.user.RemoveAccount")
|
span, ctx := tracer.StartSpanFromContext(ctx, "internal.user.RemoveAccount")
|
||||||
defer span.Finish()
|
defer span.Finish()
|
||||||
|
|
||||||
@@ -352,23 +415,11 @@ func DeleteAccount(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the claims can modify the user specified in the request.
|
// Ensure the claims can modify the user specified in the request.
|
||||||
err = CanModifyUserId(ctx, claims, dbConn, req.UserID)
|
err = CanModifyUserAccount(ctx, claims, dbConn, req.UserID, req.AccountID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// If now empty set it to the current time.
|
|
||||||
if now.IsZero() {
|
|
||||||
now = time.Now()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Always store the time as UTC.
|
|
||||||
now = now.UTC()
|
|
||||||
|
|
||||||
// Postgres truncates times to milliseconds when storing. We and do the same
|
|
||||||
// here so the value we return is consistent with what we store.
|
|
||||||
now = now.Truncate(time.Millisecond)
|
|
||||||
|
|
||||||
// Build the delete SQL statement.
|
// Build the delete SQL statement.
|
||||||
query := sqlbuilder.NewDeleteBuilder()
|
query := sqlbuilder.NewDeleteBuilder()
|
||||||
query.DeleteFrom(usersAccountsTableName)
|
query.DeleteFrom(usersAccountsTableName)
|
||||||
|
738
example-project/internal/user/user_account_test.go
Normal file
738
example-project/internal/user/user_account_test.go
Normal file
@@ -0,0 +1,738 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/lib/pq"
|
||||||
|
"math/rand"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
||||||
|
"github.com/dgrijalva/jwt-go"
|
||||||
|
"github.com/huandu/go-sqlbuilder"
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestAccountFindRequestQuery validates accountFindRequestQuery
|
||||||
|
func TestAccountFindRequestQuery(t *testing.T) {
|
||||||
|
where := "account_id = ? or user_id = ?"
|
||||||
|
var (
|
||||||
|
limit uint = 12
|
||||||
|
offset uint = 34
|
||||||
|
)
|
||||||
|
|
||||||
|
req := UserAccountFindRequest{
|
||||||
|
Where: &where,
|
||||||
|
Args: []interface{}{
|
||||||
|
"xy7",
|
||||||
|
"qwert",
|
||||||
|
},
|
||||||
|
Order: []string{
|
||||||
|
"id asc",
|
||||||
|
"created_at desc",
|
||||||
|
},
|
||||||
|
Limit: &limit,
|
||||||
|
Offset: &offset,
|
||||||
|
}
|
||||||
|
expected := "SELECT " + usersAccountsMapColumns + " FROM " + usersAccountsTableName + " WHERE (account_id = ? or user_id = ?) ORDER BY id asc, created_at desc LIMIT 12 OFFSET 34"
|
||||||
|
|
||||||
|
res, args := accountFindRequestQuery(req)
|
||||||
|
|
||||||
|
if diff := cmp.Diff(res.String(), expected); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tExpected result query to match. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(args, req.Args); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tExpected result query to match. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestApplyClaimsUserAccountSelect validates applyClaimsUserAccountSelect
|
||||||
|
func TestApplyClaimsUserAccountSelect(t *testing.T) {
|
||||||
|
var claimTests = []struct {
|
||||||
|
name string
|
||||||
|
claims auth.Claims
|
||||||
|
expectedSql string
|
||||||
|
error error
|
||||||
|
}{
|
||||||
|
{"EmptyClaims",
|
||||||
|
auth.Claims{},
|
||||||
|
"SELECT " + usersAccountsMapColumns + " FROM " + usersAccountsTableName,
|
||||||
|
nil,
|
||||||
|
},
|
||||||
|
{"RoleUser",
|
||||||
|
auth.Claims{
|
||||||
|
Roles: []string{auth.RoleUser},
|
||||||
|
StandardClaims: jwt.StandardClaims{
|
||||||
|
Subject: "user1",
|
||||||
|
Audience: "acc1",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"SELECT " + usersAccountsMapColumns + " FROM " + usersAccountsTableName + " WHERE user_id IN (SELECT user_id FROM " + usersAccountsTableName + " WHERE (account_id = 'acc1' OR user_id = 'user1'))",
|
||||||
|
nil,
|
||||||
|
},
|
||||||
|
{"RoleAdmin",
|
||||||
|
auth.Claims{
|
||||||
|
Roles: []string{auth.RoleAdmin},
|
||||||
|
StandardClaims: jwt.StandardClaims{
|
||||||
|
Subject: "user1",
|
||||||
|
Audience: "acc1",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"SELECT " + usersAccountsMapColumns + " FROM " + usersAccountsTableName + " WHERE user_id IN (SELECT user_id FROM " + usersAccountsTableName + " WHERE (account_id = 'acc1' OR user_id = 'user1'))",
|
||||||
|
nil,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Log("Given the need to validate ACLs are enforced by claims to a select query.")
|
||||||
|
{
|
||||||
|
for i, tt := range claimTests {
|
||||||
|
t.Logf("\tTest: %d\tWhen running test: %s", i, tt.name)
|
||||||
|
{
|
||||||
|
ctx := tests.Context()
|
||||||
|
|
||||||
|
query := accountSelectQuery()
|
||||||
|
|
||||||
|
err := applyClaimsUserAccountSelect(ctx, tt.claims, query)
|
||||||
|
if err != tt.error {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", tt.error)
|
||||||
|
t.Fatalf("\t%s\tapplyClaimsUserAccountSelect failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
sql, args := query.Build()
|
||||||
|
|
||||||
|
// Use mysql flavor so placeholders will get replaced for comparison.
|
||||||
|
sql, err = sqlbuilder.MySQL.Interpolate(sql, args)
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tapplyClaimsUserAccountSelect failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
if diff := cmp.Diff(sql, tt.expectedSql); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tExpected result query to match. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("\t%s\tapplyClaimsUserAccountSelect ok.", tests.Success)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAddAccountValidation ensures all the validation tags work on account add.
|
||||||
|
func TestAddAccountValidation(t *testing.T) {
|
||||||
|
|
||||||
|
invalidRole := UserAccountRole("moon")
|
||||||
|
invalidStatus := UserAccountStatus("moon")
|
||||||
|
|
||||||
|
|
||||||
|
var accountTests = []struct {
|
||||||
|
name string
|
||||||
|
req AddAccountRequest
|
||||||
|
expected func(req AddAccountRequest, res *UserAccount) *UserAccount
|
||||||
|
error error
|
||||||
|
}{
|
||||||
|
{"Required Fields",
|
||||||
|
AddAccountRequest{},
|
||||||
|
func(req AddAccountRequest, res *UserAccount) *UserAccount {
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
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.Roles' Error:Field validation for 'Roles' failed on the 'required' tag"),
|
||||||
|
},
|
||||||
|
{"Valid Role",
|
||||||
|
AddAccountRequest{
|
||||||
|
UserID: uuid.NewRandom().String(),
|
||||||
|
AccountID: uuid.NewRandom().String(),
|
||||||
|
Roles: []UserAccountRole{invalidRole},
|
||||||
|
},
|
||||||
|
func(req AddAccountRequest, res *UserAccount) *UserAccount {
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
errors.New("Key: 'AddAccountRequest.Roles[0]' Error:Field validation for 'Roles[0]' failed on the 'oneof' tag"),
|
||||||
|
},
|
||||||
|
{"Valid Status",
|
||||||
|
AddAccountRequest{
|
||||||
|
UserID: uuid.NewRandom().String(),
|
||||||
|
AccountID: uuid.NewRandom().String(),
|
||||||
|
Roles: []UserAccountRole{UserAccountRole_User},
|
||||||
|
Status: &invalidStatus,
|
||||||
|
},
|
||||||
|
func(req AddAccountRequest, res *UserAccount) *UserAccount {
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
errors.New("Key: 'AddAccountRequest.Status' Error:Field validation for 'Status' failed on the 'oneof' tag"),
|
||||||
|
},
|
||||||
|
{"Default Status",
|
||||||
|
AddAccountRequest{
|
||||||
|
UserID: uuid.NewRandom().String(),
|
||||||
|
AccountID: uuid.NewRandom().String(),
|
||||||
|
Roles: []UserAccountRole{UserAccountRole_User},
|
||||||
|
},
|
||||||
|
func(req AddAccountRequest, res *UserAccount) *UserAccount {
|
||||||
|
return &UserAccount{
|
||||||
|
UserID: req.UserID,
|
||||||
|
AccountID: req.AccountID,
|
||||||
|
Roles: req.Roles,
|
||||||
|
Status: UserAccountStatus_Active,
|
||||||
|
|
||||||
|
// Copy this fields from the result.
|
||||||
|
ID: res.ID,
|
||||||
|
CreatedAt: res.CreatedAt,
|
||||||
|
UpdatedAt: res.UpdatedAt,
|
||||||
|
//ArchivedAt: nil,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
nil,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
t.Log("Given the need ensure all validation tags are working for add account.")
|
||||||
|
{
|
||||||
|
for i, tt := range accountTests {
|
||||||
|
t.Logf("\tTest: %d\tWhen running test: %s", i, tt.name)
|
||||||
|
{
|
||||||
|
ctx := tests.Context()
|
||||||
|
|
||||||
|
res, err := AddAccount(ctx, auth.Claims{}, test.MasterDB, tt.req, now)
|
||||||
|
if err != tt.error {
|
||||||
|
// TODO: need a better way to handle validation errors as they are
|
||||||
|
// of type interface validator.ValidationErrorsTranslations
|
||||||
|
var errStr string
|
||||||
|
if err != nil {
|
||||||
|
errStr = err.Error()
|
||||||
|
}
|
||||||
|
var expectStr string
|
||||||
|
if tt.error != nil {
|
||||||
|
expectStr = tt.error.Error()
|
||||||
|
}
|
||||||
|
if errStr != expectStr {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", tt.error)
|
||||||
|
t.Fatalf("\t%s\tAddAccount failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If there was an error that was expected, then don't go any further
|
||||||
|
if tt.error != nil {
|
||||||
|
t.Logf("\t%s\tAddAccount ok.", tests.Success)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := tt.expected(tt.req, res)
|
||||||
|
if diff := cmp.Diff(res, expected); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tAddAccount result should match. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("\t%s\tAddAccount ok.", tests.Success)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAddAccountExistingEntry validates emails must be unique on add account.
|
||||||
|
func TestAddAccountExistingEntry(t *testing.T) {
|
||||||
|
|
||||||
|
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
t.Log("Given the need ensure duplicate entries for the same user ID + account ID are updated and does not throw a duplicate key error.")
|
||||||
|
{
|
||||||
|
ctx := tests.Context()
|
||||||
|
|
||||||
|
req1 := AddAccountRequest{
|
||||||
|
UserID: uuid.NewRandom().String(),
|
||||||
|
AccountID: uuid.NewRandom().String(),
|
||||||
|
Roles: []UserAccountRole{UserAccountRole_User},
|
||||||
|
}
|
||||||
|
ua1, err := AddAccount(ctx, auth.Claims{}, test.MasterDB, req1, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tAddAccount failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
if diff := cmp.Diff(ua1.Roles, req1.Roles); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tAddAccount roles should match request. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
|
||||||
|
req2 := AddAccountRequest{
|
||||||
|
UserID: req1.UserID,
|
||||||
|
AccountID: req1.AccountID,
|
||||||
|
Roles: []UserAccountRole{UserAccountRole_Admin},
|
||||||
|
}
|
||||||
|
ua2, err := AddAccount(ctx, auth.Claims{}, test.MasterDB, req2, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tAddAccount failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
if diff := cmp.Diff(ua2.Roles, req2.Roles); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tAddAccount roles should match request. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("\t%s\tAddAccount ok.", tests.Success)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestUpdateAccountValidation ensures all the validation tags work on account update.
|
||||||
|
func TestUpdateAccountValidation(t *testing.T) {
|
||||||
|
|
||||||
|
invalidRole := UserAccountRole("moon")
|
||||||
|
invalidStatus := UserAccountStatus("xxxxxxxxx")
|
||||||
|
|
||||||
|
var accountTests = []struct {
|
||||||
|
name string
|
||||||
|
req UpdateAccountRequest
|
||||||
|
error error
|
||||||
|
}{
|
||||||
|
{"Required Fields",
|
||||||
|
UpdateAccountRequest{},
|
||||||
|
errors.New("Key: 'UpdateAccountRequest.UserID' Error:Field validation for 'UserID' failed on the 'required' tag\n" +
|
||||||
|
"Key: 'UpdateAccountRequest.AccountID' Error:Field validation for 'AccountID' failed on the 'required' tag\n" +
|
||||||
|
"Key: 'UpdateAccountRequest.Roles' Error:Field validation for 'Roles' failed on the 'required' tag"),
|
||||||
|
},
|
||||||
|
{"Valid Role",
|
||||||
|
UpdateAccountRequest{
|
||||||
|
UserID: uuid.NewRandom().String(),
|
||||||
|
AccountID: uuid.NewRandom().String(),
|
||||||
|
Roles: &UserAccountRoles{invalidRole},
|
||||||
|
},
|
||||||
|
errors.New("Key: 'UpdateAccountRequest.Roles[0]' Error:Field validation for 'Roles[0]' failed on the 'oneof' tag"),
|
||||||
|
},
|
||||||
|
|
||||||
|
{"Valid Status",
|
||||||
|
UpdateAccountRequest{
|
||||||
|
UserID: uuid.NewRandom().String(),
|
||||||
|
AccountID: uuid.NewRandom().String(),
|
||||||
|
Roles: &UserAccountRoles{UserAccountRole_User},
|
||||||
|
Status: &invalidStatus,
|
||||||
|
},
|
||||||
|
errors.New("Key: 'UpdateAccountRequest.Status' Error:Field validation for 'Status' failed on the 'oneof' tag"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
t.Log("Given the need ensure all validation tags are working for update account.")
|
||||||
|
{
|
||||||
|
for i, tt := range accountTests {
|
||||||
|
t.Logf("\tTest: %d\tWhen running test: %s", i, tt.name)
|
||||||
|
{
|
||||||
|
ctx := tests.Context()
|
||||||
|
|
||||||
|
err := UpdateAccount(ctx, auth.Claims{}, test.MasterDB, tt.req, now)
|
||||||
|
if err != tt.error {
|
||||||
|
// TODO: need a better way to handle validation errors as they are
|
||||||
|
// of type interface validator.ValidationErrorsTranslations
|
||||||
|
var errStr string
|
||||||
|
if err != nil {
|
||||||
|
errStr = err.Error()
|
||||||
|
}
|
||||||
|
var expectStr string
|
||||||
|
if tt.error != nil {
|
||||||
|
expectStr = tt.error.Error()
|
||||||
|
}
|
||||||
|
if errStr != expectStr {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", tt.error)
|
||||||
|
t.Fatalf("\t%s\tUpdateAccount failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If there was an error that was expected, then don't go any further
|
||||||
|
if tt.error != nil {
|
||||||
|
t.Logf("\t%s\tUpdateAccount ok.", tests.Success)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("\t%s\tUpdateAccount ok.", tests.Success)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAccountCrud validates the full set of CRUD operations for user accounts and
|
||||||
|
// ensures ACLs are correctly applied by claims.
|
||||||
|
func TestAccountCrud(t *testing.T) {
|
||||||
|
defer tests.Recover(t)
|
||||||
|
|
||||||
|
type accountTest struct {
|
||||||
|
name string
|
||||||
|
claims func(string, string) auth.Claims
|
||||||
|
updateErr error
|
||||||
|
findErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
var accountTests []accountTest
|
||||||
|
|
||||||
|
// Internal request, should bypass ACL.
|
||||||
|
accountTests = append(accountTests, accountTest{"EmptyClaims",
|
||||||
|
func(userID, accountId string) auth.Claims {
|
||||||
|
return auth.Claims{}
|
||||||
|
},
|
||||||
|
nil,
|
||||||
|
nil,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Role of user but claim user does not match update user so forbidden.
|
||||||
|
accountTests = append(accountTests, accountTest{"RoleUserDiffUser",
|
||||||
|
func(userID, accountId string) auth.Claims {
|
||||||
|
return auth.Claims{
|
||||||
|
Roles: []string{auth.RoleUser},
|
||||||
|
StandardClaims: jwt.StandardClaims{
|
||||||
|
Subject: uuid.NewRandom().String(),
|
||||||
|
Audience: accountId,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ErrForbidden,
|
||||||
|
ErrNotFound,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Role of user AND claim user matches update user so OK.
|
||||||
|
accountTests = append(accountTests, accountTest{"RoleUserSameUser",
|
||||||
|
func(userID, accountId string) auth.Claims {
|
||||||
|
return auth.Claims{
|
||||||
|
Roles: []string{auth.RoleUser},
|
||||||
|
StandardClaims: jwt.StandardClaims{
|
||||||
|
Subject: userID,
|
||||||
|
Audience: accountId,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
nil,
|
||||||
|
nil,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Role of admin but claim account does not match update user so forbidden.
|
||||||
|
accountTests = append(accountTests, accountTest{"RoleAdminDiffUser",
|
||||||
|
func(userID, accountId string) auth.Claims {
|
||||||
|
return auth.Claims{
|
||||||
|
Roles: []string{auth.RoleAdmin},
|
||||||
|
StandardClaims: jwt.StandardClaims{
|
||||||
|
Subject: uuid.NewRandom().String(),
|
||||||
|
Audience: uuid.NewRandom().String(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ErrForbidden,
|
||||||
|
ErrNotFound,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Role of admin and claim account matches update user so ok.
|
||||||
|
accountTests = append(accountTests, accountTest{"RoleAdminSameAccount",
|
||||||
|
func(userID, accountId string) auth.Claims {
|
||||||
|
return auth.Claims{
|
||||||
|
Roles: []string{auth.RoleAdmin},
|
||||||
|
StandardClaims: jwt.StandardClaims{
|
||||||
|
Subject: uuid.NewRandom().String(),
|
||||||
|
Audience: accountId,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
nil,
|
||||||
|
nil,
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Log("Given the need to validate CRUD functionality for user accounts and ensure claims are applied as ACL.")
|
||||||
|
{
|
||||||
|
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
for i, tt := range accountTests {
|
||||||
|
t.Logf("\tTest: %d\tWhen running test: %s", i, tt.name)
|
||||||
|
{
|
||||||
|
// Always create the new user with empty claims, testing claims for create user
|
||||||
|
// will be handled separately.
|
||||||
|
user, err := Create(tests.Context(), auth.Claims{}, test.MasterDB, CreateUserRequest{
|
||||||
|
Name: "Lee Brown",
|
||||||
|
Email: uuid.NewRandom().String() + "@geeksinthewoods.com",
|
||||||
|
Password: "akTechFr0n!ier",
|
||||||
|
PasswordConfirm: "akTechFr0n!ier",
|
||||||
|
}, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tCreate user failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new random account and associate that with the user.
|
||||||
|
accountID := uuid.NewRandom().String()
|
||||||
|
createReq := AddAccountRequest{
|
||||||
|
UserID: user.ID,
|
||||||
|
AccountID: accountID,
|
||||||
|
Roles: []UserAccountRole{UserAccountRole_User},
|
||||||
|
}
|
||||||
|
ua, err := AddAccount(tests.Context(), tt.claims(user.ID, accountID), test.MasterDB, createReq, now)
|
||||||
|
if err != nil && errors.Cause(err) != tt.updateErr {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", tt.updateErr)
|
||||||
|
t.Fatalf("\t%s\tUpdateAccount failed.", tests.Failed)
|
||||||
|
} else if tt.updateErr == nil {
|
||||||
|
if diff := cmp.Diff(ua.Roles, createReq.Roles); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tExpected find result to match update. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tAddAccount ok.", tests.Success)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the account.
|
||||||
|
updateReq := UpdateAccountRequest{
|
||||||
|
UserID: user.ID,
|
||||||
|
AccountID: accountID,
|
||||||
|
Roles: &UserAccountRoles{UserAccountRole_Admin},
|
||||||
|
}
|
||||||
|
err = UpdateAccount(tests.Context(), tt.claims(user.ID, accountID), test.MasterDB, updateReq, now)
|
||||||
|
if err != nil && errors.Cause(err) != tt.updateErr {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", tt.updateErr)
|
||||||
|
t.Fatalf("\t%s\tUpdateAccount failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tUpdateAccount ok.", tests.Success)
|
||||||
|
|
||||||
|
// Find the account for the user to verify the updates where made. There should only
|
||||||
|
// be one account associated with the user for this test.
|
||||||
|
findRes, err := FindAccountsByUserID(tests.Context(), tt.claims(user.ID, accountID), test.MasterDB, user.ID, false)
|
||||||
|
if err != nil && errors.Cause(err) != tt.findErr {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", tt.findErr)
|
||||||
|
t.Fatalf("\t%s\tVerify UpdateAccount failed.", tests.Failed)
|
||||||
|
} else if tt.findErr == nil {
|
||||||
|
expected := []*UserAccount{
|
||||||
|
&UserAccount{
|
||||||
|
ID: ua.ID,
|
||||||
|
UserID: ua.UserID,
|
||||||
|
AccountID: ua.AccountID,
|
||||||
|
Roles: *updateReq.Roles,
|
||||||
|
Status: ua.Status,
|
||||||
|
CreatedAt:ua.CreatedAt,
|
||||||
|
UpdatedAt: now,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(findRes, expected); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tExpected find result to match update. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tVerify UpdateAccount ok.", tests.Success)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Archive (soft-delete) the user account.
|
||||||
|
err = RemoveAccount(tests.Context(), tt.claims(user.ID, accountID), test.MasterDB, RemoveAccountRequest{
|
||||||
|
UserID: user.ID,
|
||||||
|
AccountID: accountID,
|
||||||
|
}, now)
|
||||||
|
if err != nil && errors.Cause(err) != tt.updateErr {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", tt.updateErr)
|
||||||
|
t.Fatalf("\t%s\tRemoveAccount failed.", tests.Failed)
|
||||||
|
} else if tt.updateErr == nil {
|
||||||
|
// Trying to find the archived user with the includeArchived false should result in not found.
|
||||||
|
_, err = FindAccountsByUserID(tests.Context(), tt.claims(user.ID, accountID), test.MasterDB, user.ID, false)
|
||||||
|
if errors.Cause(err) != ErrNotFound {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", ErrNotFound)
|
||||||
|
t.Fatalf("\t%s\tVerify RemoveAccount failed when excluding archived.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trying to find the archived user with the includeArchived true should result no error.
|
||||||
|
findRes, err = FindAccountsByUserID(tests.Context(), tt.claims(user.ID, accountID), test.MasterDB, user.ID, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Fatalf("\t%s\tVerify RemoveAccount failed when including archived.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := []*UserAccount{
|
||||||
|
&UserAccount{
|
||||||
|
ID: ua.ID,
|
||||||
|
UserID: ua.UserID,
|
||||||
|
AccountID: ua.AccountID,
|
||||||
|
Roles: *updateReq.Roles,
|
||||||
|
Status: ua.Status,
|
||||||
|
CreatedAt:ua.CreatedAt,
|
||||||
|
UpdatedAt: now,
|
||||||
|
ArchivedAt: pq.NullTime{Time: now, Valid:true},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(findRes, expected); diff != "" {
|
||||||
|
t.Fatalf("\t%s\tExpected find result to be archived. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tRemoveAccount ok.", tests.Success)
|
||||||
|
|
||||||
|
// Delete (hard-delete) the user account.
|
||||||
|
err = DeleteAccount(tests.Context(), tt.claims(user.ID, accountID), test.MasterDB, DeleteAccountRequest{
|
||||||
|
UserID: user.ID,
|
||||||
|
AccountID: accountID,
|
||||||
|
})
|
||||||
|
if err != nil && errors.Cause(err) != tt.updateErr {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", tt.updateErr)
|
||||||
|
t.Fatalf("\t%s\tDeleteAccount failed.", tests.Failed)
|
||||||
|
} else if tt.updateErr == nil {
|
||||||
|
// Trying to find the deleted user with the includeArchived true should result in not found.
|
||||||
|
_, err = FindAccountsByUserID(tests.Context(), tt.claims(user.ID, accountID), test.MasterDB, user.ID, true)
|
||||||
|
if errors.Cause(err) != ErrNotFound {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", ErrNotFound)
|
||||||
|
t.Fatalf("\t%s\tVerify DeleteAccount failed when including archived.", tests.Failed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tDeleteAccount ok.", tests.Success)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAccountFind validates all the request params are correctly parsed into a select query.
|
||||||
|
func TestAccountFind(t *testing.T) {
|
||||||
|
|
||||||
|
// Ensure all the existing user accounts are deleted.
|
||||||
|
{
|
||||||
|
// Build the delete SQL statement.
|
||||||
|
query := sqlbuilder.NewDeleteBuilder()
|
||||||
|
query.DeleteFrom(usersAccountsTableName)
|
||||||
|
|
||||||
|
// Execute the query with the provided context.
|
||||||
|
sql, args := query.Build()
|
||||||
|
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
|
||||||
|
for i := 0; i <= 4; i++ {
|
||||||
|
user, err := Create(tests.Context(), auth.Claims{}, test.MasterDB, CreateUserRequest{
|
||||||
|
Name: "Lee Brown",
|
||||||
|
Email: uuid.NewRandom().String() + "@geeksinthewoods.com",
|
||||||
|
Password: "akTechFr0n!ier",
|
||||||
|
PasswordConfirm: "akTechFr0n!ier",
|
||||||
|
}, now.Add(time.Second*time.Duration(i)))
|
||||||
|
if err != nil {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Fatalf("\t%s\tCreate user failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new random account and associate that with the user.
|
||||||
|
accountID := uuid.NewRandom().String()
|
||||||
|
ua, err := AddAccount(tests.Context(), auth.Claims{}, test.MasterDB, AddAccountRequest{
|
||||||
|
UserID: user.ID,
|
||||||
|
AccountID: accountID,
|
||||||
|
Roles: []UserAccountRole{UserAccountRole_User},
|
||||||
|
}, now.Add(time.Second*time.Duration(i)))
|
||||||
|
if err != nil {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Fatalf("\t%s\tAdd account failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
userAccounts = append(userAccounts, ua)
|
||||||
|
}
|
||||||
|
|
||||||
|
type accountTest struct {
|
||||||
|
name string
|
||||||
|
req UserAccountFindRequest
|
||||||
|
expected []*UserAccount
|
||||||
|
error error
|
||||||
|
}
|
||||||
|
|
||||||
|
var accountTests []accountTest
|
||||||
|
|
||||||
|
// Test sort users.
|
||||||
|
accountTests = append(accountTests, accountTest{"Find all order by created_at asx",
|
||||||
|
UserAccountFindRequest{
|
||||||
|
Order: []string{"created_at"},
|
||||||
|
},
|
||||||
|
userAccounts,
|
||||||
|
nil,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Test reverse sorted user accounts.
|
||||||
|
var expected []*UserAccount
|
||||||
|
for i := len(userAccounts) - 1; i >= 0; i-- {
|
||||||
|
expected = append(expected, userAccounts[i])
|
||||||
|
}
|
||||||
|
accountTests = append(accountTests, accountTest{"Find all order by created_at desc",
|
||||||
|
UserAccountFindRequest{
|
||||||
|
Order: []string{"created_at desc"},
|
||||||
|
},
|
||||||
|
expected,
|
||||||
|
nil,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Test limit.
|
||||||
|
var limit uint = 2
|
||||||
|
accountTests = append(accountTests, accountTest{"Find limit",
|
||||||
|
UserAccountFindRequest{
|
||||||
|
Order: []string{"created_at"},
|
||||||
|
Limit: &limit,
|
||||||
|
},
|
||||||
|
userAccounts[0:2],
|
||||||
|
nil,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Test offset.
|
||||||
|
var offset uint = 3
|
||||||
|
accountTests = append(accountTests, accountTest{"Find limit, offset",
|
||||||
|
UserAccountFindRequest{
|
||||||
|
Order: []string{"created_at"},
|
||||||
|
Limit: &limit,
|
||||||
|
Offset: &offset,
|
||||||
|
},
|
||||||
|
userAccounts[3:5],
|
||||||
|
nil,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Test where filter.
|
||||||
|
whereParts := []string{}
|
||||||
|
whereArgs := []interface{}{}
|
||||||
|
expected = []*UserAccount{}
|
||||||
|
selected := make(map[string]bool)
|
||||||
|
for i := 0; i <= 2; i++ {
|
||||||
|
ranIdx := rand.Intn(len(userAccounts))
|
||||||
|
|
||||||
|
id := userAccounts[ranIdx].ID
|
||||||
|
if selected[id] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
selected[id] = true
|
||||||
|
|
||||||
|
whereParts = append(whereParts, "id = ?")
|
||||||
|
whereArgs = append(whereArgs, id)
|
||||||
|
expected = append(expected, userAccounts[ranIdx])
|
||||||
|
}
|
||||||
|
where := strings.Join(whereParts, " OR ")
|
||||||
|
accountTests = append(accountTests, accountTest{"Find where",
|
||||||
|
UserAccountFindRequest{
|
||||||
|
Where: &where,
|
||||||
|
Args: whereArgs,
|
||||||
|
},
|
||||||
|
expected,
|
||||||
|
nil,
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Log("Given the need to ensure find users returns the expected results.")
|
||||||
|
{
|
||||||
|
for i, tt := range accountTests {
|
||||||
|
t.Logf("\tTest: %d\tWhen running test: %s", i, tt.name)
|
||||||
|
{
|
||||||
|
ctx := tests.Context()
|
||||||
|
|
||||||
|
res, err := FindAccounts(ctx, auth.Claims{}, test.MasterDB, tt.req)
|
||||||
|
if err != nil && errors.Cause(err) != tt.error {
|
||||||
|
t.Logf("\t\tGot : %+v", err)
|
||||||
|
t.Logf("\t\tWant: %+v", tt.error)
|
||||||
|
t.Fatalf("\t%s\tFind failed.", tests.Failed)
|
||||||
|
} else if diff := cmp.Diff(res, tt.expected); diff != "" {
|
||||||
|
t.Logf("\t\tGot: %d items", len(res))
|
||||||
|
t.Logf("\t\tWant: %d items", len(tt.expected))
|
||||||
|
t.Fatalf("\t%s\tExpected find result to match expected. Diff:\n%s", tests.Failed, diff)
|
||||||
|
}
|
||||||
|
t.Logf("\t%s\tFind ok.", tests.Success)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -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) {
|
||||||
|
|
||||||
invalidStatus := UserStatus("moon")
|
|
||||||
|
|
||||||
var userTests = []struct {
|
var userTests = []struct {
|
||||||
name string
|
name string
|
||||||
@@ -166,19 +165,6 @@ func TestCreateUserValidation(t *testing.T) {
|
|||||||
},
|
},
|
||||||
errors.New("Key: 'CreateUserRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag"),
|
errors.New("Key: 'CreateUserRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag"),
|
||||||
},
|
},
|
||||||
{"Valid Status",
|
|
||||||
CreateUserRequest{
|
|
||||||
Name: "Lee Brown",
|
|
||||||
Email: uuid.NewRandom().String() + "@geeksinthewoods.com",
|
|
||||||
Password: "akTechFr0n!ier",
|
|
||||||
PasswordConfirm: "akTechFr0n!ier",
|
|
||||||
Status: &invalidStatus,
|
|
||||||
},
|
|
||||||
func(req CreateUserRequest, res *User) *User {
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
errors.New("Key: 'CreateUserRequest.Status' Error:Field validation for 'Status' failed on the 'oneof' tag"),
|
|
||||||
},
|
|
||||||
{"Passwords Match",
|
{"Passwords Match",
|
||||||
CreateUserRequest{
|
CreateUserRequest{
|
||||||
Name: "Lee Brown",
|
Name: "Lee Brown",
|
||||||
@@ -191,7 +177,7 @@ func TestCreateUserValidation(t *testing.T) {
|
|||||||
},
|
},
|
||||||
errors.New("Key: 'CreateUserRequest.PasswordConfirm' Error:Field validation for 'PasswordConfirm' failed on the 'eqfield' tag"),
|
errors.New("Key: 'CreateUserRequest.PasswordConfirm' Error:Field validation for 'PasswordConfirm' failed on the 'eqfield' tag"),
|
||||||
},
|
},
|
||||||
{"Default Status & Timezone",
|
{"Default Timezone",
|
||||||
CreateUserRequest{
|
CreateUserRequest{
|
||||||
Name: "Lee Brown",
|
Name: "Lee Brown",
|
||||||
Email: uuid.NewRandom().String() + "@geeksinthewoods.com",
|
Email: uuid.NewRandom().String() + "@geeksinthewoods.com",
|
||||||
@@ -202,7 +188,6 @@ func TestCreateUserValidation(t *testing.T) {
|
|||||||
return &User{
|
return &User{
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
Email: req.Email,
|
Email: req.Email,
|
||||||
Status: UserStatus_Active,
|
|
||||||
Timezone: "America/Anchorage",
|
Timezone: "America/Anchorage",
|
||||||
|
|
||||||
// Copy this fields from the result.
|
// Copy this fields from the result.
|
||||||
@@ -412,15 +397,6 @@ func TestUpdateUserValidation(t *testing.T) {
|
|||||||
errors.New("Key: 'UpdateUserRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag"),
|
errors.New("Key: 'UpdateUserRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag"),
|
||||||
})
|
})
|
||||||
|
|
||||||
invalidStatus := UserStatus("xxxxxxxxx")
|
|
||||||
userTests = append(userTests, userTest{"Valid Status",
|
|
||||||
UpdateUserRequest{
|
|
||||||
ID: uuid.NewRandom().String(),
|
|
||||||
Status: &invalidStatus,
|
|
||||||
},
|
|
||||||
errors.New("Key: 'UpdateUserRequest.Status' Error:Field validation for 'Status' failed on the 'oneof' tag"),
|
|
||||||
})
|
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
t.Log("Given the need ensure all validation tags are working for user update.")
|
t.Log("Given the need ensure all validation tags are working for user update.")
|
||||||
@@ -534,6 +510,18 @@ func TestUpdateUserPassword(t *testing.T) {
|
|||||||
t.Fatalf("\t%s\tCreate failed.", tests.Failed)
|
t.Fatalf("\t%s\tCreate failed.", tests.Failed)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create a new random account and associate that with the user.
|
||||||
|
accountId := uuid.NewRandom().String()
|
||||||
|
_, err = AddAccount(tests.Context(), auth.Claims{}, test.MasterDB, AddAccountRequest{
|
||||||
|
UserID: user.ID,
|
||||||
|
AccountID: accountId,
|
||||||
|
Roles: []UserAccountRole{UserAccountRole_User},
|
||||||
|
}, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Log("\t\tGot :", err)
|
||||||
|
t.Fatalf("\t%s\tAddAccount failed.", tests.Failed)
|
||||||
|
}
|
||||||
|
|
||||||
// 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, now, user.Email, initPass)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -578,7 +566,7 @@ func TestUpdateUserPassword(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestUserCrud validates the full set of CRUD operations and ensures ACLs are correctly applied by claims.
|
// TestUserCrud validates the full set of CRUD operations for users and ensures ACLs are correctly applied by claims.
|
||||||
func TestUserCrud(t *testing.T) {
|
func TestUserCrud(t *testing.T) {
|
||||||
defer tests.Recover(t)
|
defer tests.Recover(t)
|
||||||
|
|
||||||
@@ -622,7 +610,6 @@ func TestUserCrud(t *testing.T) {
|
|||||||
PasswordSalt: user.PasswordSalt,
|
PasswordSalt: user.PasswordSalt,
|
||||||
PasswordHash: user.PasswordHash,
|
PasswordHash: user.PasswordHash,
|
||||||
PasswordReset: user.PasswordReset,
|
PasswordReset: user.PasswordReset,
|
||||||
Status: user.Status,
|
|
||||||
Timezone: user.Timezone,
|
Timezone: user.Timezone,
|
||||||
CreatedAt: user.CreatedAt,
|
CreatedAt: user.CreatedAt,
|
||||||
UpdatedAt: user.UpdatedAt,
|
UpdatedAt: user.UpdatedAt,
|
||||||
@@ -697,7 +684,6 @@ func TestUserCrud(t *testing.T) {
|
|||||||
PasswordSalt: user.PasswordSalt,
|
PasswordSalt: user.PasswordSalt,
|
||||||
PasswordHash: user.PasswordHash,
|
PasswordHash: user.PasswordHash,
|
||||||
PasswordReset: user.PasswordReset,
|
PasswordReset: user.PasswordReset,
|
||||||
Status: user.Status,
|
|
||||||
Timezone: user.Timezone,
|
Timezone: user.Timezone,
|
||||||
CreatedAt: user.CreatedAt,
|
CreatedAt: user.CreatedAt,
|
||||||
UpdatedAt: user.UpdatedAt,
|
UpdatedAt: user.UpdatedAt,
|
||||||
@@ -772,7 +758,6 @@ func TestUserCrud(t *testing.T) {
|
|||||||
PasswordSalt: user.PasswordSalt,
|
PasswordSalt: user.PasswordSalt,
|
||||||
PasswordHash: user.PasswordHash,
|
PasswordHash: user.PasswordHash,
|
||||||
PasswordReset: user.PasswordReset,
|
PasswordReset: user.PasswordReset,
|
||||||
Status: user.Status,
|
|
||||||
Timezone: user.Timezone,
|
Timezone: user.Timezone,
|
||||||
CreatedAt: user.CreatedAt,
|
CreatedAt: user.CreatedAt,
|
||||||
UpdatedAt: user.UpdatedAt,
|
UpdatedAt: user.UpdatedAt,
|
||||||
@@ -801,7 +786,7 @@ func TestUserCrud(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.
|
||||||
accountId := uuid.NewRandom().String()
|
accountId := uuid.NewRandom().String()
|
||||||
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: accountId,
|
||||||
Roles: []UserAccountRole{UserAccountRole_User},
|
Roles: []UserAccountRole{UserAccountRole_User},
|
||||||
@@ -840,7 +825,7 @@ func TestUserCrud(t *testing.T) {
|
|||||||
if err != nil && errors.Cause(err) != tt.updateErr {
|
if err != nil && errors.Cause(err) != tt.updateErr {
|
||||||
t.Logf("\t\tGot : %+v", err)
|
t.Logf("\t\tGot : %+v", err)
|
||||||
t.Logf("\t\tWant: %+v", tt.updateErr)
|
t.Logf("\t\tWant: %+v", tt.updateErr)
|
||||||
t.Fatalf("\t%s\tUpdate failed.", tests.Failed)
|
t.Fatalf("\t%s\tArchive failed.", tests.Failed)
|
||||||
} else if tt.updateErr == nil {
|
} else if tt.updateErr == nil {
|
||||||
// Trying to find the archived user with the includeArchived false should result in not found.
|
// Trying to find the archived user with the includeArchived false should result in not found.
|
||||||
_, err = FindById(ctx, tt.claims(user, accountId), test.MasterDB, user.ID, false)
|
_, err = FindById(ctx, tt.claims(user, accountId), test.MasterDB, user.ID, false)
|
||||||
@@ -883,6 +868,22 @@ 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.
|
||||||
|
{
|
||||||
|
// Build the delete SQL statement.
|
||||||
|
query := sqlbuilder.NewDeleteBuilder()
|
||||||
|
query.DeleteFrom(usersTableName)
|
||||||
|
|
||||||
|
// Execute the query with the provided context.
|
||||||
|
sql, args := query.Build()
|
||||||
|
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)
|
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
var users []*User
|
var users []*User
|
||||||
|
Reference in New Issue
Block a user