Skip to content

Commit

Permalink
feat: log svc
Browse files Browse the repository at this point in the history
  • Loading branch information
bookpanda committed Jun 22, 2024
1 parent 3b53cce commit ae7880a
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 21 deletions.
4 changes: 2 additions & 2 deletions .env.template
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
APP_PORT=3004
APP_PORT=3002
APP_ENV=development

DB_URL=postgres://root:1234@localhost:5432/rpkm67_db

JWT_SECRET=secret
JWT_ACCESS_TTL=3600
JWT_REFRESH_TTL=604800
JWT_REFRESH_TTL=259200
JWT_ISSUER=issuer
JWT_RESET_TOKEN_TTL=900

Expand Down
8 changes: 4 additions & 4 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ func main() {
cacheRepo := cache.NewRepository(redis)

userRepo := user.NewRepository(db)
userSvc := user.NewService(userRepo, logger)
userSvc := user.NewService(userRepo, logger.Named("userSvc"))

jwtSvc := jwt.NewService(conf.Jwt, jwt.NewJwtStrategy(conf.Jwt.Secret), jwt.NewJwtUtils())
tokenSvc := token.NewService(jwtSvc, cacheRepo, token.NewTokenUtils())
authSvc := auth.NewService(userSvc, tokenSvc, auth.NewAuthUtils(), auth.NewBcryptUtils(), logger)
jwtSvc := jwt.NewService(conf.Jwt, jwt.NewJwtStrategy(conf.Jwt.Secret), jwt.NewJwtUtils(), logger.Named("jwtSvc"))
tokenSvc := token.NewService(jwtSvc, cacheRepo, token.NewTokenUtils(), logger.Named("tokenSvc"))
authSvc := auth.NewService(userSvc, tokenSvc, auth.NewAuthUtils(), auth.NewBcryptUtils(), logger.Named("authSvc"))

listener, err := net.Listen("tcp", fmt.Sprintf(":%v", conf.App.Port))
if err != nil {
Expand Down
19 changes: 12 additions & 7 deletions internal/auth/auth.service.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ func (s *serviceImpl) SignUp(_ context.Context, in *proto.SignUpRequest) (res *p

hashedPassword, err := s.bcrypt.GenerateHashedPassword(in.Password)
if err != nil {
return nil, err
s.log.Named("SignUp").Error("GenerateHashedPassword: ", zap.Error(err))
return nil, status.Error(codes.Internal, err.Error())
}

createUser := &userProto.CreateUserRequest{
Expand All @@ -65,7 +66,8 @@ func (s *serviceImpl) SignUp(_ context.Context, in *proto.SignUpRequest) (res *p

userRes, err := s.userSvc.Create(context.Background(), createUser)
if err != nil {
return nil, err
s.log.Named("SignUp").Error("Create: ", zap.Error(err))
return nil, status.Error(codes.Internal, err.Error())
}

return &proto.SignUpResponse{
Expand All @@ -79,17 +81,20 @@ func (s *serviceImpl) SignUp(_ context.Context, in *proto.SignUpRequest) (res *p
func (s *serviceImpl) SignIn(_ context.Context, in *proto.SignInRequest) (res *proto.SignInResponse, err error) {
user, err := s.userSvc.FindByEmail(context.Background(), &userProto.FindByEmailRequest{Email: in.Email})
if err != nil {
return nil, err
s.log.Named("SignIn").Error("FindByEmail: ", zap.Error(err))
return nil, status.Error(codes.Unauthenticated, err.Error())
}

err = s.bcrypt.CompareHashedPassword(in.Password, user.User.Password)
err = s.bcrypt.CompareHashedPassword(user.User.Password, in.Password)
if err != nil {
return nil, err
s.log.Named("SignIn").Error("CompareHashedPassword: ", zap.Error(err))
return nil, status.Error(codes.Unauthenticated, err.Error())
}

credentials, err := s.tokenSvc.CreateCredentials(user.User.Id, constant.Role(user.User.Role))
credentials, err := s.tokenSvc.GetCredentials(user.User.Id, constant.Role(user.User.Role))
if err != nil {
return nil, status.Error(codes.Internal, constant.InternalServerErrorMessage)
s.log.Named("SignIn").Error("GetCredentials: ", zap.Error(err))
return nil, status.Error(codes.Internal, err.Error())
}

return &proto.SignInResponse{
Expand Down
7 changes: 5 additions & 2 deletions internal/jwt/jwt.service.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/isd-sgcu/rpkm67-auth/constant"
"github.com/isd-sgcu/rpkm67-auth/internal/dto"
"github.com/pkg/errors"
"go.uber.org/zap"
)

type Service interface {
Expand All @@ -21,10 +22,11 @@ type serviceImpl struct {
config config.JwtConfig
strategy JwtStrategy
jwtUtils JwtUtils
log *zap.Logger
}

func NewService(config config.JwtConfig, strategy JwtStrategy, jwtUtils JwtUtils) Service {
return &serviceImpl{config: config, strategy: strategy, jwtUtils: jwtUtils}
func NewService(config config.JwtConfig, strategy JwtStrategy, jwtUtils JwtUtils, log *zap.Logger) Service {
return &serviceImpl{config: config, strategy: strategy, jwtUtils: jwtUtils, log: log}
}

func (s *serviceImpl) CreateToken(userId string, role constant.Role) (string, error) {
Expand All @@ -42,6 +44,7 @@ func (s *serviceImpl) CreateToken(userId string, role constant.Role) (string, er

tokenStr, err := s.jwtUtils.SignedTokenString(token, s.config.Secret)
if err != nil {
s.log.Named("CreateToken").Error("SignedTokenString: ", zap.Error(err))
return "", errors.New(fmt.Sprintf("Error while signing the token due to: %s", err.Error()))
}

Expand Down
22 changes: 17 additions & 5 deletions internal/token/token.service.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/isd-sgcu/rpkm67-auth/internal/cache"
"github.com/isd-sgcu/rpkm67-auth/internal/dto"
"github.com/isd-sgcu/rpkm67-auth/internal/jwt"
"go.uber.org/zap"
)

type Service interface {
Expand All @@ -22,26 +23,26 @@ type serviceImpl struct {
jwtService jwt.Service
cache cache.Repository
tokenUtils TokenUtils
log *zap.Logger
}

func NewService(jwtService jwt.Service, cache cache.Repository, tokenUtils TokenUtils) Service {
func NewService(jwtService jwt.Service, cache cache.Repository, tokenUtils TokenUtils, log *zap.Logger) Service {
return &serviceImpl{
jwtService: jwtService,
cache: cache,
tokenUtils: tokenUtils,
log: log,
}
}

func (s *serviceImpl) GetCredentials(userId string, role constant.Role) (*dto.Credentials, error) {
credentials := &dto.Credentials{}
err := s.cache.GetValue(sessionKey(userId), credentials)
if err != nil {
return nil, err
}

if (credentials == &dto.Credentials{}) { // no session found
s.log.Named("tokenSvc").Named("GetCredentials").Info("No session found in cache for user", zap.String("userId", userId))
credentials, err = s.CreateCredentials(userId, role)
if err != nil {
s.log.Named("GetCredentials").Error("CreateCredentials: ", zap.Error(err))
return nil, err
}
}
Expand All @@ -50,11 +51,13 @@ func (s *serviceImpl) GetCredentials(userId string, role constant.Role) (*dto.Cr
if err != nil { // still have refreshToken but accessToken is expired
err := s.cache.DeleteValue(sessionKey(userId))
if err != nil {
s.log.Named("GetCredentials").Error("DeleteValue: ", zap.Error(err))
return nil, err
}

accessToken, err := s.jwtService.CreateToken(userId, role)
if err != nil {
s.log.Named("GetCredentials").Error("CreateToken: ", zap.Error(err))
return nil, err
}

Expand All @@ -65,6 +68,7 @@ func (s *serviceImpl) GetCredentials(userId string, role constant.Role) (*dto.Cr

err = s.cache.SetValue(sessionKey(userId), newCredentials, s.jwtService.GetConfig().AccessTTL)
if err != nil {
s.log.Named("GetCredentials").Error("SetValue: ", zap.Error(err))
return nil, err
}

Expand All @@ -77,6 +81,7 @@ func (s *serviceImpl) GetCredentials(userId string, role constant.Role) (*dto.Cr
func (s *serviceImpl) CreateCredentials(userId string, role constant.Role) (*dto.Credentials, error) {
accessToken, err := s.jwtService.CreateToken(userId, role)
if err != nil {
s.log.Named("CreateCredentials").Error("CreateToken: ", zap.Error(err))
return nil, err
}

Expand All @@ -87,6 +92,7 @@ func (s *serviceImpl) CreateCredentials(userId string, role constant.Role) (*dto
Role: role,
}, s.jwtService.GetConfig().RefreshTTL)
if err != nil {
s.log.Named("CreateCredentials").Error("SetValue refresh: ", zap.Error(err))
return nil, err
}

Expand All @@ -97,6 +103,7 @@ func (s *serviceImpl) CreateCredentials(userId string, role constant.Role) (*dto

err = s.cache.SetValue(sessionKey(userId), credentials, s.jwtService.GetConfig().AccessTTL)
if err != nil {
s.log.Named("CreateCredentials").Error("SetValue session: ", zap.Error(err))
return nil, err
}

Expand All @@ -107,23 +114,28 @@ func (s *serviceImpl) RefreshToken(refreshToken string) (*dto.Credentials, error
refreshCache := &dto.RefreshTokenCache{}
err := s.cache.GetValue(refreshKey(refreshToken), refreshCache)
if err != nil {
s.log.Named("RefreshToken").Error("GetValue: ", zap.Error(err))
return nil, err
} else if (refreshCache == &dto.RefreshTokenCache{}) {
s.log.Named("RefreshToken").Info("GetValue: refresh token not found")
return nil, fmt.Errorf("refresh token not found")
}

err = s.cache.DeleteValue(refreshKey(refreshToken))
if err != nil {
s.log.Named("RefreshToken").Error("DeleteValue refresh: ", zap.Error(err))
return nil, err
}

err = s.cache.DeleteValue(sessionKey(refreshCache.UserID))
if err != nil {
s.log.Named("RefreshToken").Error("DeleteValue session: ", zap.Error(err))
return nil, err
}

credentials, err := s.CreateCredentials(refreshCache.UserID, refreshCache.Role)
if err != nil {
s.log.Named("RefreshToken").Error("CreateCredentials: ", zap.Error(err))
return nil, err
}

Expand Down
3 changes: 2 additions & 1 deletion internal/user/user.service.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (s *serviceImpl) FindOne(_ context.Context, req *proto.FindOneUserRequest)
func (s *serviceImpl) FindByEmail(_ context.Context, req *proto.FindByEmailRequest) (res *proto.FindByEmailResponse, err error) {
user := &model.User{}

err = s.repo.FindOne(req.Email, user)
err = s.repo.FindByEmail(req.Email, user)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, status.Error(codes.NotFound, constant.UserNotFoundErrorMessage)
Expand All @@ -86,6 +86,7 @@ func ModelToProto(in *model.User) *proto.User {
return &proto.User{
Id: in.ID.String(),
Email: in.Email,
Password: in.Password,
Firstname: in.Firstname,
Lastname: in.Lastname,
Role: in.Role.String(),
Expand Down

0 comments on commit ae7880a

Please sign in to comment.