Merge pull request #77 from rede5/codex/implement-auth-usecase-with-bcrypt-and-pepper
Add username-only Login use case with bcrypt+pepper and JWT claims
This commit is contained in:
commit
199fd3a93a
2 changed files with 45 additions and 4 deletions
|
|
@ -123,12 +123,12 @@ func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
identifier := req.Email
|
if req.Username == "" {
|
||||||
if identifier == "" {
|
writeError(w, http.StatusBadRequest, errors.New("username is required"))
|
||||||
identifier = req.Username
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
token, exp, err := h.svc.Authenticate(r.Context(), identifier, req.Password)
|
token, exp, err := h.svc.Login(r.Context(), req.Username, req.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusUnauthorized, err)
|
writeError(w, http.StatusUnauthorized, err)
|
||||||
return
|
return
|
||||||
|
|
|
||||||
41
backend-old/internal/usecase/auth_usecase.go
Normal file
41
backend-old/internal/usecase/auth_usecase.go
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
package usecase
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Login validates credentials using username and returns a signed JWT.
|
||||||
|
func (s *Service) Login(ctx context.Context, username, password string) (string, time.Time, error) {
|
||||||
|
if strings.TrimSpace(username) == "" {
|
||||||
|
return "", time.Time{}, errors.New("username is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := s.repo.GetUserByUsername(ctx, username)
|
||||||
|
if err != nil {
|
||||||
|
return "", time.Time{}, errors.New("invalid credentials")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(s.pepperPassword(password))); err != nil {
|
||||||
|
return "", time.Time{}, errors.New("invalid credentials")
|
||||||
|
}
|
||||||
|
|
||||||
|
expiresAt := time.Now().Add(s.tokenTTL)
|
||||||
|
claims := jwt.MapClaims{
|
||||||
|
"user_id": user.ID.String(),
|
||||||
|
"company_id": user.CompanyID.String(),
|
||||||
|
"role": user.Role,
|
||||||
|
}
|
||||||
|
|
||||||
|
signed, err := s.signToken(claims, expiresAt)
|
||||||
|
if err != nil {
|
||||||
|
return "", time.Time{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return signed, expiresAt, nil
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue