modified: main_dc/yalarba/api_es/internal/dto/user.go
modified: main_dc/yalarba/api_es/internal/handler/user_handler.go modified: main_dc/yalarba/api_es/internal/middleware/auth.go modified: main_dc/yalarba/api_es/internal/router/router.go set authorization with cooky and bearer jwt token
This commit is contained in:
@@ -1,13 +1,14 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"api_es/internal/dto"
|
||||
appMiddleware "api_es/internal/middleware"
|
||||
"api_es/internal/service"
|
||||
"api_es/internal/utils"
|
||||
"api_es/pkg/logger"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-playground/validator/v10"
|
||||
@@ -61,6 +62,9 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Устанавливаем куку с токеном
|
||||
appMiddleware.SetAuthCookie(w, response.Token)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
zapLogger.Debug("End register")
|
||||
@@ -103,11 +107,79 @@ func (h *UserHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Устанавливаем куку с токеном
|
||||
appMiddleware.SetAuthCookie(w, response.Token)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
zapLogger.Debug("End login")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// Добавляем новый метод для logout
|
||||
// Logout godoc
|
||||
// @Summary Logout user
|
||||
// @Description Clear authentication cookies and tokens
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Router /auth/logout [post]
|
||||
func (h *UserHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
// Очищаем auth cookie
|
||||
appMiddleware.ClearAuthCookie(w)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"message": "Successfully logged out",
|
||||
})
|
||||
}
|
||||
|
||||
// Добавляем метод для обновления токена
|
||||
// RefreshToken godoc
|
||||
// @Summary Refresh authentication token
|
||||
// @Description Refresh JWT token using refresh token or existing auth
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} dto.AuthResponse
|
||||
// @Failure 401 {object} map[string]string
|
||||
// @Router /auth/refresh [post]
|
||||
func (h *UserHandler) RefreshToken(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := r.Context().Value(appMiddleware.UserIDKey).(uint)
|
||||
if !ok {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userService.GetUserProfile(r.Context(), userID)
|
||||
if err != nil {
|
||||
http.Error(w, "User not found", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Генерируем новый токен
|
||||
// В реальном приложении здесь должна быть логика с refresh token
|
||||
jwtUtil := utils.NewJWTUtil("secret")
|
||||
newToken, err := jwtUtil.GenerateToken(userID, user.Email, user.Role)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to generate token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Обновляем куку
|
||||
appMiddleware.SetAuthCookie(w, newToken)
|
||||
|
||||
response := &dto.AuthResponse{
|
||||
Token: newToken,
|
||||
User: *user,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// GetProfile godoc
|
||||
// @Summary Get user profile
|
||||
// @Description Get current user profile
|
||||
@@ -243,24 +315,3 @@ func (h *UserHandler) ListUsers(w http.ResponseWriter, r *http.Request) {
|
||||
zapLogger.Debug("Debug end handler listUsers")
|
||||
json.NewEncoder(w).Encode(users)
|
||||
}
|
||||
|
||||
func (h *UserHandler) Routes(r chi.Router) chi.Router {
|
||||
|
||||
r.Route("/auth", func(r chi.Router) {
|
||||
r.Post("/register", h.Register)
|
||||
r.Post("/login", h.Login)
|
||||
})
|
||||
|
||||
r.Route("/users", func(r chi.Router) {
|
||||
r.Use(appMiddleware.AuthMiddleware)
|
||||
|
||||
r.Get("/profile", h.GetProfile)
|
||||
r.Put("/profile", h.UpdateProfile)
|
||||
|
||||
// Admin routes
|
||||
r.With(appMiddleware.AdminMiddleware).Get("/", h.ListUsers)
|
||||
r.With(appMiddleware.AdminMiddleware).Get("/{id}", h.GetUser)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user