add login form
This commit is contained in:
+11
-6
@@ -5,6 +5,7 @@ import (
|
||||
"go-weather/middleware"
|
||||
"go-weather/models"
|
||||
"go-weather/services"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
@@ -20,17 +21,20 @@ func NewUserHandler(us *services.UserService, as *services.AuthService) *UserHan
|
||||
|
||||
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
claims := middleware.GetClaims(r)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if claims == nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]any{"user": nil})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userService.GetUserByID(claims.UserID)
|
||||
if err != nil {
|
||||
http.Error(w, "user not found", http.StatusNotFound)
|
||||
json.NewEncoder(w).Encode(map[string]any{"user": nil})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{"user": user})
|
||||
json.NewEncoder(w).Encode(map[string]any{"user": user})
|
||||
}
|
||||
|
||||
func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -51,8 +55,8 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.Password) < 8 {
|
||||
http.Error(w, "password must be at least 8 characters", http.StatusBadRequest)
|
||||
if len(req.Password) < 4 {
|
||||
http.Error(w, "password must be at least 4 characters", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -105,6 +109,7 @@ func (h *UserHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
token, err := h.authService.GenerateToken(user.ID, user.Email)
|
||||
if err != nil {
|
||||
slog.Error("failed to generate token", "user_id", user.ID, "error", err)
|
||||
http.Error(w, "failed to generate token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user