forked from mtusi2026/mtusi2026lab6
Реализация на 5
This commit is contained in:
@@ -0,0 +1,257 @@
|
||||
package framework
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
v10 "github.com/go-playground/validator/v10"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
)
|
||||
|
||||
func validate(ctx context.Context, v *validator.ValidatorImpl, value any) error {
|
||||
err := v.ValidateCtx(ctx, value)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var fieldErrors v10.ValidationErrors
|
||||
if errors.As(err, &fieldErrors) {
|
||||
return apperr.Wrap(err, apperr.CodeValidation, "invalid request fields")
|
||||
}
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "validation failed")
|
||||
}
|
||||
|
||||
func Validate(w http.ResponseWriter, r *http.Request, v *validator.ValidatorImpl, value any) bool {
|
||||
if err := validate(r.Context(), v, value); err != nil {
|
||||
JSONError(r.Context(), w, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func JSONResponse(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set(headers.HeaderContentType, "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if status == http.StatusNoContent {
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
wrapped := apperr.Wrap(err, apperr.CodeInternal, "failed json encode")
|
||||
slog.Error("response", "error", wrapped)
|
||||
}
|
||||
}
|
||||
|
||||
func JSONError(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
requestId, ok := ctx.Value(headers.HeaderRequestID).(uuid.UUID)
|
||||
if !ok {
|
||||
requestId = uuid.New()
|
||||
}
|
||||
w.Header().Set(headers.HeaderRequestID, requestId.String())
|
||||
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
err = apperr.Wrap(err, apperr.CodeServiceUnavailable, "request deadline exceeded")
|
||||
}
|
||||
appErr := apperr.As(err)
|
||||
if appErr == nil {
|
||||
appErr = apperr.As(apperr.New(apperr.CodeInternal, "internal server error"))
|
||||
}
|
||||
if appErr.Code().HTTPStatus() == http.StatusUnauthorized && w.Header().Get("WWW-Authenticate") == "" {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
|
||||
slog.ErrorContext(ctx, "http_error", "error_code", appErr.Code().String(), "status", appErr.Code().HTTPStatus(), "request_id", requestId.String())
|
||||
|
||||
var code contracts.ErrorErrorCode
|
||||
switch appErr.Code() {
|
||||
case apperr.CodeBadRequest, apperr.CodeValidation:
|
||||
code = contracts.InvalidRequest
|
||||
case apperr.CodeUnauthorized:
|
||||
code = contracts.Unauthorized
|
||||
case apperr.CodeNotFound:
|
||||
code = contracts.NotFound
|
||||
case apperr.CodeAlreadyExists, apperr.CodeConflict:
|
||||
code = contracts.Conflict
|
||||
case apperr.CodePayloadTooLarge:
|
||||
code = contracts.PayloadTooLarge
|
||||
case apperr.CodeTooManyRequests:
|
||||
code = contracts.RateLimited
|
||||
case apperr.CodeServiceUnavailable, apperr.CodeUnavailable:
|
||||
code = contracts.Unavailable
|
||||
case apperr.CodeUnsupportedMediaType:
|
||||
code = contracts.UnsupportedMediaType
|
||||
default:
|
||||
code = contracts.InternalError
|
||||
}
|
||||
JSONResponse(w, appErr.Code().HTTPStatus(), contracts.Error{
|
||||
Error: struct {
|
||||
Code contracts.ErrorErrorCode `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestId string `json:"request_id"`
|
||||
}{
|
||||
Code: code,
|
||||
Message: appErr.Message(),
|
||||
RequestId: requestId.String(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func Decode(w http.ResponseWriter, r *http.Request, object any) bool {
|
||||
mediaType, params, err := mime.ParseMediaType(r.Header.Get(headers.HeaderContentType))
|
||||
if err != nil || mediaType != "application/json" ||
|
||||
(params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected application/json"))
|
||||
return false
|
||||
}
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(object); err != nil {
|
||||
JSONError(r.Context(), w, apperr.Wrap(err, apperr.CodeBadRequest, "failed decode"))
|
||||
return false
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); err != io.EOF {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one JSON object"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func PathParam(r *http.Request, key string) string {
|
||||
return chi.URLParam(r, key)
|
||||
}
|
||||
|
||||
func QueryParam(r *http.Request, key string) string {
|
||||
return r.URL.Query().Get(key)
|
||||
}
|
||||
|
||||
func HeaderParam(r *http.Request, key string) string {
|
||||
return r.Header.Get(key)
|
||||
}
|
||||
|
||||
func ParseIDFromPathParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := PathParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func ParseIDFromQueryParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := QueryParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func ParseIDFromHeaderParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := HeaderParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing or invalid user ID"))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func Header(r *http.Request, header string) (string, bool) {
|
||||
return r.Header.Get(header), r.Header.Get(header) != ""
|
||||
}
|
||||
|
||||
func Token(r *http.Request) (string, bool) {
|
||||
foundHeader := r.Header.Get(headers.HeaderAuthorization)
|
||||
if foundHeader == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
token, found := strings.CutPrefix(foundHeader, "Bearer ")
|
||||
if !found {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return token, true
|
||||
}
|
||||
|
||||
type sessionContextKey struct{}
|
||||
|
||||
func WithVerifiedSession(r *http.Request, data *dto.UserDataInToken) *http.Request {
|
||||
return r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, *data))
|
||||
}
|
||||
|
||||
func ParseToken(r *http.Request, provider jwtprovider.Provider) (*dto.UserDataInToken, error) {
|
||||
if data, ok := r.Context().Value(sessionContextKey{}).(dto.UserDataInToken); ok {
|
||||
return &data, nil
|
||||
}
|
||||
foundHeader := r.Header.Get(headers.HeaderAuthorization)
|
||||
if foundHeader == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "missing authorization header")
|
||||
}
|
||||
|
||||
token, found := strings.CutPrefix(foundHeader, "Bearer ")
|
||||
if !found {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid authorization header")
|
||||
}
|
||||
|
||||
userData, err := provider.ParseVerified(&dto.Token{Payload: token})
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeUnauthorized, "invalid token")
|
||||
}
|
||||
|
||||
return userData, nil
|
||||
}
|
||||
|
||||
func PageParams(w http.ResponseWriter, r *http.Request) (*int, *uuid.UUID, bool) {
|
||||
query := r.URL.Query()
|
||||
var limit *int
|
||||
if values, exists := query["limit"]; exists {
|
||||
if len(values) != 1 {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
value, err := strconv.Atoi(values[0])
|
||||
if err != nil || value < 1 || value > 100 {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
limit = &value
|
||||
}
|
||||
var afterID *uuid.UUID
|
||||
if values, exists := query["cursor"]; exists {
|
||||
if len(values) != 1 {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
id, err := uuid.Parse(values[0])
|
||||
if err != nil || id == uuid.Nil {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
afterID = &id
|
||||
}
|
||||
return limit, afterID, true
|
||||
}
|
||||
Reference in New Issue
Block a user