forked from mtusi2026/mtusi2026lab2
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
95 lines
2.2 KiB
Go
95 lines
2.2 KiB
Go
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)
|
|
}
|