50 lines
1.2 KiB
Go
50 lines
1.2 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
type AuthService struct {
|
|
users UserRepository
|
|
jwtSecret []byte
|
|
jwtTTL time.Duration
|
|
}
|
|
|
|
func NewAuthService(users UserRepository, jwtSecret string, jwtTTL time.Duration) *AuthService {
|
|
return &AuthService{users: users, jwtSecret: []byte(jwtSecret), jwtTTL: jwtTTL}
|
|
}
|
|
|
|
func (s *AuthService) Register(ctx context.Context, email, password, name string) (int64, error) {
|
|
if email == "" || password == "" || name == "" {
|
|
return 0, ErrBadRequest
|
|
}
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
u, err := s.users.Create(ctx, email, string(hash), name)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return u.ID, nil
|
|
}
|
|
|
|
func (s *AuthService) Login(ctx context.Context, email, password string) (string, error) {
|
|
u, err := s.users.FindByEmail(ctx, email)
|
|
if err != nil {
|
|
return "", ErrUnauthorized
|
|
}
|
|
if bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil {
|
|
return "", ErrUnauthorized
|
|
}
|
|
claims := jwt.MapClaims{
|
|
"sub": u.ID,
|
|
"exp": time.Now().Add(s.jwtTTL).Unix(),
|
|
}
|
|
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(s.jwtSecret)
|
|
}
|