aditya.siregar 06d7b4764f update
2025-04-26 12:23:12 +07:00

59 lines
1.3 KiB
Go

package auth
import (
"enaklo-pos-be/internal/common/errors"
"enaklo-pos-be/internal/common/logger"
"enaklo-pos-be/internal/common/mycontext"
"enaklo-pos-be/internal/entity"
"go.uber.org/zap"
)
type Repository interface {
FindByEmail(ctx mycontext.Context, email string) (*entity.Customer, error)
}
type CryptoSvc interface {
GenerateJWTCustomer(user *entity.Customer) (string, error)
CompareHashAndPassword(hash string, password string) bool
}
type Service interface {
AuthCustomer(ctx mycontext.Context, email, password string) (*entity.AuthenticateUser, error)
}
type authSvc struct {
repo Repository
crypt CryptoSvc
}
func New(repo Repository, cryptSvc CryptoSvc) Service {
return &authSvc{
repo: repo,
crypt: cryptSvc,
}
}
func (a authSvc) AuthCustomer(ctx mycontext.Context, email, password string) (*entity.AuthenticateUser, error) {
user, err := a.repo.FindByEmail(ctx, email)
if err != nil {
logger.ContextLogger(ctx).Error("error when get user", zap.Error(err))
return nil, errors.ErrorInternalServer
}
if user == nil {
return nil, errors.ErrorUserIsNotFound
}
if ok := a.crypt.CompareHashAndPassword(user.Password, password); !ok {
return nil, errors.ErrorUserInvalidLogin
}
signedToken, err := a.crypt.GenerateJWTCustomer(user)
if err != nil {
return nil, err
}
return user.ToUserAuthenticate(signedToken), nil
}