forked from mtusi2026/mtusi2026lab2
Implement lab2 messenger API with PostgreSQL Redis and Docker
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"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
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&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
|
||||
}
|
||||
|
||||
chats, err := h.store.ListChatsForUser(r.Context(), currentUser.ID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chatPage{
|
||||
Items: chats,
|
||||
NextCursor: nil,
|
||||
})
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"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
|
||||
}
|
||||
|
||||
func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, ok := h.accessibleChat(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
currentUser, _ := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
var req createMessageRequest
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest,
|
||||
"invalid_request", "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
textLength := utf8.RuneCountInString(req.Text)
|
||||
if textLength < 1 || 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),
|
||||
}
|
||||
|
||||
err := h.messages.CreateMessage(r.Context(), message)
|
||||
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 := decodeCursor(raw)
|
||||
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 := encodeCursor(items[len(items)-1])
|
||||
nextCursor = &cursor
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, messagePage{
|
||||
Items: items,
|
||||
NextCursor: nextCursor,
|
||||
})
|
||||
}
|
||||
|
||||
func encodeCursor(message model.Message) string {
|
||||
value := fmt.Sprintf(
|
||||
"%s|%s",
|
||||
message.CreatedAt.Format(time.RFC3339Nano),
|
||||
message.ID.String(),
|
||||
)
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(value))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor string) (time.Time, uuid.UUID, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
|
||||
parts := strings.SplitN(string(data), "|", 2)
|
||||
if len(parts) != 2 {
|
||||
return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor")
|
||||
}
|
||||
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
|
||||
id, err := uuid.Parse(parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, uuid.Nil, err
|
||||
}
|
||||
|
||||
return createdAt, id, nil
|
||||
}
|
||||
@@ -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,151 @@
|
||||
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"`,
|
||||
)
|
||||
|
||||
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,160 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"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
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&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)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
const currentUserKey contextKey = "current_user"
|
||||
|
||||
type authErrorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type authErrorResponse struct {
|
||||
Error authErrorBody `json:"error"`
|
||||
}
|
||||
|
||||
func Auth(store *storage.SessionService) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
|
||||
if !strings.HasPrefix(authorization, "Bearer ") {
|
||||
writeAuthError(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(authorization, "Bearer ")
|
||||
if token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
writeAuthError(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := store.GetSessionUser(r.Context(), token)
|
||||
|
||||
if errors.Is(err, storage.ErrSessionNotFound) {
|
||||
writeAuthError(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(authErrorResponse{
|
||||
Error: authErrorBody{
|
||||
Code: "unavailable",
|
||||
Message: "service unavailable",
|
||||
RequestID: GetRequestID(r.Context()),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), currentUserKey, user)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func GetCurrentUser(ctx context.Context) (model.User, bool) {
|
||||
user, ok := ctx.Value(currentUserKey).(model.User)
|
||||
return user, ok
|
||||
}
|
||||
|
||||
func writeAuthError(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(authErrorResponse{
|
||||
Error: authErrorBody{
|
||||
Code: "unauthorized",
|
||||
Message: "authentication required",
|
||||
RequestID: GetRequestID(r.Context()),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const requestIDKey contextKey = "request_id"
|
||||
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := uuid.NewString()
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
ctx := context.WithValue(r.Context(), requestIDKey, requestID)
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
requestID, _ := ctx.Value(requestIDKey).(string)
|
||||
return requestID
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
ChatID uuid.UUID `json:"chat_id"`
|
||||
SenderID uuid.UUID `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"time"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrUsernameTaken = errors.New("username already exists")
|
||||
ErrSessionNotFound = errors.New("session not found")
|
||||
)
|
||||
|
||||
type AuthStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAuthStore(pool *pgxpool.Pool) *AuthStore {
|
||||
return &AuthStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *AuthStore) CreateUser(
|
||||
ctx context.Context,
|
||||
user model.User,
|
||||
passwordHash string,
|
||||
) error {
|
||||
const query = `
|
||||
INSERT INTO users
|
||||
(id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
_, err := s.pool.Exec(ctx, query,
|
||||
user.ID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
passwordHash,
|
||||
user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
return fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (model.User, string, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name,
|
||||
password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
|
||||
var user model.User
|
||||
var passwordHash string
|
||||
|
||||
err := s.pool.QueryRow(ctx, query, username).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&passwordHash,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, "", fmt.Errorf("get user: %w", err)
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) GetUserByID(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
) (model.User, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
var user model.User
|
||||
|
||||
err := s.pool.QueryRow(ctx, query, id).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("get user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func tokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *AuthStore) CreateSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
userID uuid.UUID,
|
||||
createdAt time.Time,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
const query = `
|
||||
INSERT INTO sessions
|
||||
(token_hash, user_id, created_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
`
|
||||
|
||||
_, err := s.pool.Exec(ctx, query,
|
||||
tokenHash(token),
|
||||
userID,
|
||||
createdAt,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) GetSessionUser(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (model.User, error) {
|
||||
const query = `
|
||||
SELECT u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
AND s.expires_at > NOW()
|
||||
`
|
||||
|
||||
var user model.User
|
||||
|
||||
err := s.pool.QueryRow(ctx, query, tokenHash(token)).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrSessionNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("get session: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *AuthStore) RevokeSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
const query = `
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
AND expires_at > NOW()
|
||||
`
|
||||
|
||||
result, err := s.pool.Exec(ctx, query, tokenHash(token))
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke session: %w", err)
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrChatNotFound = errors.New("chat not found")
|
||||
ErrInvalidMember = errors.New("chat member does not exist")
|
||||
)
|
||||
|
||||
type ChatStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatStore(pool *pgxpool.Pool) *ChatStore {
|
||||
return &ChatStore{pool: pool}
|
||||
}
|
||||
|
||||
// CreateChat creates the chat and all its members in one transaction.
|
||||
// A failure inserting any member rolls back the entire chat.
|
||||
func (s *ChatStore) CreateChat(
|
||||
ctx context.Context,
|
||||
chat model.Chat,
|
||||
) error {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin chat transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES ($1, $2, $3)
|
||||
`, chat.ID, chat.Title, chat.CreatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
`, chat.ID, memberID)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
|
||||
return ErrInvalidMember
|
||||
}
|
||||
return fmt.Errorf("insert chat member: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit chat transaction: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetChatForUser returns a chat only if the user is a member.
|
||||
// Missing chats and inaccessible chats both return ErrChatNotFound.
|
||||
func (s *ChatStore) GetChatForUser(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
userID uuid.UUID,
|
||||
) (model.Chat, error) {
|
||||
var chat model.Chat
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1 AND cm.user_id = $2
|
||||
`, chatID, userID).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrChatNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
|
||||
members, err := s.getMemberIDs(ctx, chat.ID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
chat.MemberIDs = members
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) getMemberIDs(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
) ([]uuid.UUID, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
ORDER BY user_id
|
||||
`, chatID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query chat members: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
members := make([]uuid.UUID, 0)
|
||||
|
||||
for rows.Next() {
|
||||
var memberID uuid.UUID
|
||||
if err := rows.Scan(&memberID); err != nil {
|
||||
return nil, fmt.Errorf("scan chat member: %w", err)
|
||||
}
|
||||
members = append(members, memberID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate chat members: %w", err)
|
||||
}
|
||||
|
||||
return members, nil
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListChatsForUser(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
) ([]model.Chat, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
|
||||
chats := make([]model.Chat, 0)
|
||||
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
if err := rows.Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("scan chat: %w", err)
|
||||
}
|
||||
chats = append(chats, chat)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("iterate chats: %w", err)
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
// A connection cannot be reused for another query until rows are closed.
|
||||
for i := range chats {
|
||||
members, err := s.getMemberIDs(ctx, chats[i].ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats[i].MemberIDs = members
|
||||
}
|
||||
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
// ExistsUser is used to validate members before creating a chat.
|
||||
func (s *ChatStore) ExistsUser(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
) (bool, error) {
|
||||
var exists bool
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM users WHERE id = $1)
|
||||
`, userID).Scan(&exists)
|
||||
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check user existence: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// Kept here to document that chat timestamps are stored in UTC.
|
||||
var _ = time.UTC
|
||||
@@ -0,0 +1,126 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
func TestConcurrentRegistrationSameUsername(t *testing.T) {
|
||||
store, _ := newTestAuthStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
username := "race_" + uuid.NewString()[:8]
|
||||
const workers = 10
|
||||
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, workers)
|
||||
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: "Race Test",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
results <- store.CreateUser(ctx, user, "test_password_hash")
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
successes := 0
|
||||
conflicts := 0
|
||||
|
||||
for err := range results {
|
||||
switch {
|
||||
case err == nil:
|
||||
successes++
|
||||
case errors.Is(err, ErrUsernameTaken):
|
||||
conflicts++
|
||||
default:
|
||||
t.Fatalf("unexpected registration error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if successes != 1 || conflicts != workers-1 {
|
||||
t.Fatalf(
|
||||
"expected 1 success and %d conflicts, got %d successes and %d conflicts",
|
||||
workers-1, successes, conflicts,
|
||||
)
|
||||
}
|
||||
|
||||
t.Logf("PASS: %d successful registration, %d conflicts",
|
||||
successes, conflicts)
|
||||
}
|
||||
|
||||
func TestCreateChatRollbackOnInvalidMember(t *testing.T) {
|
||||
authStore, validUserID := newTestAuthStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
chatID := uuid.New()
|
||||
|
||||
chat := model.Chat{
|
||||
ID: chatID,
|
||||
Title: "Rollback Test",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
MemberIDs: []uuid.UUID{
|
||||
validUserID,
|
||||
uuid.New(),
|
||||
},
|
||||
}
|
||||
|
||||
err := NewChatStore(authStore.pool).CreateChat(ctx, chat)
|
||||
|
||||
if !errors.Is(err, ErrInvalidMember) {
|
||||
t.Fatalf("expected ErrInvalidMember, got %v", err)
|
||||
}
|
||||
|
||||
var chatCount int
|
||||
err = authStore.pool.QueryRow(
|
||||
ctx,
|
||||
"SELECT COUNT(*) FROM chats WHERE id = $1",
|
||||
chatID,
|
||||
).Scan(&chatCount)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("check chat existence: %v", err)
|
||||
}
|
||||
|
||||
if chatCount != 0 {
|
||||
t.Fatalf("rollback failed: chat still exists")
|
||||
}
|
||||
|
||||
var memberCount int
|
||||
err = authStore.pool.QueryRow(
|
||||
ctx,
|
||||
"SELECT COUNT(*) FROM chat_members WHERE chat_id = $1",
|
||||
chatID,
|
||||
).Scan(&memberCount)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("check chat members: %v", err)
|
||||
}
|
||||
|
||||
if memberCount != 0 {
|
||||
t.Fatalf("rollback failed: %d chat members still exist", memberCount)
|
||||
}
|
||||
|
||||
t.Log("PASS: transaction rolled back chat and member inserts")
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
users map[uuid.UUID]model.User
|
||||
chats map[uuid.UUID]model.Chat
|
||||
messages map[uuid.UUID][]model.Message
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
users: make(map[uuid.UUID]model.User),
|
||||
chats: make(map[uuid.UUID]model.Chat),
|
||||
messages: make(map[uuid.UUID][]model.Message),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateUser(user model.User) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, existingUser := range s.users {
|
||||
if existingUser.Username == user.Username {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
s.users[user.ID] = user
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetUserByID(id uuid.UUID) (model.User, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
user, ok := s.users[id]
|
||||
return user, ok
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateChat(chat model.Chat) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.chats[chat.ID] = chat
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatByID(id uuid.UUID) (model.Chat, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, ok := s.chats[id]
|
||||
return chat, ok
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListChatsForUser(userID uuid.UUID) []model.Chat {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chats := make([]model.Chat, 0)
|
||||
|
||||
for _, chat := range s.chats {
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == userID {
|
||||
chats = append(chats, chat)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return chats
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateMessage(message model.Message) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.messages[message.ChatID] = append(
|
||||
s.messages[message.ChatID],
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListMessages(chatID uuid.UUID) []model.Message {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
messages := s.messages[chatID]
|
||||
|
||||
result := make([]model.Message, len(messages))
|
||||
copy(result, messages)
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
var ErrMessageMemberNotFound = errors.New("sender is not a chat member")
|
||||
|
||||
type MessageStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageStore(pool *pgxpool.Pool) *MessageStore {
|
||||
return &MessageStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *MessageStore) CreateMessage(
|
||||
ctx context.Context,
|
||||
message model.Message,
|
||||
) error {
|
||||
const query = `
|
||||
INSERT INTO messages (
|
||||
id, chat_id, sender_id, text, created_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
_, err := s.pool.Exec(ctx, query,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
message.SenderID,
|
||||
message.Text,
|
||||
message.CreatedAt,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
|
||||
return ErrMessageMemberNotFound
|
||||
}
|
||||
return fmt.Errorf("create message: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListMessages implements keyset pagination.
|
||||
// Cursor is the created_at + id of the previous page's last item.
|
||||
func (s *MessageStore) ListMessages(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
limit int,
|
||||
cursorTime *time.Time,
|
||||
cursorID *uuid.UUID,
|
||||
) ([]model.Message, bool, error) {
|
||||
var rows pgx.Rows
|
||||
var err error
|
||||
|
||||
if cursorTime == nil || cursorID == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2
|
||||
`, chatID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
`, chatID, *cursorTime, *cursorID, limit+1)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
messages := make([]model.Message, 0, limit+1)
|
||||
|
||||
for rows.Next() {
|
||||
var message model.Message
|
||||
|
||||
if err := rows.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, false, fmt.Errorf("scan message: %w", err)
|
||||
}
|
||||
|
||||
messages = append(messages, message)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, fmt.Errorf("iterate messages: %w", err)
|
||||
}
|
||||
|
||||
hasMore := len(messages) > limit
|
||||
if hasMore {
|
||||
messages = messages[:limit]
|
||||
}
|
||||
|
||||
return messages, hasMore, nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026lab2/migrations"
|
||||
)
|
||||
|
||||
func ApplyMigrations(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin migrations: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// Serialize migrations across API instances.
|
||||
_, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(20260002)`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lock migrations: %w", err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version BIGINT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create migration history: %w", err)
|
||||
}
|
||||
|
||||
entries, err := fs.ReadDir(migrations.Files, ".")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migrations: %w", err)
|
||||
}
|
||||
|
||||
names := make([]string, 0)
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".up.sql") {
|
||||
names = append(names, entry.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
for _, name := range names {
|
||||
versionPart := strings.SplitN(name, "_", 2)[0]
|
||||
|
||||
version, err := strconv.ParseInt(versionPart, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid migration filename %q: %w", name, err)
|
||||
}
|
||||
|
||||
var applied bool
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM schema_migrations
|
||||
WHERE version = $1
|
||||
)
|
||||
`, version).Scan(&applied)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check migration %d: %w", version, err)
|
||||
}
|
||||
|
||||
if applied {
|
||||
continue
|
||||
}
|
||||
|
||||
sql, err := fs.ReadFile(migrations.Files, name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migration %s: %w", name, err)
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, string(sql)); err != nil {
|
||||
return fmt.Errorf("apply migration %s: %w", name, err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO schema_migrations (version)
|
||||
VALUES ($1)
|
||||
`, version)
|
||||
if err != nil {
|
||||
return fmt.Errorf("record migration %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit migrations: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func NewPostgresPool(
|
||||
ctx context.Context,
|
||||
databaseURL string,
|
||||
) (*pgxpool.Pool, error) {
|
||||
config, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"invalid database config: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
config.MaxConns = 10
|
||||
config.MinConns = 1
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
config.HealthCheckPeriod = time.Minute
|
||||
config.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
|
||||
connectCtx, cancel := context.WithTimeout(
|
||||
ctx,
|
||||
10*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(
|
||||
connectCtx,
|
||||
config,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"create postgres pool: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if err := pool.Ping(connectCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf(
|
||||
"postgres unavailable: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type SessionCache struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionCache(redisURL string) (*SessionCache, error) {
|
||||
options, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid redis URL: %w", err)
|
||||
}
|
||||
|
||||
options.DialTimeout = 2 * time.Second
|
||||
options.ReadTimeout = 2 * time.Second
|
||||
options.WriteTimeout = 2 * time.Second
|
||||
options.MaxRetries = 0
|
||||
|
||||
return &SessionCache{
|
||||
client: redis.NewClient(options),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) Close() error {
|
||||
return c.client.Close()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Ping(ctx context.Context) error {
|
||||
return c.client.Ping(ctx).Err()
|
||||
}
|
||||
|
||||
func cacheKey(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "session:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (c *SessionCache) Set(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
userID uuid.UUID,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
ttl := time.Until(expiresAt)
|
||||
if ttl <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return c.client.Set(
|
||||
ctx,
|
||||
cacheKey(token),
|
||||
userID.String(),
|
||||
ttl,
|
||||
).Err()
|
||||
}
|
||||
|
||||
func (c *SessionCache) Get(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (uuid.UUID, bool, error) {
|
||||
value, err := c.client.Get(ctx, cacheKey(token)).Result()
|
||||
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return uuid.Nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, false, err
|
||||
}
|
||||
|
||||
userID, err := uuid.Parse(value)
|
||||
if err != nil {
|
||||
return uuid.Nil, false, err
|
||||
}
|
||||
|
||||
return userID, true, nil
|
||||
}
|
||||
|
||||
func (c *SessionCache) Delete(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
return c.client.Del(ctx, cacheKey(token)).Err()
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type SessionService struct {
|
||||
db *AuthStore
|
||||
cache *SessionCache
|
||||
}
|
||||
|
||||
func NewSessionService(
|
||||
db *AuthStore,
|
||||
cache *SessionCache,
|
||||
) *SessionService {
|
||||
return &SessionService{
|
||||
db: db,
|
||||
cache: cache,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionService) CreateSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
userID uuid.UUID,
|
||||
createdAt time.Time,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
if err := s.db.CreateSession(
|
||||
ctx, token, userID, createdAt, expiresAt,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(
|
||||
context.Background(), 2*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
_ = s.cache.Set(cacheCtx, token, userID, expiresAt)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SessionService) GetSessionUser(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (model.User, error) {
|
||||
// PostgreSQL remains the source of truth.
|
||||
user, err := s.db.GetSessionUser(ctx, token)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
|
||||
// Redis is best-effort and cannot extend a session.
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(
|
||||
context.Background(), 2*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
_, _, _ = s.cache.Get(cacheCtx, token)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *SessionService) RevokeSession(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
if err := s.db.RevokeSession(ctx, token); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(
|
||||
context.Background(), 2*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
_ = s.cache.Delete(cacheCtx, token)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
func newTestAuthStore(t *testing.T) (*AuthStore, uuid.UUID) {
|
||||
t.Helper()
|
||||
|
||||
databaseURL := os.Getenv("TEST_DATABASE_URL")
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set; integration test skipped")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
pool, err := NewPostgresPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatalf("connect to PostgreSQL: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
|
||||
store := NewAuthStore(pool)
|
||||
|
||||
userID := uuid.New()
|
||||
username := "test_" + uuid.NewString()[:8]
|
||||
|
||||
user := model.User{
|
||||
ID: userID,
|
||||
Username: username,
|
||||
DisplayName: "Integration Test",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
err = store.CreateUser(ctx, user, "test-password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("create test user: %v", err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, _ = pool.Exec(cleanupCtx,
|
||||
"DELETE FROM sessions WHERE user_id = $1", userID)
|
||||
_, _ = pool.Exec(cleanupCtx,
|
||||
"DELETE FROM users WHERE id = $1", userID)
|
||||
})
|
||||
|
||||
return store, userID
|
||||
}
|
||||
|
||||
func TestSessionCreateAndGet(t *testing.T) {
|
||||
store, userID := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
token := "test-token-" + uuid.NewString()
|
||||
|
||||
err := service.CreateSession(
|
||||
ctx, token, userID, now, now.Add(time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
user, err := service.GetSessionUser(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatalf("get session user: %v", err)
|
||||
}
|
||||
|
||||
if user.ID != userID {
|
||||
t.Fatalf("expected user %s, got %s", userID, user.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpiredSessionRejected(t *testing.T) {
|
||||
store, userID := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
token := "expired-token-" + uuid.NewString()
|
||||
|
||||
err := service.CreateSession(
|
||||
ctx,
|
||||
token,
|
||||
userID,
|
||||
now.Add(-2*time.Hour),
|
||||
now.Add(-time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create expired session: %v", err)
|
||||
}
|
||||
|
||||
_, err = service.GetSessionUser(ctx, token)
|
||||
|
||||
if !errors.Is(err, ErrSessionNotFound) {
|
||||
t.Fatalf("expected ErrSessionNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutRevokesSession(t *testing.T) {
|
||||
store, userID := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
token := "logout-token-" + uuid.NewString()
|
||||
|
||||
err := service.CreateSession(
|
||||
ctx, token, userID, now, now.Add(time.Hour),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
|
||||
err = service.RevokeSession(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatalf("revoke session: %v", err)
|
||||
}
|
||||
|
||||
_, err = service.GetSessionUser(ctx, token)
|
||||
|
||||
if !errors.Is(err, ErrSessionNotFound) {
|
||||
t.Fatalf("expected revoked token to be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownTokenRejected(t *testing.T) {
|
||||
store, _ := newTestAuthStore(t)
|
||||
service := NewSessionService(store, nil)
|
||||
|
||||
token := fmt.Sprintf("unknown-%s", uuid.NewString())
|
||||
|
||||
_, err := service.GetSessionUser(context.Background(), token)
|
||||
|
||||
if !errors.Is(err, ErrSessionNotFound) {
|
||||
t.Fatalf("expected ErrSessionNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user