Skeleton contracts / contracts (pull_request) Blocked by required conditions
60 lines
1.8 KiB
Go
60 lines
1.8 KiB
Go
package chat
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
|
)
|
|
|
|
func bearerToken(c echo.Context) string {
|
|
parts := strings.Fields(c.Request().Header.Get("Authorization"))
|
|
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
|
return ""
|
|
}
|
|
return parts[1]
|
|
}
|
|
|
|
func (h *Chat) createSession(c echo.Context) error {
|
|
username, password, ok := c.Request().BasicAuth()
|
|
if !ok {
|
|
c.Response().Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
|
return h.writeError(c, http.StatusUnauthorized, "unauthorized", "Неверные учётные данные")
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(c.Request().Body, 1))
|
|
if err != nil || len(body) != 0 {
|
|
return h.invalid(c, "Тело запроса входа должно быть пустым")
|
|
}
|
|
if h.loginLimit != nil {
|
|
account := fmt.Sprintf("%x", sha256.Sum256([]byte(strings.ToLower(username))))
|
|
delay, err := h.loginLimit(c.Request().Context(), account)
|
|
if err != nil {
|
|
return h.useCaseError(c, err)
|
|
}
|
|
if delay > 0 {
|
|
c.Response().Header().Set("Retry-After", strconv.Itoa(delay))
|
|
return h.writeError(c, http.StatusTooManyRequests, "rate_limited", "Слишком много попыток входа")
|
|
}
|
|
}
|
|
login, err := h.useCase.CreateSession(c.Request().Context(), username, password)
|
|
if err != nil {
|
|
return h.useCaseError(c, err)
|
|
}
|
|
return c.JSON(http.StatusCreated, dto.CreateSessionResponse{
|
|
Token: login.Token, TokenType: "Bearer", ExpiresAt: dto.Timestamp(login.ExpiresAt), User: createUserResponseFromDomain(login.User),
|
|
})
|
|
}
|
|
|
|
func (h *Chat) deleteSession(c echo.Context) error {
|
|
if err := h.useCase.DeleteSession(c.Request().Context(), bearerToken(c)); err != nil {
|
|
return h.useCaseError(c, err)
|
|
}
|
|
return c.NoContent(http.StatusNoContent)
|
|
}
|