forked from mtusi2026/mtusi2026lab3
feat: implement lab3 load balancing and idempotency
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
store *storage.ChatStore
|
||||
}
|
||||
|
||||
func NewChatHandler(store *storage.ChatStore) *ChatHandler {
|
||||
return &ChatHandler{store: store}
|
||||
}
|
||||
|
||||
type createChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
}
|
||||
|
||||
type chatPage struct {
|
||||
Items []model.Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
var req createChatRequest
|
||||
if err := decodeOneObject(r, &req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
title := strings.TrimSpace(req.Title)
|
||||
titleLength := utf8.RuneCountInString(title)
|
||||
|
||||
if titleLength < 1 || titleLength > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "title must contain from 1 to 100 characters")
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.MemberIDs) < 1 || len(req.MemberIDs) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member_ids must contain from 1 to 100 users")
|
||||
return
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(req.MemberIDs))
|
||||
currentUserIsMember := false
|
||||
|
||||
for _, memberID := range req.MemberIDs {
|
||||
if _, exists := seen[memberID]; exists {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member_ids must contain unique users")
|
||||
return
|
||||
}
|
||||
seen[memberID] = struct{}{}
|
||||
|
||||
if memberID == currentUser.ID {
|
||||
currentUserIsMember = true
|
||||
}
|
||||
}
|
||||
|
||||
if !currentUserIsMember {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "current user must be a chat member")
|
||||
return
|
||||
}
|
||||
|
||||
for _, memberID := range req.MemberIDs {
|
||||
exists, err := h.store.ExistsUser(r.Context(), memberID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member does not exist")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
chat := model.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: req.MemberIDs,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err := h.store.CreateChat(r.Context(), chat)
|
||||
if errors.Is(err, storage.ErrInvalidMember) {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "member does not exist")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
limit := 50
|
||||
if values, exists := r.URL.Query()["limit"]; exists {
|
||||
if len(values) != 1 {
|
||||
writeError(w, r, 400, "invalid_request", "invalid limit")
|
||||
return
|
||||
}
|
||||
n, err := strconv.Atoi(values[0])
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
writeError(w, r, 400, "invalid_request", "limit must be between 1 and 100")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
var cursorTime *time.Time
|
||||
var cursorID *uuid.UUID
|
||||
if values, exists := r.URL.Query()["cursor"]; exists {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
writeError(w, r, 400, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
t, id, err := decodeChatCursor(values[0], currentUser.ID)
|
||||
if err != nil {
|
||||
writeError(w, r, 400, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
cursorTime = &t
|
||||
cursorID = &id
|
||||
}
|
||||
chats, more, err := h.store.ListChatsPage(r.Context(), currentUser.ID, limit, cursorTime, cursorID)
|
||||
if err != nil {
|
||||
writeError(w, r, 503, "unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
var next *string
|
||||
if more && len(chats) > 0 {
|
||||
c := encodeChatCursor(currentUser.ID, chats[len(chats)-1])
|
||||
next = &c
|
||||
}
|
||||
writeJSON(w, 200, chatPage{Items: chats, NextCursor: next})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.GetChatForUser(
|
||||
r.Context(), chatID, currentUser.ID,
|
||||
)
|
||||
if errors.Is(err, storage.ErrChatNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
func encodeChatCursor(userID uuid.UUID, chat model.Chat) string {
|
||||
value := fmt.Sprintf("%s|%s|%s", userID, chat.CreatedAt.Format(time.RFC3339Nano), chat.ID)
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
func decodeChatCursor(cursor string, userID uuid.UUID) (time.Time, uuid.UUID, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
parts := strings.Split(string(data), "|")
|
||||
if len(parts) != 3 || parts[0] != userID.String() {
|
||||
return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor")
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
return t, id, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// decodeOneObject rejects a second JSON value, trailing garbage and unknown fields.
|
||||
func decodeOneObject(r *http.Request, target any) error {
|
||||
dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(target); err != nil {
|
||||
return err
|
||||
}
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("multiple JSON values")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func requireEmptyBody(r *http.Request) error {
|
||||
// A whitespace-only body is accepted as empty; any JSON or other bytes are not.
|
||||
data, err := io.ReadAll(io.LimitReader(r.Body, 2))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) != 0 {
|
||||
return errors.New("request body must be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type MessageHandler struct {
|
||||
chats *storage.ChatStore
|
||||
messages *storage.MessageStore
|
||||
}
|
||||
|
||||
func NewMessageHandler(
|
||||
chats *storage.ChatStore,
|
||||
messages *storage.MessageStore,
|
||||
) *MessageHandler {
|
||||
return &MessageHandler{
|
||||
chats: chats,
|
||||
messages: messages,
|
||||
}
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type messagePage struct {
|
||||
Items []model.Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func (h *MessageHandler) accessibleChat(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) (uuid.UUID, bool) {
|
||||
currentUser, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid chat id")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
_, err = h.chats.GetChatForUser(
|
||||
r.Context(), chatID, currentUser.ID,
|
||||
)
|
||||
if errors.Is(err, storage.ErrChatNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
|
||||
return chatID, true
|
||||
}
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyPattern.MatchString(key) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid or missing Idempotency-Key")
|
||||
return
|
||||
}
|
||||
|
||||
chatID, ok := h.accessibleChat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
currentUser, _ := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
var req createMessageRequest
|
||||
if err := decodeOneObject(r, &req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
textLength := utf8.RuneCountInString(req.Text)
|
||||
if strings.TrimSpace(req.Text) == "" || textLength > 4000 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "text must contain from 1 to 4000 characters")
|
||||
return
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: currentUser.ID,
|
||||
Text: req.Text,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
message, err := h.messages.CreateMessageIdempotent(r.Context(), message, key)
|
||||
if errors.Is(err, storage.ErrIdempotencyConflict) {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "Idempotency-Key reused with different body")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, storage.ErrMessageMemberNotFound) {
|
||||
writeError(w, r, http.StatusNotFound,
|
||||
"not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
}
|
||||
|
||||
func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, ok := h.accessibleChat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
limit := 50
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "limit must be between 1 and 100")
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
|
||||
var cursorTime *time.Time
|
||||
var cursorID *uuid.UUID
|
||||
|
||||
if raw := r.URL.Query().Get("cursor"); raw != "" {
|
||||
t, id, err := decodeMessageCursor(raw, chatID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
cursorTime = &t
|
||||
cursorID = &id
|
||||
}
|
||||
|
||||
items, hasMore, err := h.messages.ListMessages(
|
||||
r.Context(), chatID, limit, cursorTime, cursorID,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
var nextCursor *string
|
||||
if hasMore && len(items) > 0 {
|
||||
cursor := encodeMessageCursor(items[len(items)-1])
|
||||
nextCursor = &cursor
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, messagePage{
|
||||
Items: items,
|
||||
NextCursor: nextCursor,
|
||||
})
|
||||
}
|
||||
|
||||
// Cursor contains the chat UUID to prevent cross-chat replay.
|
||||
func encodeMessageCursor(message model.Message) string {
|
||||
value := fmt.Sprintf("%s|%s|%s", message.ChatID, message.CreatedAt.Format(time.RFC3339Nano), message.ID)
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
|
||||
func decodeMessageCursor(cursor string, chatID uuid.UUID) (time.Time, uuid.UUID, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
parts := strings.Split(string(data), "|")
|
||||
if len(parts) != 3 || parts[0] != chatID.String() {
|
||||
return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor for chat")
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
return t, id, nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestStrictJSON(t *testing.T) {
|
||||
for _, body := range []string{`{"text":"hello"} garbage`, `{"text":"hello"}{"text":"again"}`} {
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(body))
|
||||
var v createMessageRequest
|
||||
if err := decodeOneObject(req, &v); err == nil {
|
||||
t.Fatalf("accepted trailing JSON: %q", body)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestMessageCursorBoundToChat(t *testing.T) {
|
||||
chatA, chatB := uuid.New(), uuid.New()
|
||||
cursor := encodeMessageCursor(model.Message{ID: uuid.New(), ChatID: chatA, CreatedAt: time.Now().UTC()})
|
||||
if _, _, err := decodeMessageCursor(cursor, chatA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := decodeMessageCursor(cursor, chatB); err == nil {
|
||||
t.Fatal("accepted cursor for another chat")
|
||||
}
|
||||
}
|
||||
func TestChatCursorBoundToUser(t *testing.T) {
|
||||
a, b := uuid.New(), uuid.New()
|
||||
cursor := encodeChatCursor(a, model.Chat{ID: uuid.New(), CreatedAt: time.Now().UTC()})
|
||||
if _, _, err := decodeChatCursor(cursor, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := decodeChatCursor(cursor, b); err == nil {
|
||||
t.Fatal("accepted cursor for another user")
|
||||
}
|
||||
}
|
||||
func TestEmptyLoginBody(t *testing.T) {
|
||||
req := httptest.NewRequest("POST", "/", strings.NewReader(`{"ignored":true}`))
|
||||
if err := requireEmptyBody(req); err == nil {
|
||||
t.Fatal("accepted login body")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Error errorBody `json:"error"`
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, data any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func writeError(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
status int,
|
||||
code string,
|
||||
message string,
|
||||
) {
|
||||
writeJSON(w, status, errorResponse{
|
||||
Error: errorBody{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: middleware.GetRequestID(r.Context()),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type SessionHandler struct {
|
||||
users *storage.AuthStore
|
||||
sessions *storage.SessionService
|
||||
}
|
||||
|
||||
func NewSessionHandler(
|
||||
users *storage.AuthStore,
|
||||
sessions *storage.SessionService,
|
||||
) *SessionHandler {
|
||||
return &SessionHandler{
|
||||
users: users,
|
||||
sessions: sessions,
|
||||
}
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User interface{} `json:"user"`
|
||||
}
|
||||
|
||||
func sessionTTL() time.Duration {
|
||||
seconds := 3600
|
||||
|
||||
if raw := os.Getenv("SESSION_TTL_SECONDS"); raw != "" {
|
||||
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
||||
seconds = n
|
||||
}
|
||||
}
|
||||
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
|
||||
if err := requireEmptyBody(r); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "request body must be empty")
|
||||
return
|
||||
}
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" || password == "" {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
user, passwordHash, err := h.users.GetUserByUsername(
|
||||
r.Context(), username,
|
||||
)
|
||||
|
||||
if errors.Is(err, storage.ErrUserNotFound) {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
if !VerifyPassword(password, passwordHash) {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
randomBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
writeError(w, r, http.StatusInternalServerError,
|
||||
"internal_error", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||
createdAt := time.Now().UTC().Truncate(time.Microsecond)
|
||||
expiresAt := createdAt.Add(sessionTTL())
|
||||
|
||||
err = h.sessions.CreateSession(
|
||||
r.Context(),
|
||||
token,
|
||||
user.ID,
|
||||
createdAt,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Del("WWW-Authenticate")
|
||||
|
||||
writeJSON(w, http.StatusCreated, sessionResponse{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
|
||||
if !strings.HasPrefix(authorization, "Bearer ") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(authorization, "Bearer ")
|
||||
if token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
err := h.sessions.RevokeSession(r.Context(), token)
|
||||
|
||||
if errors.Is(err, storage.ErrSessionNotFound) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"mtusi2026lab2/internal/middleware"
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
var usernameRegexp = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserHandler struct {
|
||||
store *storage.AuthStore
|
||||
}
|
||||
|
||||
func NewUserHandler(store *storage.AuthStore) *UserHandler {
|
||||
return &UserHandler{store: store}
|
||||
}
|
||||
|
||||
type createUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
1,
|
||||
64*1024,
|
||||
4,
|
||||
32,
|
||||
)
|
||||
|
||||
return "argon2id$" +
|
||||
base64.RawStdEncoding.EncodeToString(salt) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(hash), nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 3 || parts[0] != "argon2id" {
|
||||
return false
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
|
||||
if err != nil || len(salt) != 16 {
|
||||
return false
|
||||
}
|
||||
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[2])
|
||||
if err != nil || len(expected) != 32 {
|
||||
return false
|
||||
}
|
||||
|
||||
actual := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
1,
|
||||
64*1024,
|
||||
4,
|
||||
32,
|
||||
)
|
||||
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var req createUserRequest
|
||||
|
||||
if err := decodeOneObject(r, &req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if !usernameRegexp.MatchString(req.Username) {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
|
||||
req.DisplayName = strings.TrimSpace(req.DisplayName)
|
||||
nameLength := utf8.RuneCountInString(req.DisplayName)
|
||||
|
||||
if nameLength < 1 || nameLength > 100 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid display_name")
|
||||
return
|
||||
}
|
||||
|
||||
passwordLength := utf8.RuneCountInString(req.Password)
|
||||
if passwordLength < 12 || passwordLength > 128 {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request",
|
||||
"password must contain 12 to 128 characters")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := HashPassword(req.Password)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusInternalServerError,
|
||||
"internal_error", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
err = h.store.CreateUser(r.Context(), user, passwordHash)
|
||||
if errors.Is(err, storage.ErrUsernameTaken) {
|
||||
writeError(w, r, http.StatusConflict,
|
||||
"conflict", "username already exists")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := middleware.GetCurrentUser(r.Context())
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
Reference in New Issue
Block a user