1
0
mirror of https://github.com/raseels-repos/golang-saas-starter-kit.git synced 2025-06-15 00:15:15 +02:00

Complated web-api crud endpoints and unittests. unittest for find

endpoints still need to be implemented.
This commit is contained in:
Lee Brown
2019-06-27 04:48:18 -08:00
parent 48ae19bd6a
commit 24dd0dff42
27 changed files with 4062 additions and 1529 deletions

View File

@ -568,7 +568,7 @@ func Delete(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, accountID
// Defines the struct to apply validation
req := struct {
ID string `validate:"required,uuid"`
ID string `json:"id" validate:"required,uuid"`
}{
ID: accountID,
}

View File

@ -151,12 +151,12 @@ func TestCreateValidation(t *testing.T) {
func(req AccountCreateRequest, res *Account) *Account {
return nil
},
errors.New("Key: 'AccountCreateRequest.Name' Error:Field validation for 'Name' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.Address1' Error:Field validation for 'Address1' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.City' Error:Field validation for 'City' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.Region' Error:Field validation for 'Region' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.Country' Error:Field validation for 'Country' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.Zipcode' Error:Field validation for 'Zipcode' failed on the 'required' tag"),
errors.New("Key: 'AccountCreateRequest.name' Error:Field validation for 'name' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.address1' Error:Field validation for 'address1' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.city' Error:Field validation for 'city' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.region' Error:Field validation for 'region' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.country' Error:Field validation for 'country' failed on the 'required' tag\n" +
"Key: 'AccountCreateRequest.zipcode' Error:Field validation for 'zipcode' failed on the 'required' tag"),
},
{"Default Timezone & Status",
@ -204,7 +204,7 @@ func TestCreateValidation(t *testing.T) {
func(req AccountCreateRequest, res *Account) *Account {
return nil
},
errors.New("Key: 'AccountCreateRequest.Status' Error:Field validation for 'Status' failed on the 'oneof' tag"),
errors.New("Key: 'AccountCreateRequest.status' Error:Field validation for 'status' failed on the 'oneof' tag"),
},
}
@ -286,7 +286,7 @@ func TestCreateValidationNameUnique(t *testing.T) {
Country: "USA",
Zipcode: "99686",
}
expectedErr := errors.New("Key: 'AccountCreateRequest.Name' Error:Field validation for 'Name' failed on the 'unique' tag")
expectedErr := errors.New("Key: 'AccountCreateRequest.name' Error:Field validation for 'name' failed on the 'unique' tag")
_, err = Create(ctx, auth.Claims{}, test.MasterDB, req2, now)
if err == nil {
t.Logf("\t\tWant: %+v", expectedErr)
@ -403,7 +403,7 @@ func TestUpdateValidation(t *testing.T) {
var accountTests = []accountTest{
{"Required Fields",
AccountUpdateRequest{},
errors.New("Key: 'AccountUpdateRequest.ID' Error:Field validation for 'ID' failed on the 'required' tag"),
errors.New("Key: 'AccountUpdateRequest.id' Error:Field validation for 'id' failed on the 'required' tag"),
},
}
@ -413,7 +413,7 @@ func TestUpdateValidation(t *testing.T) {
ID: uuid.NewRandom().String(),
Status: &invalidStatus,
},
errors.New("Key: 'AccountUpdateRequest.Status' Error:Field validation for 'Status' failed on the 'oneof' tag"),
errors.New("Key: 'AccountUpdateRequest.status' Error:Field validation for 'status' failed on the 'oneof' tag"),
})
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
@ -494,7 +494,7 @@ func TestUpdateValidationNameUnique(t *testing.T) {
ID: account2.ID,
Name: &account1.Name,
}
expectedErr := errors.New("Key: 'AccountUpdateRequest.Name' Error:Field validation for 'Name' failed on the 'unique' tag")
expectedErr := errors.New("Key: 'AccountUpdateRequest.name' Error:Field validation for 'name' failed on the 'unique' tag")
err = Update(ctx, auth.Claims{}, test.MasterDB, updateReq, now)
if err == nil {
t.Logf("\t\tWant: %+v", expectedErr)

View File

@ -119,6 +119,3 @@ func parseAuthHeader(bearerStr string) (string, error) {
return split[1], nil
}

View File

@ -31,7 +31,7 @@ type Error struct {
func NewRequestError(err error, status int) error {
// if its a validation error then
if verr, ok := NewValidationError(err); ok {
if verr, ok := NewValidationError(err); ok {
return verr
}

View File

@ -83,7 +83,7 @@ func Decode(r *http.Request, val interface{}) error {
}
if err := validate.Struct(val); err != nil {
verr, _ := NewValidationError(err)
verr, _ := NewValidationError(err)
return verr
}
@ -130,7 +130,6 @@ func ExtractWhereArgs(where string) (string, []interface{}, error) {
return where, vals, nil
}
func RequestIsJson(r *http.Request) bool {
if r == nil {
return false
@ -155,4 +154,3 @@ func RequestIsJson(r *http.Request) bool {
return false
}

View File

@ -199,7 +199,7 @@ func Read(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, id string, i
res, err := find(ctx, claims, dbConn, query, []interface{}{}, includedArchived)
if res == nil || len(res) == 0 {
err = errors.WithMessagef(ErrNotFound, "account %s not found", id)
err = errors.WithMessagef(ErrNotFound, "project %s not found", id)
return nil, err
} else if err != nil {
return nil, err
@ -424,8 +424,10 @@ func Delete(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, id string)
// Defines the struct to apply validation
req := struct {
ID string `validate:"required,uuid"`
}{}
ID string `json:"id" validate:"required,uuid"`
}{
ID: id,
}
// Validate the request.
v := web.NewValidator()

View File

@ -61,4 +61,3 @@ func (m *SignupResult) Response(ctx context.Context) *SignupResponse {
return r
}

View File

@ -32,7 +32,6 @@ func Signup(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, req Signup
return nil, err
}
f := func(fl validator.FieldLevel) bool {
if fl.Field().String() == "invalid" {
return false

View File

@ -40,15 +40,15 @@ func TestSignupValidation(t *testing.T) {
func(req SignupRequest, res *SignupResult) *SignupResult {
return nil
},
errors.New("Key: 'SignupRequest.Account.Name' Error:Field validation for 'Name' failed on the 'required' tag\n" +
"Key: 'SignupRequest.Account.Address1' Error:Field validation for 'Address1' failed on the 'required' tag\n" +
"Key: 'SignupRequest.Account.City' Error:Field validation for 'City' failed on the 'required' tag\n" +
"Key: 'SignupRequest.Account.Region' Error:Field validation for 'Region' failed on the 'required' tag\n" +
"Key: 'SignupRequest.Account.Country' Error:Field validation for 'Country' failed on the 'required' tag\n" +
"Key: 'SignupRequest.Account.Zipcode' Error:Field validation for 'Zipcode' failed on the 'required' tag\n" +
"Key: 'SignupRequest.User.Name' Error:Field validation for 'Name' failed on the 'required' tag\n" +
"Key: 'SignupRequest.User.Email' Error:Field validation for 'Email' failed on the 'required' tag\n" +
"Key: 'SignupRequest.User.Password' Error:Field validation for 'Password' failed on the 'required' tag"),
errors.New("Key: 'SignupRequest.account.name' Error:Field validation for 'name' failed on the 'required' tag\n" +
"Key: 'SignupRequest.account.address1' Error:Field validation for 'address1' failed on the 'required' tag\n" +
"Key: 'SignupRequest.account.city' Error:Field validation for 'city' failed on the 'required' tag\n" +
"Key: 'SignupRequest.account.region' Error:Field validation for 'region' failed on the 'required' tag\n" +
"Key: 'SignupRequest.account.country' Error:Field validation for 'country' failed on the 'required' tag\n" +
"Key: 'SignupRequest.account.zipcode' Error:Field validation for 'zipcode' failed on the 'required' tag\n" +
"Key: 'SignupRequest.user.name' Error:Field validation for 'name' failed on the 'required' tag\n" +
"Key: 'SignupRequest.user.email' Error:Field validation for 'email' failed on the 'required' tag\n" +
"Key: 'SignupRequest.user.password' Error:Field validation for 'password' failed on the 'required' tag"),
},
}

View File

@ -72,8 +72,8 @@ func SwitchAccount(ctx context.Context, dbConn *sqlx.DB, tknGen TokenGenerator,
// 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 string `json:"user_id" validate:"required,uuid"`
AccountID string `json:"account_id" validate:"required,uuid"`
}{
UserID: claims.Subject,
AccountID: accountID,

View File

@ -90,35 +90,52 @@ func CanReadUser(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userI
// CanModifyUser determines if claims has the authority to modify the specified user ID.
func CanModifyUser(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userID string) error {
// If the request has claims from a specific account, ensure that the user
// has the correct access to the account.
// If the request has claims from a specific user, ensure that the user
// has the correct role for creating a new user.
if claims.Subject != "" && claims.Subject != userID {
// When the claims Audience - AccountID - does not match the requested account, the
// claims Audience - AccountID - should have a record with an admin role.
// select id from users_accounts where account_id = [claims.Audience] and user_id = [userID] and any (roles) = 'admin'
query := sqlbuilder.NewSelectBuilder().Select("id").From(userAccountTableName)
query.Where(query.And(
query.Equal("account_id", claims.Audience),
query.Equal("user_id", userID),
"'"+auth.RoleAdmin+"' = ANY (roles)",
))
queryStr, args := query.Build()
queryStr = dbConn.Rebind(queryStr)
var userAccountId string
err := dbConn.QueryRowContext(ctx, queryStr, args...).Scan(&userAccountId)
if err != nil && err != sql.ErrNoRows {
err = errors.Wrapf(err, "query - %s", query.String())
// Users with the role of admin are ony allows to create users.
if !claims.HasRole(auth.RoleAdmin) {
err := errors.WithStack(ErrForbidden)
return err
}
// When there is no userAccount ID returned, then the current user does not have access
// to the specified account.
if userAccountId == "" {
return errors.WithStack(ErrForbidden)
}
}
if err := CanReadUser(ctx, claims, dbConn, userID); err != nil {
return err
}
// TODO: Review, this doesn't seem correct, replaced with above.
/*
// If the request has claims from a specific account, ensure that the user
// has the correct access to the account.
if claims.Subject != "" && claims.Subject != userID {
// When the claims Audience - AccountID - does not match the requested account, the
// claims Audience - AccountID - should have a record with an admin role.
// select id from users_accounts where account_id = [claims.Audience] and user_id = [userID] and any (roles) = 'admin'
query := sqlbuilder.NewSelectBuilder().Select("id").From(userAccountTableName)
query.Where(query.And(
query.Equal("account_id", claims.Audience),
query.Equal("user_id", userID),
"'"+auth.RoleAdmin+"' = ANY (roles)",
))
queryStr, args := query.Build()
queryStr = dbConn.Rebind(queryStr)
var userAccountId string
err := dbConn.QueryRowContext(ctx, queryStr, args...).Scan(&userAccountId)
if err != nil && err != sql.ErrNoRows {
err = errors.Wrapf(err, "query - %s", query.String())
return err
}
// When there is no userAccount ID returned, then the current user does not have access
// to the specified account.
if userAccountId == "" {
return errors.WithStack(ErrForbidden)
}
}
*/
return nil
}
@ -598,7 +615,7 @@ func Delete(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, userID str
// Defines the struct to apply validation
req := struct {
ID string `validate:"required,uuid"`
ID string `json:"id" validate:"required,uuid"`
}{
ID: userID,
}

View File

@ -1,7 +1,6 @@
package user
import (
"github.com/lib/pq"
"math/rand"
"os"
"strings"
@ -13,6 +12,7 @@ import (
"github.com/dgrijalva/jwt-go"
"github.com/google/go-cmp/cmp"
"github.com/huandu/go-sqlbuilder"
"github.com/lib/pq"
"github.com/pborman/uuid"
"github.com/pkg/errors"
)
@ -149,9 +149,9 @@ func TestCreateValidation(t *testing.T) {
func(req UserCreateRequest, res *User) *User {
return nil
},
errors.New("Key: 'UserCreateRequest.Name' Error:Field validation for 'Name' failed on the 'required' tag\n" +
"Key: 'UserCreateRequest.Email' Error:Field validation for 'Email' failed on the 'required' tag\n" +
"Key: 'UserCreateRequest.Password' Error:Field validation for 'Password' failed on the 'required' tag"),
errors.New("Key: 'UserCreateRequest.name' Error:Field validation for 'name' failed on the 'required' tag\n" +
"Key: 'UserCreateRequest.email' Error:Field validation for 'email' failed on the 'required' tag\n" +
"Key: 'UserCreateRequest.password' Error:Field validation for 'password' failed on the 'required' tag"),
},
{"Valid Email",
UserCreateRequest{
@ -163,7 +163,7 @@ func TestCreateValidation(t *testing.T) {
func(req UserCreateRequest, res *User) *User {
return nil
},
errors.New("Key: 'UserCreateRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag"),
errors.New("Key: 'UserCreateRequest.email' Error:Field validation for 'email' failed on the 'email' tag"),
},
{"Passwords Match",
UserCreateRequest{
@ -175,7 +175,7 @@ func TestCreateValidation(t *testing.T) {
func(req UserCreateRequest, res *User) *User {
return nil
},
errors.New("Key: 'UserCreateRequest.PasswordConfirm' Error:Field validation for 'PasswordConfirm' failed on the 'eqfield' tag"),
errors.New("Key: 'UserCreateRequest.password_confirm' Error:Field validation for 'password_confirm' failed on the 'eqfield' tag"),
},
{"Default Timezone",
UserCreateRequest{
@ -276,7 +276,7 @@ func TestCreateValidationEmailUnique(t *testing.T) {
Password: "W0rkL1fe#",
PasswordConfirm: "W0rkL1fe#",
}
expectedErr := errors.New("Key: 'UserCreateRequest.Email' Error:Field validation for 'Email' failed on the 'unique' tag")
expectedErr := errors.New("Key: 'UserCreateRequest.email' Error:Field validation for 'email' failed on the 'unique' tag")
_, err = Create(ctx, auth.Claims{}, test.MasterDB, req2, now)
if err == nil {
t.Logf("\t\tWant: %+v", expectedErr)
@ -384,7 +384,7 @@ func TestUpdateValidation(t *testing.T) {
var userTests = []userTest{
{"Required Fields",
UserUpdateRequest{},
errors.New("Key: 'UserUpdateRequest.ID' Error:Field validation for 'ID' failed on the 'required' tag"),
errors.New("Key: 'UserUpdateRequest.id' Error:Field validation for 'id' failed on the 'required' tag"),
},
}
@ -394,7 +394,7 @@ func TestUpdateValidation(t *testing.T) {
ID: uuid.NewRandom().String(),
Email: &invalidEmail,
},
errors.New("Key: 'UserUpdateRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag"),
errors.New("Key: 'UserUpdateRequest.email' Error:Field validation for 'email' failed on the 'email' tag"),
})
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
@ -469,7 +469,7 @@ func TestUpdateValidationEmailUnique(t *testing.T) {
ID: user2.ID,
Email: &user1.Email,
}
expectedErr := errors.New("Key: 'UserUpdateRequest.Email' Error:Field validation for 'Email' failed on the 'unique' tag")
expectedErr := errors.New("Key: 'UserUpdateRequest.email' Error:Field validation for 'email' failed on the 'unique' tag")
err = Update(ctx, auth.Claims{}, test.MasterDB, updateReq, now)
if err == nil {
t.Logf("\t\tWant: %+v", expectedErr)
@ -533,8 +533,8 @@ func TestUpdatePassword(t *testing.T) {
}
// Ensure validation is working by trying UpdatePassword with an empty request.
expectedErr := errors.New("Key: 'UserUpdatePasswordRequest.ID' Error:Field validation for 'ID' failed on the 'required' tag\n" +
"Key: 'UserUpdatePasswordRequest.Password' Error:Field validation for 'Password' failed on the 'required' tag")
expectedErr := errors.New("Key: 'UserUpdatePasswordRequest.id' Error:Field validation for 'id' failed on the 'required' tag\n" +
"Key: 'UserUpdatePasswordRequest.password' Error:Field validation for 'password' failed on the 'required' tag")
err = UpdatePassword(ctx, auth.Claims{}, test.MasterDB, UserUpdatePasswordRequest{}, now)
if err == nil {
t.Logf("\t\tWant: %+v", expectedErr)

View File

@ -53,7 +53,7 @@ func (m *UserAccount) Response(ctx context.Context) *UserAccountResponse {
UserID: m.UserID,
AccountID: m.AccountID,
Roles: m.Roles,
Status: web.NewEnumResponse(ctx, m.Status, UserAccountRole_Values),
Status: web.NewEnumResponse(ctx, m.Status, UserAccountStatus_Values),
CreatedAt: web.NewTimeResponse(ctx, m.CreatedAt),
UpdatedAt: web.NewTimeResponse(ctx, m.UpdatedAt),
}
@ -82,7 +82,7 @@ type UserAccountCreateRequest struct {
type UserAccountUpdateRequest struct {
UserID string `json:"user_id" validate:"required,uuid" example:"d69bdef7-173f-4d29-b52c-3edc60baf6a2"`
AccountID string `json:"account_id" validate:"required,uuid" example:"c4653bf9-5978-48b7-89c5-95704aebb7e2"`
Roles *UserAccountRoles `json:"roles,omitempty" validate:"required,dive,oneof=admin user" enums:"admin,user" swaggertype:"array,string" example:"user"`
Roles *UserAccountRoles `json:"roles,omitempty" validate:"omitempty,dive,oneof=admin user" enums:"admin,user" swaggertype:"array,string" example:"user"`
Status *UserAccountStatus `json:"status,omitempty" validate:"omitempty,oneof=active invited disabled" enums:"active,invited,disabled" swaggertype:"string" example:"disabled"`
unArchive bool `json:"-"` // Internal use only.
}

View File

@ -300,7 +300,7 @@ func Read(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, id string, i
res, err := find(ctx, claims, dbConn, query, []interface{}{}, includedArchived)
if res == nil || len(res) == 0 {
err = errors.WithMessagef(ErrNotFound, "account %s not found", id)
err = errors.WithMessagef(ErrNotFound, "user account %s not found", id)
return nil, err
} else if err != nil {
return nil, err

View File

@ -152,9 +152,9 @@ func TestCreateValidation(t *testing.T) {
func(req UserAccountCreateRequest, res *UserAccount) *UserAccount {
return nil
},
errors.New("Key: 'UserAccountCreateRequest.UserID' Error:Field validation for 'UserID' failed on the 'required' tag\n" +
"Key: 'UserAccountCreateRequest.AccountID' Error:Field validation for 'AccountID' failed on the 'required' tag\n" +
"Key: 'UserAccountCreateRequest.Roles' Error:Field validation for 'Roles' failed on the 'required' tag"),
errors.New("Key: 'UserAccountCreateRequest.user_id' Error:Field validation for 'user_id' failed on the 'required' tag\n" +
"Key: 'UserAccountCreateRequest.account_id' Error:Field validation for 'account_id' failed on the 'required' tag\n" +
"Key: 'UserAccountCreateRequest.roles' Error:Field validation for 'roles' failed on the 'required' tag"),
},
{"Valid Role",
UserAccountCreateRequest{
@ -165,7 +165,7 @@ func TestCreateValidation(t *testing.T) {
func(req UserAccountCreateRequest, res *UserAccount) *UserAccount {
return nil
},
errors.New("Key: 'UserAccountCreateRequest.Roles[0]' Error:Field validation for 'Roles[0]' failed on the 'oneof' tag"),
errors.New("Key: 'UserAccountCreateRequest.roles[0]' Error:Field validation for 'roles[0]' failed on the 'oneof' tag"),
},
{"Valid Status",
UserAccountCreateRequest{
@ -177,7 +177,7 @@ func TestCreateValidation(t *testing.T) {
func(req UserAccountCreateRequest, res *UserAccount) *UserAccount {
return nil
},
errors.New("Key: 'UserAccountCreateRequest.Status' Error:Field validation for 'Status' failed on the 'oneof' tag"),
errors.New("Key: 'UserAccountCreateRequest.status' Error:Field validation for 'status' failed on the 'oneof' tag"),
},
{"Default Status",
UserAccountCreateRequest{
@ -373,9 +373,8 @@ func TestUpdateValidation(t *testing.T) {
}{
{"Required Fields",
UserAccountUpdateRequest{},
errors.New("Key: 'UserAccountUpdateRequest.UserID' Error:Field validation for 'UserID' failed on the 'required' tag\n" +
"Key: 'UserAccountUpdateRequest.AccountID' Error:Field validation for 'AccountID' failed on the 'required' tag\n" +
"Key: 'UserAccountUpdateRequest.Roles' Error:Field validation for 'Roles' failed on the 'required' tag"),
errors.New("Key: 'UserAccountUpdateRequest.user_id' Error:Field validation for 'user_id' failed on the 'required' tag\n" +
"Key: 'UserAccountUpdateRequest.account_id' Error:Field validation for 'account_id' failed on the 'required' tag"),
},
{"Valid Role",
UserAccountUpdateRequest{
@ -383,7 +382,7 @@ func TestUpdateValidation(t *testing.T) {
AccountID: uuid.NewRandom().String(),
Roles: &UserAccountRoles{invalidRole},
},
errors.New("Key: 'UserAccountUpdateRequest.Roles[0]' Error:Field validation for 'Roles[0]' failed on the 'oneof' tag"),
errors.New("Key: 'UserAccountUpdateRequest.roles[0]' Error:Field validation for 'roles[0]' failed on the 'oneof' tag"),
},
{"Valid Status",
@ -393,7 +392,7 @@ func TestUpdateValidation(t *testing.T) {
Roles: &UserAccountRoles{UserAccountRole_User},
Status: &invalidStatus,
},
errors.New("Key: 'UserAccountUpdateRequest.Status' Error:Field validation for 'Status' failed on the 'oneof' tag"),
errors.New("Key: 'UserAccountUpdateRequest.status' Error:Field validation for 'status' failed on the 'oneof' tag"),
},
}