auth.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package auth
  2. //go:generate mkdir -p mocks
  3. //go:generate rm -rf ./mocks/*_minimock.go
  4. //go:generate minimock -i ../../interfaces.Auth -o ./mocks/ -s "_minimock.go"
  5. import (
  6. "time"
  7. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/interfaces"
  8. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
  9. "github.com/gofiber/fiber/v2"
  10. "github.com/golang-jwt/jwt/v4"
  11. "golang.org/x/crypto/bcrypt"
  12. )
  13. const (
  14. defaultCost = bcrypt.DefaultCost
  15. defaultUserKey = "user"
  16. )
  17. type auth struct {
  18. env interfaces.Env
  19. }
  20. func Init(env interfaces.Env) (interfaces.Auth, error) {
  21. return auth{env: env}, nil
  22. }
  23. func (a auth) GeneratePasswordHash(password string) (string, error) {
  24. res, err := bcrypt.GenerateFromPassword([]byte(password), defaultCost)
  25. if err != nil {
  26. return "", err
  27. }
  28. return string(res), nil
  29. }
  30. func (a auth) IsCorrectPassword(password string, hash string) bool {
  31. return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
  32. }
  33. func (a auth) GetClaims(fctx *fiber.Ctx) jwt.MapClaims {
  34. jwtUser := fctx.Locals(defaultUserKey).(*jwt.Token)
  35. claims := jwtUser.Claims.(jwt.MapClaims)
  36. return claims
  37. }
  38. func (a auth) GenerateToken(user models.User) (string, error) {
  39. claims := jwt.MapClaims{
  40. "name": user.Username,
  41. "exp": time.Now().Add(time.Duration(a.env.GetJWTLifetime()) * time.Second).Unix(),
  42. }
  43. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  44. return token.SignedString([]byte(a.env.GetJWTSecretKey()))
  45. }