package handler import ( "errors" "highload/internal/service" "highload/internal/transport/http/httputils" "highload/internal/transport/http/middleware" "io" "net/http" ) type AuthHandler struct { authService *service.AuthService } func NewAuthHandler(authService *service.AuthService) *AuthHandler { return &AuthHandler{authService: authService} } func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) { requestID := middleware.RequestIDFromContext(r.Context()) username, password, ok := r.BasicAuth() if !ok { httputils.WriteBasicUnauthorized(w, requestID) return } var probe [1]byte n, err := r.Body.Read(probe[:]) if n > 0 || (err != nil && !errors.Is(err, io.EOF)) { _ = httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{ Code: "invalid_request", Message: "Request body must be empty", RequestID: requestID, }) return } createdSession, err := h.authService.CreateSession(r.Context(), username, password) if err != nil { if errors.Is(err, service.ErrUnauthorized) { httputils.WriteBasicUnauthorized(w, requestID) return } httputils.WriteServiceError(w, err, requestID) return } response := createSessionResponse{ Token: createdSession.Token, TokenType: createdSession.TokenType, ExpiresAt: httputils.FormatTime(createdSession.ExpiresAt), User: UserResponse{ Username: createdSession.User.Username, ID: createdSession.User.ID, DisplayName: createdSession.User.DisplayName, CreatedAt: httputils.FormatTime(createdSession.User.CreatedAt), }, } httputils.WriteJSON[createSessionResponse](w, http.StatusCreated, response) } func (h *AuthHandler) DeleteSession(w http.ResponseWriter, r *http.Request) { requestID := middleware.RequestIDFromContext(r.Context()) token, ok := httputils.ExtractBearerToken(r) if !ok { httputils.WriteBearerUnauthorized(w, requestID) return } err := h.authService.RevokeSession(r.Context(), token) if err != nil { if errors.Is(err, service.ErrUnauthorized) { httputils.WriteBearerUnauthorized(w, requestID) return } httputils.WriteServiceError(w, err, requestID) return } w.WriteHeader(http.StatusNoContent) }