forked from mtusi2026/mtusi2026lab6
Реализация на 5
This commit is contained in:
@@ -0,0 +1 @@
|
||||
package http
|
||||
@@ -0,0 +1,111 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type AttachmentHandler struct {
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
svc *attachment.Service
|
||||
}
|
||||
|
||||
func NewAttachmentHandler(r router.Router, p jwtprovider.Provider, s *attachment.Service) Handler {
|
||||
return &AttachmentHandler{r, p, s}
|
||||
}
|
||||
func (h *AttachmentHandler) RegisterRoutes() {
|
||||
h.router.Private("POST", "/api/v1/chats/{chat_id}/attachments", h.Upload)
|
||||
h.router.Private("GET", "/api/v1/attachments/{attachment_id}", h.Get)
|
||||
h.router.Private("GET", "/api/v1/attachments/{attachment_id}/content", h.Get)
|
||||
}
|
||||
func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
user, e := framework.ParseToken(r, h.provider)
|
||||
if e != nil {
|
||||
framework.JSONError(r.Context(), w, e)
|
||||
return
|
||||
}
|
||||
id, e := framework.ParseIDFromPathParam(r.Context(), w, r, "chat_id")
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
values := r.URL.Query()["filename"]
|
||||
if len(values) != 1 {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one filename"))
|
||||
return
|
||||
}
|
||||
if !attachment.ValidFilename(values[0]) {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid filename"))
|
||||
return
|
||||
}
|
||||
mt, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if e != nil || (mt != "image/png" && mt != "image/jpeg") {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected PNG or JPEG"))
|
||||
return
|
||||
}
|
||||
if r.ContentLength > h.svc.Config.MaxBytes {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodePayloadTooLarge, "upload too large"))
|
||||
return
|
||||
}
|
||||
a, e := h.svc.Upload(r.Context(), dto.UploadAttachment{UserID: user.UserID, ChatID: id, Filename: values[0], ContentType: mt, Body: io.LimitReader(r.Body, h.svc.Config.MaxBytes+1)})
|
||||
if e != nil {
|
||||
if apperr.CodeFromError(e) == apperr.CodeTooManyRequests {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
}
|
||||
framework.JSONError(r.Context(), w, e)
|
||||
return
|
||||
}
|
||||
framework.JSONResponse(w, http.StatusAccepted, a)
|
||||
}
|
||||
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
user, e := framework.ParseToken(r, h.provider)
|
||||
if e != nil {
|
||||
framework.JSONError(r.Context(), w, e)
|
||||
return
|
||||
}
|
||||
id, e := framework.ParseIDFromPathParam(r.Context(), w, r, "attachment_id")
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !strings.HasSuffix(r.URL.Path, "/content") {
|
||||
a, e := h.svc.Get(r.Context(), user.UserID, id)
|
||||
if e != nil {
|
||||
framework.JSONError(r.Context(), w, e)
|
||||
return
|
||||
}
|
||||
framework.JSONResponse(w, 200, a.Public)
|
||||
return
|
||||
}
|
||||
v := r.URL.Query().Get("variant")
|
||||
if v == "" {
|
||||
v = "original"
|
||||
}
|
||||
if v != "original" && v != "thumbnail" && v != "crop" && v != "optimized" {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid variant"))
|
||||
return
|
||||
}
|
||||
obj, e := h.svc.Content(r.Context(), user.UserID, id, v)
|
||||
if e != nil {
|
||||
framework.JSONError(r.Context(), w, e)
|
||||
return
|
||||
}
|
||||
defer obj.Body.Close()
|
||||
w.Header().Set("Content-Type", obj.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(obj.Size, 10))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
// Once streaming has started a transport failure terminates the response; no JSON
|
||||
// error can be appended to an image. Content-Length exposes incomplete downloads.
|
||||
if _, e = io.Copy(w, obj.Body); e != nil {
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"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/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
router router.Router
|
||||
|
||||
auth auth.API
|
||||
}
|
||||
|
||||
func NewAuthHandler(r router.Router, api auth.API) Handler {
|
||||
return &AuthHandler{
|
||||
router: r,
|
||||
auth: api,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) RegisterRoutes() {
|
||||
h.router.Public(http.MethodPost, "/api/v1/auth/sessions", h.Login)
|
||||
h.router.Private(http.MethodDelete, "/api/v1/auth/sessions/current", h.Logout)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" || password == "" {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "invalid credentials"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.auth.Login(ctx, dto.Login{
|
||||
Username: username,
|
||||
Password: password,
|
||||
})
|
||||
if err != nil {
|
||||
if apperr.HTTPStatusFromError(err) == http.StatusUnauthorized {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.Session{
|
||||
ExpiresAt: resp.ExpiresAt,
|
||||
Token: resp.Tokens.RefreshToken.Payload,
|
||||
TokenType: resp.TokenType,
|
||||
User: contracts.User{
|
||||
CreatedAt: resp.User.CreatedAt,
|
||||
DisplayName: resp.User.DisplayName,
|
||||
Id: resp.User.ID,
|
||||
Username: resp.User.Username,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
token, exists := framework.Token(r)
|
||||
if !exists {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing token in header"))
|
||||
return
|
||||
}
|
||||
|
||||
err := h.auth.Logout(ctx, dto.RefreshToken{
|
||||
Payload: token,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusNoContent, nil)
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"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/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
|
||||
)
|
||||
|
||||
var messageKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type ChatHandler struct {
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
validator *validator.ValidatorImpl
|
||||
|
||||
chat chat.API
|
||||
}
|
||||
|
||||
func NewChatHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api chat.API) Handler {
|
||||
return &ChatHandler{
|
||||
router: r,
|
||||
provider: provider,
|
||||
validator: v,
|
||||
chat: api,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) RegisterRoutes() {
|
||||
h.router.Private(http.MethodPost, "/api/v1/chats", h.Create)
|
||||
h.router.Private(http.MethodGet, "/api/v1/chats", h.Get)
|
||||
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}", h.GetByID)
|
||||
h.router.Private(http.MethodPost, "/api/v1/chats/{chat_id}/messages", h.SendMessage)
|
||||
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}/messages", h.GetMessages)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
var req contracts.CreateChat
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
if userData.UserID == uuid.Nil ||
|
||||
!validText(req.Title, 100) ||
|
||||
len(req.MemberIds) < 1 ||
|
||||
len(req.MemberIds) > 100 {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid chat fields"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.chat.CreateChat(ctx, dto.CreateChat{
|
||||
CreatorID: userData.UserID,
|
||||
Title: req.Title,
|
||||
MemberIDs: req.MemberIds,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.Chat{
|
||||
Id: resp.ID,
|
||||
Title: resp.Title,
|
||||
MemberIds: resp.MemberIDs,
|
||||
CreatedAt: resp.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
limit, afterID, ok := framework.PageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if userData.UserID == uuid.Nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user id"))
|
||||
return
|
||||
}
|
||||
if afterID != nil && *afterID == uuid.Nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.chat.ListForMember(ctx, dto.ChatFilters{
|
||||
UserID: userData.UserID,
|
||||
Limit: limit,
|
||||
AfterID: afterID,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]contracts.Chat, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, contracts.Chat{
|
||||
CreatedAt: item.CreatedAt,
|
||||
Id: item.ID,
|
||||
MemberIds: item.MemberIDs,
|
||||
Title: item.Title,
|
||||
})
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.ChatPage{
|
||||
Items: items,
|
||||
NextCursor: cursorString(page.NextCursorID),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetByID(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.chat.GetForMember(ctx, dto.ChatMember{
|
||||
UserID: userData.UserID,
|
||||
ChatID: chatID,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Chat{
|
||||
CreatedAt: resp.CreatedAt,
|
||||
Id: resp.ID,
|
||||
MemberIds: resp.MemberIDs,
|
||||
Title: resp.Title,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
keyValues := r.Header.Values("Idempotency-Key")
|
||||
if len(keyValues) != 1 || !messageKeyPattern.MatchString(keyValues[0]) {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid idempotency key"))
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Text *string `json:"text"`
|
||||
AttachmentIDs json.RawMessage `json:"attachment_ids"`
|
||||
}
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
if req.Text == nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "text is required"))
|
||||
return
|
||||
}
|
||||
|
||||
ids := []uuid.UUID{}
|
||||
if len(req.AttachmentIDs) > 0 {
|
||||
if bytes.Equal(bytes.TrimSpace(req.AttachmentIDs), []byte("null")) || json.Unmarshal(req.AttachmentIDs, &ids) != nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid attachment_ids"))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
message, err := h.chat.CreateMessage(ctx, dto.CreateMessage{
|
||||
IdempotencyKey: keyValues[0],
|
||||
ChatID: chatID,
|
||||
SenderID: userData.UserID,
|
||||
Text: *req.Text,
|
||||
AttachmentIDs: ids,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.Message{
|
||||
Id: message.ID,
|
||||
ChatId: message.ChatID,
|
||||
SenderId: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
AttachmentIds: message.AttachmentIDs,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
limit, afterID, ok := framework.PageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.chat.ListForChat(ctx, dto.MessageFilters{
|
||||
ChatID: chatID,
|
||||
UserID: userData.UserID,
|
||||
Limit: limit,
|
||||
AfterID: afterID,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]contracts.Message, 0, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
items = append(items, contracts.Message{
|
||||
Id: message.ID,
|
||||
ChatId: message.ChatID,
|
||||
SenderId: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
AttachmentIds: message.AttachmentIDs,
|
||||
})
|
||||
}
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.MessagePage{Items: items, NextCursor: cursorString(page.NextCursorID)})
|
||||
}
|
||||
|
||||
func cursorString(id *uuid.UUID) *string {
|
||||
if id == nil {
|
||||
return nil
|
||||
}
|
||||
value := id.String()
|
||||
return &value
|
||||
}
|
||||
|
||||
func validText(value string, maxLength int) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxLength
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
)
|
||||
|
||||
type Server interface {
|
||||
ShouldBeRunning() bool
|
||||
Ready() bool
|
||||
Start(ctx context.Context) error
|
||||
Stop(ctx context.Context) error
|
||||
}
|
||||
|
||||
type server struct {
|
||||
server http.Server
|
||||
cfg *config.Server
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
func New(cfg *config.Config, router router.Router) Server {
|
||||
s := server{
|
||||
server: http.Server{
|
||||
Addr: cfg.Server.BindAddress(),
|
||||
Handler: router,
|
||||
ReadTimeout: cfg.Server.ReadTimeout,
|
||||
WriteTimeout: cfg.Server.WriteTimeout,
|
||||
IdleTimeout: cfg.Server.IdleTimeout,
|
||||
},
|
||||
cfg: cfg.Server,
|
||||
ready: atomic.Bool{},
|
||||
}
|
||||
|
||||
if err := s.validate(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return &s
|
||||
}
|
||||
|
||||
func (s *server) Start(_ context.Context) error {
|
||||
if !s.ShouldBeRunning() {
|
||||
slog.Info("server should not be running: skip starting")
|
||||
return nil
|
||||
}
|
||||
listener, err := net.Listen("tcp", s.server.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.ready.Store(true)
|
||||
go func() {
|
||||
defer s.ready.Store(false)
|
||||
if err := s.server.Serve(listener); err != nil &&
|
||||
!errors.Is(err, http.ErrServerClosed) {
|
||||
slog.Error("rest server failed", "error", err)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *server) Stop(ctx context.Context) error {
|
||||
if !s.ShouldBeRunning() {
|
||||
slog.Info("server should not be running: skip stopping")
|
||||
return nil
|
||||
}
|
||||
|
||||
slog.Info("shutting down rest server...", "address", s.server.Addr)
|
||||
s.ready.Store(false)
|
||||
if err := s.server.Shutdown(ctx); err != nil {
|
||||
slog.Error("rest server shutdown failed", "error", err)
|
||||
_ = s.server.Close()
|
||||
return err
|
||||
}
|
||||
slog.Info("rest server shutdown successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *server) ShouldBeRunning() bool {
|
||||
return s.cfg.Enabled
|
||||
}
|
||||
|
||||
func (s *server) Ready() bool {
|
||||
return s.ready.Load()
|
||||
}
|
||||
|
||||
func (s *server) validate() error {
|
||||
if s.cfg == nil {
|
||||
slog.Error("failed to validate server: provided nil config")
|
||||
return errors.New("failed to validate server: provided nil config")
|
||||
}
|
||||
|
||||
slog.Info("server successfully validated")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package http
|
||||
|
||||
type Handler interface {
|
||||
RegisterRoutes()
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
)
|
||||
|
||||
type databasePinger interface{ Ping(context.Context) error }
|
||||
|
||||
type HealthHandler struct {
|
||||
router router.Router
|
||||
server Server
|
||||
database databasePinger
|
||||
storage []databasePinger
|
||||
}
|
||||
|
||||
func NewHealthHandler(r router.Router, server Server, database databasePinger, storage ...databasePinger) Handler {
|
||||
return &HealthHandler{
|
||||
router: r,
|
||||
server: server,
|
||||
database: database,
|
||||
storage: storage,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) RegisterRoutes() {
|
||||
h.router.Public(http.MethodGet, "/health/ready", h.Ready)
|
||||
h.router.Public(http.MethodGet, "/health/live", h.Live)
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, _ *http.Request) {
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.server.Ready() {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready"))
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := h.database.Ping(ctx); err != nil {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "database unavailable"))
|
||||
return
|
||||
}
|
||||
for _, dependency := range h.storage {
|
||||
if err := dependency.Ping(ctx); err != nil {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "storage unavailable"))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
package http
|
||||
@@ -0,0 +1,113 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"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/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/user"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
validator *validator.ValidatorImpl
|
||||
|
||||
user user.API
|
||||
}
|
||||
|
||||
func NewUserHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api user.API) Handler {
|
||||
return &UserHandler{
|
||||
router: r,
|
||||
provider: provider,
|
||||
validator: v,
|
||||
user: api,
|
||||
}
|
||||
}
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func (h *UserHandler) RegisterRoutes() {
|
||||
h.router.Public(http.MethodPost, "/api/v1/users", h.Create)
|
||||
h.router.Private(http.MethodGet, "/api/v1/users/me", h.GetMe)
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
var req contracts.CreateUser
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
toCreate := dto.CreateUser{
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
}
|
||||
|
||||
if req.Password != nil {
|
||||
toCreate.Password = *req.Password
|
||||
}
|
||||
|
||||
if !usernamePattern.MatchString(req.Username) || !utf8.ValidString(req.DisplayName) ||
|
||||
strings.TrimSpace(req.DisplayName) == "" || utf8.RuneCountInString(req.DisplayName) > 100 {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user fields"))
|
||||
return
|
||||
}
|
||||
passwordLen := utf8.RuneCountInString(toCreate.Password)
|
||||
if !utf8.ValidString(toCreate.Password) || strings.TrimSpace(toCreate.Password) == "" || passwordLen < 12 || passwordLen > 128 {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid password"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.user.Create(ctx, toCreate)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.User{
|
||||
CreatedAt: resp.CreatedAt,
|
||||
DisplayName: resp.DisplayName,
|
||||
Id: resp.ID,
|
||||
Username: resp.Username,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
if userData.UserID == uuid.Nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user id"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.user.GetByID(ctx, userData.UserID)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.User{
|
||||
CreatedAt: resp.CreatedAt,
|
||||
DisplayName: resp.DisplayName,
|
||||
Id: resp.ID,
|
||||
Username: resp.Username,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user