This commit is contained in:
@@ -28,6 +28,6 @@ func createChatRequestToDomain(request dto.CreateChatRequest) domain.Chat {
|
||||
|
||||
func createChatResponseFromDomain(chat domain.Chat) dto.CreateChatResponse {
|
||||
return dto.CreateChatResponse{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,6 @@ func createMessageRequestToDomain(request dto.CreateMessageRequest) domain.Messa
|
||||
func createMessageResponseFromDomain(message domain.Message) dto.CreateMessageResponse {
|
||||
return dto.CreateMessageResponse{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, CreatedAt: message.CreatedAt,
|
||||
Text: message.Text, CreatedAt: dto.Timestamp(message.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ func (h *Chat) createUser(c echo.Context) error {
|
||||
if err := decodeJSON(c, &request); err != nil {
|
||||
return h.jsonError(c, err)
|
||||
}
|
||||
user, err := h.useCase.CreateUser(c.Request().Context(), createUserRequestToDomain(request))
|
||||
user, err := h.useCase.CreateUser(c.Request().Context(), createUserRequestToDomain(request), request.Password)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
@@ -27,6 +27,6 @@ func createUserRequestToDomain(request dto.CreateUserRequest) domain.User {
|
||||
|
||||
func createUserResponseFromDomain(user domain.User) dto.CreateUserResponse {
|
||||
return dto.CreateUserResponse{
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt,
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,6 @@ func (h *Chat) currentUser(c echo.Context) error {
|
||||
|
||||
func currentUserResponseFromDomain(user domain.User) dto.CurrentUserResponse {
|
||||
return dto.CurrentUserResponse{
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt,
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package chat
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
@@ -24,14 +23,6 @@ type cursorCodec struct {
|
||||
secret [32]byte
|
||||
}
|
||||
|
||||
func newCursorCodec() cursorCodec {
|
||||
var codec cursorCodec
|
||||
if _, err := rand.Read(codec.secret[:]); err != nil {
|
||||
panic("cannot initialize cursor signing key: " + err.Error())
|
||||
}
|
||||
return codec
|
||||
}
|
||||
|
||||
func (c cursorCodec) encode(scope, owner string, createdAt time.Time, id string) string {
|
||||
payload, err := json.Marshal(cursorPayload{
|
||||
Scope: scope,
|
||||
|
||||
@@ -33,10 +33,17 @@ func (h *Chat) useCaseError(c echo.Context, err error) error {
|
||||
}
|
||||
status := http.StatusInternalServerError
|
||||
switch applicationError.Code {
|
||||
case domain.ErrorUnavailable:
|
||||
status = http.StatusServiceUnavailable
|
||||
case domain.ErrorInvalid:
|
||||
status = http.StatusBadRequest
|
||||
case domain.ErrorUnauthorized:
|
||||
status = http.StatusUnauthorized
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if c.Path() == "/api/v1/auth/sessions" {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
c.Response().Header().Set("WWW-Authenticate", challenge)
|
||||
case domain.ErrorNotFound:
|
||||
status = http.StatusNotFound
|
||||
case domain.ErrorConflict:
|
||||
|
||||
@@ -27,6 +27,6 @@ func getChatRequestToDomain(request dto.GetChatRequest) domain.Chat {
|
||||
|
||||
func getChatResponseFromDomain(chat domain.Chat) dto.GetChatResponse {
|
||||
return dto.GetChatResponse{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ func listChatsResponseFromDomain(page domain.ChatPage, nextCursor *string) dto.L
|
||||
items := make([]dto.ListChatsItem, 0, len(page.Items))
|
||||
for _, chat := range page.Items {
|
||||
items = append(items, dto.ListChatsItem{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
|
||||
})
|
||||
}
|
||||
return dto.ListChatsResponse{Items: items, NextCursor: nextCursor}
|
||||
|
||||
@@ -63,7 +63,7 @@ func listMessagesResponseFromDomain(page domain.MessagePage, nextCursor *string)
|
||||
for _, message := range page.Items {
|
||||
items = append(items, dto.ListMessagesItem{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, CreatedAt: message.CreatedAt,
|
||||
Text: message.Text, CreatedAt: dto.Timestamp(message.CreatedAt),
|
||||
})
|
||||
}
|
||||
return dto.ListMessagesResponse{Items: items, NextCursor: nextCursor}
|
||||
|
||||
@@ -23,7 +23,7 @@ func (h *Chat) requestIDMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
|
||||
func (h *Chat) authenticate(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
user, err := h.useCase.Authenticate(c.Request().Context(), c.Request().Header.Get("X-User-Id"))
|
||||
user, err := h.useCase.Authenticate(c.Request().Context(), bearerToken(c))
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
|
||||
@@ -9,5 +9,8 @@ import (
|
||||
)
|
||||
|
||||
func (h *Chat) readiness(c echo.Context) error {
|
||||
if err := h.useCase.Ready(c.Request().Context()); err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, dto.ReadinessResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
@@ -14,8 +14,8 @@ type Chat struct {
|
||||
cursor cursorCodec
|
||||
}
|
||||
|
||||
func NewChat(useCase UseCase) *Chat {
|
||||
return &Chat{useCase: useCase, cursor: newCursorCodec()}
|
||||
func NewChat(useCase UseCase, cursorKey [32]byte) *Chat {
|
||||
return &Chat{useCase: useCase, cursor: cursorCodec{secret: cursorKey}}
|
||||
}
|
||||
|
||||
func (h *Chat) Router() *echo.Echo {
|
||||
@@ -60,8 +60,11 @@ func (h *Chat) Router() *echo.Echo {
|
||||
e.GET("/swagger/*", swaggerUI)
|
||||
e.POST("/api/v1/users", h.createUser)
|
||||
|
||||
e.POST("/api/v1/auth/sessions", h.createSession)
|
||||
|
||||
api := e.Group("/api/v1", h.authenticate)
|
||||
api.GET("/users/me", h.currentUser)
|
||||
api.DELETE("/auth/sessions/current", h.deleteSession)
|
||||
api.POST("/chats", h.createChat)
|
||||
api.GET("/chats", h.listChats)
|
||||
api.GET("/chats/:chat_id", h.getChat)
|
||||
|
||||
@@ -2,6 +2,8 @@ package chat_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -13,12 +15,14 @@ import (
|
||||
"time"
|
||||
|
||||
chathandler "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
|
||||
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||
)
|
||||
|
||||
type testAPI struct {
|
||||
server *httptest.Server
|
||||
tokens sync.Map
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
@@ -47,8 +51,8 @@ type errorResponse struct {
|
||||
|
||||
func newTestAPI(t *testing.T) *testAPI {
|
||||
t.Helper()
|
||||
useCase := chatusecase.New(repository.NewMemory())
|
||||
server := httptest.NewServer(chathandler.NewChat(useCase).Router())
|
||||
useCase := chatusecase.New(repository.NewMemory(), &testSessions{values: map[string]domain.Session{}}, time.Hour)
|
||||
server := httptest.NewServer(chathandler.NewChat(useCase, [32]byte{1}).Router())
|
||||
t.Cleanup(server.Close)
|
||||
return &testAPI{server: server}
|
||||
}
|
||||
@@ -63,7 +67,8 @@ func (a *testAPI) request(t *testing.T, client *http.Client, method, path, actor
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if actorID != "" {
|
||||
request.Header.Set("X-User-Id", actorID)
|
||||
token, _ := a.tokens.Load(actorID)
|
||||
request.Header.Set("Authorization", "Bearer "+token.(string))
|
||||
}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
@@ -91,7 +96,27 @@ func (a *testAPI) createUser(t *testing.T, username string) userResponse {
|
||||
t.Helper()
|
||||
var user userResponse
|
||||
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/users", "",
|
||||
fmt.Sprintf(`{"username":%q,"display_name":%q}`, username, username), http.StatusCreated, &user)
|
||||
fmt.Sprintf(`{"username":%q,"display_name":%q,"password":"test-password-12345"}`, username, username), http.StatusCreated, &user)
|
||||
req, err := http.NewRequest(http.MethodPost, a.server.URL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":test-password-12345")))
|
||||
response, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
var login struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("login status: %d", response.StatusCode)
|
||||
}
|
||||
if err = json.NewDecoder(response.Body).Decode(&login); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.tokens.Store(user.ID, login.Token)
|
||||
return user
|
||||
}
|
||||
|
||||
@@ -153,7 +178,7 @@ func TestRejectsDuplicateUsername(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.createUser(t, "duplicate_user")
|
||||
api.requestError(t, http.MethodPost, "/api/v1/users", "",
|
||||
`{"username":"duplicate_user","display_name":"Duplicate"}`, http.StatusConflict, "conflict")
|
||||
`{"username":"duplicate_user","display_name":"Duplicate","password":"test-password-12345"}`, http.StatusConflict, "conflict")
|
||||
}
|
||||
|
||||
func TestPaginatesMessagesAcrossMultiplePages(t *testing.T) {
|
||||
@@ -232,7 +257,8 @@ func TestConcurrentMessagesAreUnique(t *testing.T) {
|
||||
return
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-User-Id", users[clientIndex].ID)
|
||||
token, _ := api.tokens.Load(users[clientIndex].ID)
|
||||
request.Header.Set("Authorization", "Bearer "+token.(string))
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
@@ -294,3 +320,30 @@ func TestConcurrentMessagesAreUnique(t *testing.T) {
|
||||
len(seenIDs), len(seenTexts), 10*10)
|
||||
}
|
||||
}
|
||||
|
||||
// Session fake is only used by HTTP unit tests; the server always uses Redis.
|
||||
type testSessions struct {
|
||||
mu sync.Mutex
|
||||
values map[string]domain.Session
|
||||
}
|
||||
|
||||
func (s *testSessions) Ready(context.Context) error { return nil }
|
||||
func (s *testSessions) Put(_ context.Context, key string, value domain.Session) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.values[key] = value
|
||||
return nil
|
||||
}
|
||||
func (s *testSessions) Get(_ context.Context, key string) (domain.Session, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
value, ok := s.values[key]
|
||||
return value, ok, nil
|
||||
}
|
||||
func (s *testSessions) Delete(_ context.Context, key string) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, ok := s.values[key]
|
||||
delete(s.values, key)
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"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, "Тело запроса входа должно быть пустым")
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -8,8 +8,11 @@ import (
|
||||
|
||||
// UseCase is the application boundary required by the HTTP handler.
|
||||
type UseCase interface {
|
||||
Authenticate(ctx context.Context, rawUserID string) (domain.User, error)
|
||||
CreateUser(ctx context.Context, user domain.User) (domain.User, error)
|
||||
Ready(context.Context) error
|
||||
CreateSession(context.Context, string, string) (domain.Login, error)
|
||||
DeleteSession(context.Context, string) error
|
||||
Authenticate(ctx context.Context, token string) (domain.User, error)
|
||||
CreateUser(ctx context.Context, user domain.User, password string) (domain.User, error)
|
||||
CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
|
||||
GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
|
||||
ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error)
|
||||
|
||||
Reference in New Issue
Block a user