add auth middleware

This commit is contained in:
2026-02-23 16:39:04 -05:00
parent af9c23c521
commit 11eb192e2a
4 changed files with 89 additions and 5 deletions
+39 -2
View File
@@ -10,10 +10,11 @@ import (
type UserHandler struct {
userService *services.UserService
authService *services.AuthService
}
func NewUserHandler(us *services.UserService) *UserHandler {
return &UserHandler{userService: us}
func NewUserHandler(us *services.UserService, as *services.AuthService) *UserHandler {
return &UserHandler{userService: us, authService: as}
}
func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
@@ -60,3 +61,39 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(user)
}
func (h *UserHandler) Login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var req models.LoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
req.Email = strings.ToLower(strings.TrimSpace(req.Email))
user, err := h.userService.GetUserByEmail(req.Email)
if err != nil || user == nil {
http.Error(w, "invalid credentials", http.StatusUnauthorized)
return
}
if !h.userService.ValidatePassword(user, req.Password) {
http.Error(w, "invalid credentials", http.StatusUnauthorized)
return
}
token, err := h.authService.GenerateToken(user.ID, user.Email)
if err != nil {
http.Error(w, "failed to generate token", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(models.LoginResponse{User: *user, Token: token})
}