auth.go 1.3 KB

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