modified: serv_nginx/api_bb/internal/handlers/auth.go

change method login
This commit is contained in:
2025-10-11 11:30:45 +05:00
parent 556780fd28
commit ce433e6187
+69 -46
View File
@@ -164,60 +164,83 @@ func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) {
} }
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
h.logger.Info("handling login request",
zap.String("method", r.Method),
zap.String("path", r.URL.Path),
zap.String("remote_addr", r.RemoteAddr),
)
h.logger.Info("handling login request", // Проверяем Content-Type
zap.String("method", r.Method), if r.Header.Get("Content-Type") != "application/json" {
zap.String("path", r.URL.Path), h.logger.Warn("invalid content type", zap.String("content_type", r.Header.Get("Content-Type")))
zap.String("remote_addr", r.RemoteAddr), utils.RespondWithError(w, http.StatusBadRequest, "Content-Type must be application/json")
) return
}
var req LoginRequest // Читаем и логируем тело запроса
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { bodyBytes, err := io.ReadAll(r.Body)
h.logger.Error("failed to decode login request", zap.Error(err)) if err != nil {
utils.RespondWithError(w, http.StatusBadRequest, "Invalid request payload: "+err.Error()) h.logger.Error("failed to read request body", zap.Error(err))
return utils.RespondWithError(w, http.StatusBadRequest, "Failed to read request body")
} return
}
defer r.Body.Close()
// Валидация // Восстанавливаем тело
if req.Email == "" || req.Password == "" { r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
h.logger.Warn("login failed - email or password empty")
utils.RespondWithError(w, http.StatusBadRequest, "Email and password are required")
return
}
h.logger.Info("attempting user login", zap.String("email", req.Email)) h.logger.Debug("request body", zap.String("body", string(bodyBytes)))
user, token, err := h.authService.Login(req.Email, req.Password) var req LoginRequest
if err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.logger.Warn("login failed", h.logger.Error("JSON decode failed",
zap.String("email", req.Email), zap.Error(err),
zap.Error(err), zap.String("raw_body", string(bodyBytes)),
) )
utils.RespondWithError(w, http.StatusUnauthorized, err.Error()) utils.RespondWithError(w, http.StatusBadRequest, "Invalid JSON: "+err.Error())
return return
} }
// Устанавливаем токен в куки // Валидация
http.SetCookie(w, &http.Cookie{ if req.Email == "" || req.Password == "" {
Name: "auth_token", h.logger.Warn("validation failed",
Value: token, zap.String("email", req.Email),
Path: "/", zap.Int("password_len", len(req.Password)),
HttpOnly: true, )
Secure: false, // В production установить true utils.RespondWithError(w, http.StatusBadRequest, "Email and password are required")
SameSite: http.SameSiteLaxMode, return
Expires: time.Now().Add(24 * time.Hour), }
})
h.logger.Info("user logged in successfully", h.logger.Info("attempting login", zap.String("email", req.Email))
zap.Uint("user_id", user.ID),
zap.String("email", user.Email),
)
utils.RespondWithJSON(w, http.StatusOK, map[string]interface{}{ user, token, err := h.authService.Login(req.Email, req.Password)
"message": "Login successful", if err != nil {
"token": token, h.logger.Warn("login failed", zap.String("email", req.Email), zap.Error(err))
"user": toUserResponse(user), utils.RespondWithError(w, http.StatusUnauthorized, err.Error())
}) return
}
// Устанавливаем куки
http.SetCookie(w, &http.Cookie{
Name: "auth_token",
Value: token,
Path: "/",
HttpOnly: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
Expires: time.Now().Add(24 * time.Hour),
})
h.logger.Info("login successful",
zap.Uint("user_id", user.ID),
zap.String("email", user.Email),
)
utils.RespondWithJSON(w, http.StatusOK, map[string]interface{}{
"message": "Login successful",
"token": token,
"user": toUserResponse(user),
})
} }
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) { func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {