Skip to content

Commit

Permalink
Merge pull request #30 from voltgizerz/felix_11_improvement_refactor_…
Browse files Browse the repository at this point in the history
…code_core

Refactor core code for auth
  • Loading branch information
voltgizerz committed Jun 27, 2024
2 parents 90faac0 + 8988f76 commit 0c04215
Show file tree
Hide file tree
Showing 16 changed files with 487 additions and 244 deletions.
8 changes: 4 additions & 4 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ func main() {
menuRepo := repository.NewMenuRepository(repoOpts)

// Initialize Services
userService := service.NewUserService(interactor.UserService{
AuthService: authJWT,
authService := service.NewAuthService(interactor.AuthService{
JWTService: authJWT,
UserRepository: userRepo,
})

Expand All @@ -63,8 +63,8 @@ func main() {
})

// Initialize Handlers
authHandler := handler.NewAuthHandler(interactor.UserHandler{
UserService: userService,
authHandler := handler.NewAuthHandler(interactor.AuthHandler{
AuthService: authService,
})

menuHandler := handler.NewMenuHandler(interactor.MenuHandler{
Expand Down
13 changes: 7 additions & 6 deletions internal/app/api/handler/auth_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ import (
)

type AuthHandler struct {
userService ports.IUserService
authService ports.IAuthService
}

func NewAuthHandler(i interactor.UserHandler) *AuthHandler {
func NewAuthHandler(i interactor.AuthHandler) *AuthHandler {
return &AuthHandler{
userService: i.UserService,
authService: i.AuthService,
}
}

Expand All @@ -42,7 +42,7 @@ func (h *AuthHandler) Login(c fiber.Ctx) error {
return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}

userLoginData, err := h.userService.Login(ctx, req.Username, req.Password)
dataLogin, err := h.authService.Login(ctx, req.Username, req.Password)
if err != nil {
if err == sql.ErrNoRows {
return SendErrorResp(c, fiber.StatusUnauthorized, constants.ErrMsgUsernameNotFound)
Expand All @@ -51,7 +51,7 @@ func (h *AuthHandler) Login(c fiber.Ctx) error {
return SendErrorResp(c, fiber.StatusUnauthorized, constants.ErrMsgInvalidUsernameOrPassword)
}

return SendSuccessResp(c, fiber.StatusOK, "Success", userLoginData)
return SendSuccessResp(c, fiber.StatusOK, "Success", dataLogin)
}

func (h *AuthHandler) Register(c fiber.Ctx) error {
Expand All @@ -64,6 +64,7 @@ func (h *AuthHandler) Register(c fiber.Ctx) error {
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, "Invalid request body.")
}


err = validator.New().StructCtx(ctx, req)
if err != nil {
Expand All @@ -83,7 +84,7 @@ func (h *AuthHandler) Register(c fiber.Ctx) error {
Username: req.Username,
}

result, err := h.userService.Register(ctx, *userData)
result, err := h.authService.Register(ctx, *userData)
if err != nil {
return SendErrorResp(c, fiber.StatusBadRequest, err.Error())
}
Expand Down
89 changes: 36 additions & 53 deletions internal/app/api/handler/auth_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,71 +3,54 @@ package handler
import (
"testing"

"github.com/bytedance/sonic"
"github.com/gofiber/fiber/v3"
)

// func TestUserHandler_Login(t *testing.T) {
// app := fiber.New()
// mockCtx := app.AcquireCtx(&fasthttp.RequestCtx{})
// mockCtx.Request().SetBodyString(`{"username":"user","password":"password"}`)

// type args struct {
// c fiber.Ctx
// }
// tests := []struct {
// name string
// args args
// wantErr bool
// wantCode int
// setup func(mockObj *MockObject)
// }{{
// name: "SUCCESS - Login",
// args: args{c: mockCtx},
// setup: func(mockObj *MockObject) {
// },
// wantCode: fiber.StatusOK,
// }}
// for _, tt := range tests {
// ctrl, mockObj := NewMock(t)
// if tt.setup != nil {
// tt.setup(mockObj)
// }
// defer ctrl.Finish()
"github.com/valyala/fasthttp"

// authHandler := &AuthHandler{
// userService: mockObj.MockUserService,
// }

// t.Run(tt.name, func(t *testing.T) {
// if err := authHandler.Login(tt.args.c); (err != nil) != tt.wantErr {
// t.Errorf("AuthHandler.Login() error = %v, wantErr %v", err, tt.wantErr)
// }

// var responseBody successResponse
// err := json.Unmarshal(tt.args.c.Response().Body(), &responseBody)
// require.NoError(t, err)
// logger.Log.Println(responseBody)
// assert.Equal(t, responseBody.Code, tt.wantCode)
// assert.True(t, gock.IsDone())
// })
// }
// }
"github.com/voltgizerz/POS-restaurant/internal/app/constants"
"github.com/voltgizerz/POS-restaurant/internal/app/entity"
)

func TestAuthHandler_Login(t *testing.T) {
type args struct {
c fiber.Ctx
}
app := fiber.New()

tests := []struct {
name string
h *AuthHandler
args args
wantErr bool
setup func(mockObj *MockObject) fiber.Ctx
}{
// TODO: Add test cases.
{
name: "SUCCESS - Login",
wantErr: false,
setup: func(mockObj *MockObject) fiber.Ctx {
mockCtx := app.AcquireCtx(&fasthttp.RequestCtx{})
mockCtx.Locals(constants.CTXKeyRequestID, "mock-req-id")

data, _ := sonic.Marshal(entity.LoginRequest{
Username: "fELIX",
Password: "fELIX",
})
mockCtx.Request().SetBodyString(string(data))

// mockObj.MockAuthService.EXPECT().Login(gomock.Any(), gomock.Any(), gomock.Any()).
// Return(&entity.LoginResponse{}, nil).Times(1)
return mockCtx
},
},
}
for _, tt := range tests {
ctrl, mockObj := NewMock(t)
defer ctrl.Finish()

authHandler := &AuthHandler{
authService: mockObj.MockAuthService,
}

c := tt.setup(mockObj)

t.Run(tt.name, func(t *testing.T) {
if err := tt.h.Login(tt.args.c); (err != nil) != tt.wantErr {
if err := authHandler.Login(c); (err != nil) != tt.wantErr {
t.Errorf("AuthHandler.Login() error = %v, wantErr %v", err, tt.wantErr)
}
})
Expand Down
10 changes: 5 additions & 5 deletions internal/app/api/handler/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,21 @@ func TestMain(m *testing.M) {

type MockObject struct {
MockUserRepo *mocks.MockIUserRepository
MockAuthService *mocks.MockIAuth
MockUserService *mocks.MockIUserService
MockJWTService *mocks.MockIJWTAuth
MockAuthService *mocks.MockIAuthService
}

func NewMock(t *testing.T) (*gomock.Controller, *MockObject) {
setTestENV()
ctrl := gomock.NewController(t)
mockUserRepo := mocks.NewMockIUserRepository(ctrl)
mockAuthService := mocks.NewMockIAuth(ctrl)
mockUserService := mocks.NewMockIUserService(ctrl)
mockJWTService := mocks.NewMockIJWTAuth(ctrl)
mockAuthService := mocks.NewMockIAuthService(ctrl)

mockObj := &MockObject{
MockUserRepo: mockUserRepo,
MockJWTService: mockJWTService,
MockAuthService: mockAuthService,
MockUserService: mockUserService,
}

return ctrl, mockObj
Expand Down
4 changes: 2 additions & 2 deletions internal/app/api/middleware/jwt_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ const (
)

type JWTAuth struct {
AuthService ports.IAuth
AuthService ports.IJWTAuth
}

func NewJWTAuthMiddleware(authService ports.IAuth) JWTAuth {
func NewJWTAuthMiddleware(authService ports.IJWTAuth) JWTAuth {
return JWTAuth{
AuthService: authService,
}
Expand Down
2 changes: 1 addition & 1 deletion internal/app/auth/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type AuthJWT struct {
ExpireDuration int
}

func NewAuthJWT(secretKey string) ports.IAuth {
func NewAuthJWT(secretKey string) ports.IJWTAuth {
return &AuthJWT{
SecretKey: secretKey,
ExpireDuration: expireDurationJWT,
Expand Down
14 changes: 7 additions & 7 deletions internal/app/interactor/interactor.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ type APInteractor struct {
MenuHandler ports.IMenuHandler
}

type UserHandler struct {
UserService ports.IUserService
type AuthHandler struct {
AuthService ports.IAuthService
}

type MenuHandler struct {
MenuService ports.IMenuService
type AuthService struct {
JWTService ports.IJWTAuth
UserRepository ports.IUserRepository
}

type UserService struct {
AuthService ports.IAuth
UserRepository ports.IUserRepository
type MenuHandler struct {
MenuService ports.IMenuService
}

type MenuService struct {
Expand Down
87 changes: 70 additions & 17 deletions internal/app/mocks/mocks_auth.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 0c04215

Please sign in to comment.