Skip to content

Commit

Permalink
MF- 249 - Fix auth user mock (#262)
Browse files Browse the repository at this point in the history
* MF-250 - Fix auth user mock

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Rename file

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Modify mocks

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Fix users endpoint tests

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Use array of users in mock

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Change names

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Fix user SDK tests

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Change names

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Use const

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Remuve redundant email

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Fix indentation

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

* MF-249 - Change names

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>

---------

Signed-off-by: zzokki81 <zoran.rebic@outlook.com>
  • Loading branch information
zzokki81 authored Aug 4, 2023
1 parent d36fbeb commit db94dfd
Show file tree
Hide file tree
Showing 6 changed files with 103 additions and 142 deletions.
42 changes: 18 additions & 24 deletions pkg/sdk/go/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,22 @@ const (
invalidEmail = "userexample.com"
userEmail = "user@example.com"
validPass = "validPass"
registerUser = "register@example.com"
)

var (
passRegex = regexp.MustCompile("^.{8,}$")
admin = users.User{Email: adminEmail, Password: validPass}
user = users.User{Email: userEmail, ID: "574106f7-030e-4881-8ab0-151195c29f94", Password: validPass, Status: "enabled"}
admin = users.User{Email: adminEmail, ID: "371106m2-131g-5286-2mc1-540295c29f95", Password: validPass, Status: "enabled"}
usersList = []users.User{admin, user}
)

func newUserService() users.Service {
usersRepo := mocks.NewUserRepository()
usersRepo := mocks.NewUserRepository(usersList)
hasher := mocks.NewHasher()

idProvider := uuid.New()
id, _ := idProvider.ID()
admin.ID = id

auth := mocks.NewAuthService("", map[string]users.User{adminEmail: admin})

admin.ID, _ = idProvider.ID()
auth := mocks.NewAuthService(admin.ID, usersList)
emailer := mocks.NewEmailer()

return users.New(usersRepo, hasher, auth, emailer, idProvider, passRegex)
Expand All @@ -64,7 +63,7 @@ func TestCreateUser(t *testing.T) {
TLSVerification: false,
}

sdkUser := sdk.User{Email: "new-user@example.com", Password: "password"}
sdkUser := sdk.User{Email: registerUser, Password: validPass}

token, err := svc.Login(context.Background(), admin)
require.Nil(t, err, fmt.Sprintf("unexpected error login: %s", err))
Expand Down Expand Up @@ -96,13 +95,13 @@ func TestCreateUser(t *testing.T) {
},
{
desc: "create user with empty password",
user: sdk.User{Email: "user2@example.com", Password: ""},
user: sdk.User{Email: registerUser, Password: ""},
token: token,
err: createError(sdk.ErrFailedCreation, http.StatusBadRequest),
},
{
desc: "create user without password",
user: sdk.User{Email: "user2@example.com"},
user: sdk.User{Email: registerUser},
token: token,
err: createError(sdk.ErrFailedCreation, http.StatusBadRequest),
},
Expand Down Expand Up @@ -130,15 +129,15 @@ func TestRegisterUser(t *testing.T) {
svc := newUserService()
ts := newUserServer(svc)
defer ts.Close()

sdkConf := sdk.Config{
UsersURL: ts.URL,
MsgContentType: contentType,
TLSVerification: false,
}

sdkUser := sdk.User{Email: "user@example.com", Password: "password"}

sdkUser := sdk.User{Email: registerUser, Password: validPass}
mainfluxSDK := sdk.NewSDK(sdkConf)

cases := []struct {
desc string
user sdk.User
Expand All @@ -161,12 +160,12 @@ func TestRegisterUser(t *testing.T) {
},
{
desc: "register user with empty password",
user: sdk.User{Email: "user2@example.com", Password: ""},
user: sdk.User{Email: registerUser, Password: ""},
err: createError(sdk.ErrFailedCreation, http.StatusBadRequest),
},
{
desc: "register user without password",
user: sdk.User{Email: "user2@example.com"},
user: sdk.User{Email: registerUser},
err: createError(sdk.ErrFailedCreation, http.StatusBadRequest),
},
{
Expand Down Expand Up @@ -198,14 +197,9 @@ func TestCreateToken(t *testing.T) {
}

mainfluxSDK := sdk.NewSDK(sdkConf)
sdkUser := sdk.User{Email: "user@example.com", Password: "password"}

token, err := svc.Login(context.Background(), admin)
require.Nil(t, err, fmt.Sprintf("unexpected error admin login: %s", err))
_, err = mainfluxSDK.CreateUser(token, sdkUser)
require.Nil(t, err, fmt.Sprintf("unexpected error creating use: %s", err))
sdkUser := sdk.User{Email: userEmail, Password: validPass}

token, err = svc.Login(context.Background(), users.User{Email: sdkUser.Email, Password: sdkUser.Password})
token, err := svc.Login(context.Background(), users.User{Email: sdkUser.Email, Password: sdkUser.Password})
require.Nil(t, err, fmt.Sprintf("unexpected error login: %s", err))

cases := []struct {
Expand All @@ -222,7 +216,7 @@ func TestCreateToken(t *testing.T) {
},
{
desc: "create token for non existing user",
user: sdk.User{Email: "user2@example.com", Password: "password"},
user: sdk.User{Email: registerUser, Password: "password"},
token: "",
err: createError(sdk.ErrFailedCreation, http.StatusUnauthorized),
},
Expand Down
5 changes: 3 additions & 2 deletions readers/api/endpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ var (
idProvider = uuid.New()

user = users.User{Email: userEmail, Password: validPass}
admin = users.User{ID: adminID, Email: adminEmail, Password: validPass}
admin = users.User{ID: adminID, Email: adminEmail, Password: validPass, Status: "enabled"}
usersList = []users.User{user, admin}
)

func newServer(repo readers.MessageRepository, tc mainflux.ThingsServiceClient, ac mainflux.AuthServiceClient) *httptest.Server {
Expand Down Expand Up @@ -89,7 +90,7 @@ func (tr testRequest) make() (*http.Response, error) {
return tr.client.Do(req)
}
func newAuthService() mainflux.AuthServiceClient {
return authmocks.NewAuthService(admin.ID, map[string]users.User{user.Email: user, admin.Email: admin})
return authmocks.NewAuthService(admin.ID, usersList)
}

func TestListChannelMessages(t *testing.T) {
Expand Down
59 changes: 19 additions & 40 deletions users/api/http/endpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,10 @@ const (
)

var (
user = users.User{Email: validEmail, Password: validPass, Status: "enabled"}
admin = users.User{Email: adminEmail, Password: validPass, Status: "enabled"}
user = users.User{Email: validEmail, ID: "574106f7-030e-4881-8ab0-151195c29f94", Password: validPass, Status: "enabled"}
admin = users.User{Email: adminEmail, ID: "371106m2-131g-5286-2mc1-540295c29f95", Password: validPass, Status: "enabled"}
newUser = users.User{Email: "newuser@example.com", Password: validPass, Status: "enabled"}
usersList = []users.User{admin, user}
notFoundRes = toJSON(apiutil.ErrorRes{Err: errors.ErrNotFound.Error()})
unauthRes = toJSON(apiutil.ErrorRes{Err: errors.ErrAuthentication.Error()})
weakPassword = toJSON(apiutil.ErrorRes{Err: users.ErrPasswordFormat.Error()})
Expand All @@ -55,7 +57,6 @@ var (
invalidRestPassRes = toJSON(apiutil.ErrorRes{Err: apiutil.ErrInvalidResetPass.Error()})
idProvider = uuid.New()
passRegex = regexp.MustCompile("^.{8,}$")
userAdmin = users.User{Email: adminEmail, ID: admin.ID, Password: validPass, Metadata: map[string]interface{}{"role": "user"}}
)

type testRequest struct {
Expand Down Expand Up @@ -84,10 +85,9 @@ func (tr testRequest) make() (*http.Response, error) {
}

func newService() users.Service {
usersRepo := mocks.NewUserRepository()
usersRepo := mocks.NewUserRepository(usersList)
hasher := mocks.NewHasher()

auth := mocks.NewAuthService(admin.ID, map[string]users.User{admin.Email: admin})
auth := mocks.NewAuthService(admin.ID, usersList)
email := mocks.NewEmailer()
return users.New(usersRepo, hasher, auth, email, idProvider, passRegex)
}
Expand All @@ -102,19 +102,13 @@ func toJSON(data interface{}) string {
return string(jsonData)
}

func TestInit(t *testing.T) {
id, err := idProvider.ID()
require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err))
admin.ID = id
}

func TestSelfRegister(t *testing.T) {
svc := newService()
ts := newServer(svc)
defer ts.Close()
client := ts.Client()

data := toJSON(user)
data := toJSON(newUser)
invalidData := toJSON(users.User{Email: invalidEmail, Password: validPass})
invalidPasswordData := toJSON(users.User{Email: validEmail, Password: invalidPass})
invalidFieldData := fmt.Sprintf(`{"email": "%s", "pass": "%s"}`, user.Email, user.Password)
Expand Down Expand Up @@ -157,7 +151,7 @@ func TestRegister(t *testing.T) {
ts := newServer(svc)
defer ts.Close()
client := ts.Client()
data := toJSON(user)
data := toJSON(newUser)
invalidData := toJSON(users.User{Email: invalidEmail, Password: validPass})
invalidPasswordData := toJSON(users.User{Email: validEmail, Password: invalidPass})
invalidFieldData := fmt.Sprintf(`{"email": "%s", "pass": "%s"}`, user.Email, user.Password)
Expand Down Expand Up @@ -204,7 +198,7 @@ func TestLogin(t *testing.T) {
defer ts.Close()
client := ts.Client()

auth := mocks.NewAuthService("", map[string]users.User{})
auth := mocks.NewAuthService("", usersList)

data := toJSON(user)
invalidEmailData := toJSON(users.User{
Expand All @@ -220,9 +214,6 @@ func TestLogin(t *testing.T) {
Password: validPass,
})

_, err := svc.SelfRegister(context.Background(), user)
require.Nil(t, err, fmt.Sprintf("register user got unexpected error: %s", err))

mfxTok, err := auth.Issue(context.Background(), &mainflux.IssueReq{Id: user.ID, Email: user.Email, Type: 0})
require.Nil(t, err, fmt.Sprintf("issue token for user got unexpected error: %s", err))
token := mfxTok.GetValue()
Expand Down Expand Up @@ -270,10 +261,7 @@ func TestUser(t *testing.T) {
defer ts.Close()
client := ts.Client()

auth := mocks.NewAuthService("", map[string]users.User{})

userID, err := svc.SelfRegister(context.Background(), user)
require.Nil(t, err, fmt.Sprintf("register user got unexpected error: %s", err))
auth := mocks.NewAuthService("", usersList)

tkn, err := auth.Issue(context.Background(), &mainflux.IssueReq{Id: user.ID, Email: user.Email, Type: 0})
require.Nil(t, err, fmt.Sprintf("issue token got unexpected error: %s", err))
Expand All @@ -293,7 +281,7 @@ func TestUser(t *testing.T) {
req := testRequest{
client: client,
method: http.MethodGet,
url: fmt.Sprintf("%s/users/%s", ts.URL, userID),
url: fmt.Sprintf("%s/users/%s", ts.URL, user.ID),
token: tc.token,
}
res, err := req.make()
Expand All @@ -313,11 +301,11 @@ func TestListUsers(t *testing.T) {
defer ts.Close()
client := ts.Client()

token, err := svc.Login(context.Background(), userAdmin)
token, err := svc.Login(context.Background(), admin)
require.Nil(t, err, fmt.Sprintf("unexpected error: %s", err))

var data []viewUserRes
data = append(data, viewUserRes{admin.ID, userAdmin.Email})
data = append(data, viewUserRes{admin.ID, admin.Email}, viewUserRes{user.ID, user.Email})
for i := 1; i < userNum; i++ {
id := fmt.Sprintf("%s%012d", prefix, i)
email := fmt.Sprintf("users%d@example.com", i)
Expand All @@ -327,10 +315,10 @@ func TestListUsers(t *testing.T) {
Password: "password",
Status: "enabled",
}
usr, err := svc.Register(context.Background(), token, user)
usersList, err := svc.Register(context.Background(), token, user)
require.Nil(t, err, fmt.Sprintf("unexpected error: %s", err))

data = append(data, viewUserRes{usr, email})
data = append(data, viewUserRes{usersList, email})
}

sort.Slice(data, func(i, j int) bool {
Expand Down Expand Up @@ -486,9 +474,6 @@ func TestPasswordResetRequest(t *testing.T) {
httpapi.MailSent,
})

_, err := svc.SelfRegister(context.Background(), user)
require.Nil(t, err, fmt.Sprintf("register user got unexpected error: %s", err))

cases := []struct {
desc string
req string
Expand Down Expand Up @@ -534,12 +519,9 @@ func TestPasswordReset(t *testing.T) {
ConfPass string `json:"confirm_password,omitempty"`
}{}

auth := mocks.NewAuthService("", map[string]users.User{})

id, err := svc.SelfRegister(context.Background(), user)
require.Nil(t, err, fmt.Sprintf("register user got unexpected error: %s", err))
auth := mocks.NewAuthService("", usersList)

tkn, err := auth.Issue(context.Background(), &mainflux.IssueReq{Id: id, Email: user.Email, Type: 0})
tkn, err := auth.Issue(context.Background(), &mainflux.IssueReq{Id: user.ID, Email: user.Email, Type: 0})
require.Nil(t, err, fmt.Sprintf("issue user token error: %s", err))

token := tkn.GetValue()
Expand Down Expand Up @@ -605,18 +587,15 @@ func TestPasswordChange(t *testing.T) {
defer ts.Close()
client := ts.Client()

auth := mocks.NewAuthService("", map[string]users.User{})
auth := mocks.NewAuthService("", usersList)

reqData := struct {
Token string `json:"token,omitempty"`
Password string `json:"password,omitempty"`
OldPassw string `json:"old_password,omitempty"`
}{}

id, err := svc.SelfRegister(context.Background(), user)
require.Nil(t, err, fmt.Sprintf("register user got unexpected error: %s", err))

tkn, err := auth.Issue(context.Background(), &mainflux.IssueReq{Id: id, Email: user.Email, Type: 0})
tkn, err := auth.Issue(context.Background(), &mainflux.IssueReq{Id: user.ID, Email: user.Email, Type: 0})
require.Nil(t, err, fmt.Sprintf("issue token got unexpected error: %s", err))
token := tkn.GetValue()

Expand Down
30 changes: 14 additions & 16 deletions users/mocks/authn.go → users/mocks/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,44 +8,42 @@ import (

"github.com/MainfluxLabs/mainflux"
"github.com/MainfluxLabs/mainflux/pkg/errors"
user "github.com/MainfluxLabs/mainflux/users"
"github.com/MainfluxLabs/mainflux/users"
"github.com/golang/protobuf/ptypes/empty"
"google.golang.org/grpc"
)

var _ mainflux.AuthServiceClient = (*authServiceMock)(nil)

type authServiceMock struct {
authz map[string]string
roles map[string]string
usersByEmail map[string]users.User
}

// NewAuthService creates mock of users service.
func NewAuthService(adminID string, users map[string]user.User) mainflux.AuthServiceClient {
authz := make(map[string]string)
authz["root"] = adminID
func NewAuthService(adminID string, userList []users.User) mainflux.AuthServiceClient {
usersByEmail := make(map[string]users.User)
roles := map[string]string{"root": adminID}

mockUsers = users
if mockUsersByID == nil {
mockUsersByID = make(map[string]user.User)
}
for _, u := range users {
mockUsersByID[u.ID] = u
for _, user := range userList {
usersByEmail[user.Email] = user
}

return &authServiceMock{
authz: authz,
roles: roles,
usersByEmail: usersByEmail,
}
}

func (svc authServiceMock) Identify(ctx context.Context, in *mainflux.Token, opts ...grpc.CallOption) (*mainflux.UserIdentity, error) {
if u, ok := mockUsers[in.Value]; ok {
if u, ok := svc.usersByEmail[in.Value]; ok {
return &mainflux.UserIdentity{Id: u.ID, Email: u.Email}, nil
}
return nil, errors.ErrAuthentication
}

func (svc authServiceMock) Issue(ctx context.Context, in *mainflux.IssueReq, opts ...grpc.CallOption) (*mainflux.Token, error) {
if u, ok := mockUsers[in.GetEmail()]; ok {
if u, ok := svc.usersByEmail[in.GetEmail()]; ok {
switch in.Type {
default:
return &mainflux.Token{Value: u.Email}, nil
Expand All @@ -55,12 +53,12 @@ func (svc authServiceMock) Issue(ctx context.Context, in *mainflux.IssueReq, opt
}

func (svc authServiceMock) Authorize(ctx context.Context, req *mainflux.AuthorizeReq, _ ...grpc.CallOption) (r *empty.Empty, err error) {
u, ok := mockUsers[req.Token]
u, ok := svc.usersByEmail[req.Token]
if !ok {
return &empty.Empty{}, errors.ErrAuthentication
}

if svc.authz["root"] != u.ID {
if svc.roles["root"] != u.ID {
return &empty.Empty{}, errors.ErrAuthorization
}

Expand Down
Loading

0 comments on commit db94dfd

Please sign in to comment.