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 Config interface {
  16. JWTSecretKey() string
  17. JWTLifeTime() time.Duration
  18. }
  19. type Service struct {
  20. config Config
  21. }
  22. func Init(c Config) (*Service, error) {
  23. return &Service{config: c}, 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(a.config.JWTLifeTime()).Unix(),
  44. }
  45. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  46. return token.SignedString([]byte(a.config.JWTSecretKey()))
  47. }