Skip to content

Commit

Permalink
Refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
voltgizerz committed Jun 9, 2024
1 parent bfc4094 commit a3bda37
Show file tree
Hide file tree
Showing 10 changed files with 48 additions and 23 deletions.
6 changes: 4 additions & 2 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,13 @@ func main() {
userRepo := repository.NewUserRepository(repoOpts)

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

// Initialize Handlers
userHandler := handler.NewUserHandler(interactor.UserHandler{
Auth: authJWT,
UserService: userService,
})

Expand Down
2 changes: 1 addition & 1 deletion database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func connectMySQL(ctx context.Context, dsn string, maxOpenConns, maxIdleConns in

db, err := sqlx.Connect("mysql", dsn)
if err != nil {
logger.LogStdErr.Errorf("Failed to connect to MySQL: %s", err)
logger.LogStdErr.Fatalf("Failed to connect to MySQL: %s", err)
}

db.SetMaxOpenConns(maxOpenConns)
Expand Down
2 changes: 1 addition & 1 deletion internal/app/api/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func NewAuthJWT(secretKey string) ports.IAuth {
}
}

func (a *AuthJWT) CreateToken(user *entity.User) (*entity.CreateTokenResponse, error) {
func (a *AuthJWT) CreateToken(user *entity.UserORM) (*entity.CreateTokenResponse, error) {
expiredAt := time.Now().Add(time.Hour * time.Duration(a.ExpireDurationInHour))

token := jwt.NewWithClaims(jwt.SigningMethodHS256,
Expand Down
10 changes: 2 additions & 8 deletions internal/app/api/handler/user_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ type UserHandler struct {

func NewUserHandler(i interactor.UserHandler) *UserHandler {
return &UserHandler{
authService: i.Auth,
userService: i.UserService,
}
}
Expand All @@ -37,7 +36,7 @@ func (h *UserHandler) Login(c fiber.Ctx) error {
return sendErrorResp(c, fiber.StatusBadRequest, constants.ErrMsgUsernameOrPasswordRequired)
}

dataUser, err := h.userService.Login(ctx, req.Username, req.Password)
userLoginData, err := h.userService.Login(ctx, req.Username, req.Password)
if err != nil {
if err == sql.ErrNoRows {
return sendErrorResp(c, fiber.StatusUnauthorized, constants.ErrMsgUsernameNotFound)
Expand All @@ -46,12 +45,7 @@ func (h *UserHandler) Login(c fiber.Ctx) error {
return sendErrorResp(c, fiber.StatusUnauthorized, constants.ErrMsgInvalidUsernameOrPassword)
}

token, err := h.authService.CreateToken(dataUser)
if err != nil {
return sendErrorResp(c, fiber.StatusInternalServerError, constants.ErrMsgInternalServerError)
}

return sendSuccessResp(c, fiber.StatusOK, "Success", token)
return sendSuccessResp(c, fiber.StatusOK, "Success", userLoginData)
}

func (h *UserHandler) Register(c fiber.Ctx) error {
Expand Down
2 changes: 1 addition & 1 deletion internal/app/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type Server struct {

func NewServer(interactor interactor.APInteractor) *Server {
return &Server{
cfgAPI: interactor.CfgAPI,
cfgAPI: interactor.CfgAPI,
userHandler: interactor.UserHandler,
}
}
Expand Down
10 changes: 9 additions & 1 deletion internal/app/entity/auth_entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,12 @@ type CreateTokenResponse struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiredAt time.Time `json:"expired_at"`
}
}

type LoginResponse struct {
UserID int64 `json:"user_id"`
RoleID int64 `json:"role_id"`
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiredAt time.Time `json:"expired_at"`
}
6 changes: 5 additions & 1 deletion internal/app/interactor/interactor.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ type APInteractor struct {
}

type UserHandler struct {
Auth ports.IAuth
UserService ports.IUserService
}

type UserService struct {
AuthService ports.IAuth
UserRepository ports.IUserRepository
}
2 changes: 1 addition & 1 deletion internal/app/ports/auth_ports.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ import (
)

type IAuth interface {
CreateToken(user *entity.User) (*entity.CreateTokenResponse, error)
CreateToken(user *entity.UserORM) (*entity.CreateTokenResponse, error)
VerifyToken(tokenString string) error
}
2 changes: 1 addition & 1 deletion internal/app/ports/user_ports.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type IUserRepository interface {
}

type IUserService interface {
Login(ctx context.Context, username string, password string) (*entity.User, error)
Login(ctx context.Context, username string, password string) (*entity.LoginResponse, error)
}

type IUserHandler interface {
Expand Down
29 changes: 23 additions & 6 deletions internal/app/service/user_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,25 @@ import (
"github.com/opentracing/opentracing-go"
"github.com/sirupsen/logrus"
"github.com/voltgizerz/POS-restaurant/internal/app/entity"
"github.com/voltgizerz/POS-restaurant/internal/app/interactor"
"github.com/voltgizerz/POS-restaurant/internal/app/ports"
"github.com/voltgizerz/POS-restaurant/internal/utils"
"github.com/voltgizerz/POS-restaurant/pkg/logger"
)

type UserService struct {
authService ports.IAuth
userRepository ports.IUserRepository
}

func NewUserService(userRepository ports.IUserRepository) *UserService {
func NewUserService(i interactor.UserService) *UserService {
return &UserService{
userRepository: userRepository,
authService: i.AuthService,
userRepository: i.UserRepository,
}
}

func (s *UserService) Login(ctx context.Context, username string, password string) (*entity.User, error) {
func (s *UserService) Login(ctx context.Context, username string, password string) (*entity.LoginResponse, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "service.UserService.Login")
defer span.Finish()

Expand All @@ -45,11 +48,25 @@ func (s *UserService) Login(ctx context.Context, username string, password strin
return nil, err
}

userData := &entity.User{
ID: user.ID,
tokenData, err := s.authService.CreateToken(user)
if err != nil {
logger.LogStdErr.WithFields(logrus.Fields{
"username": username,
"error": err,
}).Error("[UserService] error on CreateToken")

return nil, err
}

resp := &entity.LoginResponse{
UserID: user.ID,
RoleID: 1, // TODO
Token: tokenData.Token,
TokenType: tokenData.TokenType,
ExpiredAt: tokenData.ExpiredAt,
}

return userData, nil
return resp, nil
}

func (s *UserService) Register(email string, password string, confirmPass string) error {
Expand Down

0 comments on commit a3bda37

Please sign in to comment.