auth.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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/homethings/internal/models"
  8. )
  9. const (
  10. ClaimsKeyName = "name"
  11. claimsKeyExp = "exp"
  12. claimsKeyUser = "user"
  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(claimsKeyUser).(*jwt.Token)
  37. return jwtUser.Claims.(jwt.MapClaims)
  38. }
  39. func (a Service) GenerateToken(user models.User) (string, error) {
  40. claims := jwt.MapClaims{
  41. ClaimsKeyName: user.Username,
  42. claimsKeyExp: time.Now().Add(time.Duration(a.env.JWTLifetime()) * time.Second).Unix(),
  43. }
  44. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  45. return token.SignedString([]byte(a.env.JWTSecretKey()))
  46. }