import lab3 files
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title" binding:"required,min=1,max=100"`
|
||||
MemberIDs []string `json:"member_ids" binding:"required,min=1,max=100,dive,uuid"`
|
||||
}
|
||||
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChatPageResponse struct {
|
||||
Items []ChatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func ChatFromDomain(c *domain.Chat) ChatResponse {
|
||||
return ChatResponse{
|
||||
ID: c.ID,
|
||||
Title: c.Title,
|
||||
MemberIDs: append([]string(nil), c.MemberIDs...),
|
||||
CreatedAt: c.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
|
||||
func ChatsFromDomain(items []domain.Chat) []ChatResponse {
|
||||
out := make([]ChatResponse, len(items))
|
||||
for i := range items {
|
||||
out[i] = ChatFromDomain(&items[i])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
// делаем вложенный ответ через вкладку ErrorBody в обертку.
|
||||
|
||||
type ErrorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorBody `json:"error"`
|
||||
}
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
func ErrorFromDomain(err error, requestID string) ErrorResponse {
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
code := c.Code()
|
||||
message := err.Error()
|
||||
if code == domain.CodeInternalError {
|
||||
message = "внутренняя ошибка"
|
||||
}
|
||||
return ErrorResponse{Error: ErrorBody{
|
||||
Code: string(code),
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
}}
|
||||
}
|
||||
code := domain.CodeInternalError
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
code = domain.CodeNotFound
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
code = domain.CodeConflict
|
||||
case errors.Is(err, domain.ErrInvalidInput):
|
||||
code = domain.CodeInvalidRequest
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
code = domain.CodeUnauthorized
|
||||
case errors.Is(err, domain.ErrUnsupportedMediaType):
|
||||
code = domain.CodeUnsupportedMediaType
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
code = domain.CodeUnavailable
|
||||
}
|
||||
message := err.Error()
|
||||
if code == domain.CodeInternalError {
|
||||
message = "внутренняя ошибка"
|
||||
}
|
||||
return ErrorResponse{Error: ErrorBody{
|
||||
Code: string(code),
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
}}
|
||||
}
|
||||
|
||||
func StatusFromError(err error) int {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return 404
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return 409
|
||||
case errors.Is(err, domain.ErrInvalidInput):
|
||||
return 400
|
||||
case errors.Is(err, domain.ErrUnauthorized):
|
||||
return 401
|
||||
case errors.Is(err, domain.ErrUnsupportedMediaType):
|
||||
return 415
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
return 503
|
||||
default:
|
||||
return 500
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package dto
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text" binding:"required,min=1,max=4000"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type MessagePageResponse struct {
|
||||
Items []MessageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func MessageFromDomain(m *domain.Message) MessageResponse {
|
||||
return MessageResponse{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.SenderID,
|
||||
Text: m.Text,
|
||||
CreatedAt: m.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
|
||||
func MessagesFromDomain(items []domain.Message) []MessageResponse {
|
||||
out := make([]MessageResponse, len(items))
|
||||
for i := range items {
|
||||
out[i] = MessageFromDomain(&items[i])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
|
||||
func SessionResponseFromDomain(s *domain.Session, token string, u *domain.User) SessionResponse {
|
||||
return SessionResponse{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: s.ExpiresAt.UTC().Format(timeFormat),
|
||||
User: UserFromDomain(u),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const timeFormat = "2006-01-02T15:04:05.000000Z07:00"
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username" binding:"required,min=3,max=32"`
|
||||
DisplayName string `json:"display_name" binding:"required,min=1,max=100"`
|
||||
Password string `json:"password" binding:"required,min=12,max=512"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func UserFromDomain(u *domain.User) UserResponse {
|
||||
return UserResponse{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: u.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
sessions *service.SessionService
|
||||
}
|
||||
|
||||
func NewAuthHandler(sessions *service.SessionService) *AuthHandler {
|
||||
return &AuthHandler{sessions: sessions}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(c *gin.Context) {
|
||||
username, password, err := parseBasicAuth(c)
|
||||
if err != nil {
|
||||
respondBasicChallenge(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
session, token, user, err := h.sessions.Login(c.Request.Context(), username, password)
|
||||
if err != nil {
|
||||
respondBasicChallenge(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dto.SessionResponseFromDomain(session, token, user))
|
||||
}
|
||||
|
||||
// RevokeCurrent отзывает текущую сессию. Токен уже проверен BearerAuth,
|
||||
// поэтому здесь его достаточно передать в SessionService.
|
||||
func (h *AuthHandler) RevokeCurrent(c *gin.Context) {
|
||||
token := middleware.CurrentToken(c)
|
||||
if token == "" {
|
||||
respondError(c, &domain.UnauthorizedError{Reason: "нет токена"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.sessions.Revoke(c.Request.Context(), token); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// parseBasicAuth читает Authorization: Basic base64(username:password).
|
||||
func parseBasicAuth(c *gin.Context) (string, string, error) {
|
||||
const prefix = "Basic "
|
||||
|
||||
auth := c.GetHeader("Authorization")
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "требуется Basic"}
|
||||
}
|
||||
|
||||
decoded, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "некорректный Base64"}
|
||||
}
|
||||
|
||||
username, password, ok := strings.Cut(string(decoded), ":")
|
||||
if !ok || username == "" {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "некорректный Basic-формат"}
|
||||
}
|
||||
|
||||
return username, password, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
func bindStrictJSON(c *gin.Context, dst any) error {
|
||||
ct := c.GetHeader("Content-Type")
|
||||
mediaType, _, err := mime.ParseMediaType(ct)
|
||||
if ct == "" || err != nil || !strings.EqualFold(mediaType, "application/json") {
|
||||
return &domain.UnsupportedMediaTypeError{MediaType: ct}
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return &badRequestError{msg: "не удалось прочитать тело запроса"}
|
||||
}
|
||||
_ = c.Request.Body.Close()
|
||||
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return &badRequestError{msg: "тело запроса обязательно"}
|
||||
}
|
||||
return &badRequestError{msg: err.Error()}
|
||||
}
|
||||
|
||||
// Отклоняем любой непустой остаток после первого JSON-значения.
|
||||
var extra json.RawMessage
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return &badRequestError{msg: "тело запроса содержит данные после JSON"}
|
||||
}
|
||||
|
||||
if v := binding.Validator; v != nil {
|
||||
if err := v.ValidateStruct(dst); err != nil {
|
||||
return &badRequestError{msg: err.Error()}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chats *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chats *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chats: chats}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateChatRequest
|
||||
if err := bindStrictJSON(c, &req); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chat, err := h.chats.Create(c.Request.Context(), me.ID, req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.ChatFromDomain(chat))
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.chats.Get(c.Request.Context(), me.ID, chatID)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.ChatFromDomain(chat))
|
||||
}
|
||||
|
||||
func (h *ChatHandler) List(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
limit, cursor, err := parseListQuery(c)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
items, next, err := h.chats.List(c.Request.Context(), me.ID, limit, cursor)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.ChatPageResponse{
|
||||
Items: dto.ChatsFromDomain(items),
|
||||
NextCursor: next,
|
||||
})
|
||||
}
|
||||
|
||||
func parseListQuery(c *gin.Context) (int, *string, error) {
|
||||
limit := 50
|
||||
if v := c.Query("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, nil, &badRequestError{msg: "limit должен быть целым 1..100"}
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
var cursor *string
|
||||
if v := c.Query("cursor"); v != "" {
|
||||
cursor = &v
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
)
|
||||
|
||||
type HealthCheck func(ctx context.Context) error
|
||||
|
||||
type HealthHandler struct {
|
||||
checks []HealthCheck
|
||||
ready *atomic.Bool
|
||||
}
|
||||
|
||||
func NewHealthHandler(checks ...HealthCheck) *HealthHandler {
|
||||
return &HealthHandler{checks: checks}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) WithReadyFlag(v *atomic.Bool) *HealthHandler {
|
||||
h.ready = v
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(c *gin.Context) {
|
||||
if h.ready != nil && !h.ready.Load() {
|
||||
respondError(c, &domain.UnavailableError{Reason: "shutting down"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
for _, check := range h.checks {
|
||||
if check == nil {
|
||||
continue
|
||||
}
|
||||
if err := check(ctx); err != nil {
|
||||
respondError(c, &domain.UnavailableError{Reason: "зависимость недоступна"})
|
||||
return
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type MessageHandler struct {
|
||||
messages *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(messages *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{messages: messages}
|
||||
}
|
||||
|
||||
func (h *MessageHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateMessageRequest
|
||||
if err := bindStrictJSON(c, &req); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
key := c.GetHeader("Idempotency-Key")
|
||||
if key == "" || !idempotencyKeyPattern.MatchString(key) {
|
||||
respondError(c, &badRequestError{
|
||||
msg: "Idempotency-Key обязателен и должен соответствовать ^[A-Za-z0-9._:-]{1,128}$",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.messages.Create(
|
||||
c.Request.Context(),
|
||||
me.ID,
|
||||
chatID,
|
||||
req.Text,
|
||||
key,
|
||||
c.Request.URL.Path,
|
||||
)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Data(result.Status, "application/json", result.Body)
|
||||
}
|
||||
|
||||
func (h *MessageHandler) List(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
limit, cursor, err := parseListQuery(c)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
items, next, err := h.messages.List(c.Request.Context(), me.ID, chatID, limit, cursor)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MessagePageResponse{
|
||||
Items: dto.MessagesFromDomain(items),
|
||||
NextCursor: next,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
)
|
||||
|
||||
type badRequestError struct{ msg string }
|
||||
|
||||
func (e *badRequestError) Error() string { return e.msg }
|
||||
func (e *badRequestError) Unwrap() error { return domain.ErrInvalidInput }
|
||||
func (e *badRequestError) Code() domain.ErrorCode { return domain.CodeInvalidRequest }
|
||||
|
||||
func parseUUIDPathParam(c *gin.Context, name string) (string, error) {
|
||||
raw := c.Param(name)
|
||||
if raw == "" {
|
||||
return "", &badRequestError{msg: "параметр " + name + " обязателен"}
|
||||
}
|
||||
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return "", &badRequestError{msg: "параметр " + name + " должен быть корректным UUID"}
|
||||
}
|
||||
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
func respondError(c *gin.Context, err error) {
|
||||
reqID := middleware.GetRequestID(c)
|
||||
c.JSON(dto.StatusFromError(err), dto.ErrorFromDomain(err, reqID))
|
||||
}
|
||||
|
||||
// respondBasicChallenge выставляет WWW-Authenticate для 401 на /auth/sessions.
|
||||
// На не-401 ответах заголовок не ставится как по контракту нужно
|
||||
func respondBasicChallenge(c *gin.Context, err error) {
|
||||
if dto.StatusFromError(err) == 401 {
|
||||
c.Header("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
respondError(c, err)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
users *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(users *service.UserService) *UserHandler {
|
||||
return &UserHandler{users: users}
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(c *gin.Context) {
|
||||
var req dto.CreateUserRequest
|
||||
if err := bindStrictJSON(c, &req); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := h.users.Create(c.Request.Context(), req.Username, req.DisplayName, req.Password)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.UserFromDomain(u))
|
||||
}
|
||||
|
||||
func (h *UserHandler) Current(c *gin.Context) {
|
||||
u := middleware.CurrentUser(c)
|
||||
if u == nil {
|
||||
respondError(c, &badRequestError{msg: "нет текущего пользователя"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.UserFromDomain(u))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
)
|
||||
|
||||
func Auth(users domain.UserRepository) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader("X-User-Id")
|
||||
if id == "" {
|
||||
abortUnauthorized(c, "требуется X-User-Id")
|
||||
return
|
||||
}
|
||||
|
||||
u, err := users.GetByID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
abortUnauthorized(c, "неизвестный пользователь")
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(CurrentUserKey, u)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func abortUnauthorized(c *gin.Context, msg string) {
|
||||
reqID := GetRequestID(c)
|
||||
body := dto.ErrorFromDomain(
|
||||
&domain.UnauthorizedError{Reason: msg},
|
||||
reqID,
|
||||
)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, body)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
const authTimeout = 3 * time.Second
|
||||
|
||||
// BearerAuth читает Authorization: Bearer <token>, проверяет сессию
|
||||
// через SessionService и кладёт пользователя и токен в контекст.
|
||||
func BearerAuth(sessions *service.SessionService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token, ok := parseBearerToken(c)
|
||||
if !ok {
|
||||
abortBearer(c, "требуется Bearer")
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), authTimeout)
|
||||
defer cancel()
|
||||
|
||||
user, err := sessions.Resolve(ctx, token)
|
||||
if err != nil {
|
||||
abortBearerWithErr(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(CurrentUserKey, user)
|
||||
c.Set(CurrentTokenKey, token)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// parseBearerToken читает Authorization: Bearer <opaque-token>.
|
||||
func parseBearerToken(c *gin.Context) (string, bool) {
|
||||
const prefix = "Bearer "
|
||||
auth := c.GetHeader("Authorization")
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimSpace(auth[len(prefix):])
|
||||
if token == "" {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func abortBearer(c *gin.Context, reason string) {
|
||||
abortBearerWithErr(c, &domain.UnauthorizedError{Reason: reason})
|
||||
}
|
||||
|
||||
// abortBearerWithErr формирует ответ на ошибку аутентификации.
|
||||
// Заголовок WWW-Authenticate: Bearer выставляется только на 401;
|
||||
// при 503 (недоступность БД/кэша) — обычный ответ ошибки без challenge.
|
||||
func abortBearerWithErr(c *gin.Context, err error) {
|
||||
reqID := GetRequestID(c)
|
||||
status := dto.StatusFromError(err)
|
||||
if status == 401 {
|
||||
c.Header("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
c.AbortWithStatusJSON(status, dto.ErrorFromDomain(err, reqID))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
CurrentUserKey = "current_user"
|
||||
CurrentTokenKey = "current_token"
|
||||
)
|
||||
|
||||
func CurrentUser(c *gin.Context) *domain.User {
|
||||
if v, ok := c.Get(CurrentUserKey); ok {
|
||||
if u, ok := v.(*domain.User); ok {
|
||||
return u
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CurrentToken(c *gin.Context) string {
|
||||
if v, ok := c.Get(CurrentTokenKey); ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const InstanceIDHeader = "X-Instance-Id"
|
||||
|
||||
var instanceID = resolveInstanceID()
|
||||
|
||||
func resolveInstanceID() string {
|
||||
if v := os.Getenv("INSTANCE_ID"); v != "" {
|
||||
return v
|
||||
}
|
||||
if v, err := os.Hostname(); err == nil && v != "" {
|
||||
return v
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
|
||||
func Instance() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set(InstanceIDHeader, instanceID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetInstanceID() string { return instanceID }
|
||||
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
RequestIDKey = "request_id"
|
||||
RequestIDHeader = "X-Request-Id"
|
||||
)
|
||||
|
||||
func RequestID() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader(RequestIDHeader)
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
c.Set(RequestIDKey, id)
|
||||
c.Writer.Header().Set(RequestIDHeader, id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetRequestID(c *gin.Context) string {
|
||||
if v, ok := c.Get(RequestIDKey); ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/handler"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
)
|
||||
|
||||
type Handlers struct {
|
||||
Health *handler.HealthHandler
|
||||
User *handler.UserHandler
|
||||
Chat *handler.ChatHandler
|
||||
Message *handler.MessageHandler
|
||||
Auth *handler.AuthHandler
|
||||
}
|
||||
|
||||
func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
|
||||
gin.EnableJsonDecoderDisallowUnknownFields()
|
||||
|
||||
r := gin.New()
|
||||
r.Use(gin.Logger())
|
||||
r.Use(gin.Recovery())
|
||||
r.Use(middleware.RequestID())
|
||||
r.Use(middleware.Instance())
|
||||
|
||||
r.GET("/health/live", h.Health.Live)
|
||||
r.GET("/health/ready", h.Health.Ready)
|
||||
|
||||
api := r.Group("/api/v1")
|
||||
{
|
||||
api.POST("/users", h.User.Create)
|
||||
api.POST("/auth/sessions", h.Auth.CreateSession)
|
||||
}
|
||||
|
||||
protected := api.Group("")
|
||||
protected.Use(auth)
|
||||
{
|
||||
protected.DELETE("/auth/sessions/current", h.Auth.RevokeCurrent)
|
||||
|
||||
protected.GET("/users/me", h.User.Current)
|
||||
protected.POST("/chats", h.Chat.Create)
|
||||
protected.GET("/chats", h.Chat.List)
|
||||
protected.GET("/chats/:chat_id", h.Chat.Get)
|
||||
protected.POST("/chats/:chat_id/messages", h.Message.Create)
|
||||
protected.GET("/chats/:chat_id/messages", h.Message.List)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
Reference in New Issue
Block a user