forked from mtusi2026/mtusi2026lab3
chore(app) transferred codebase from Lab2
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
// AGENT: Field-level validation is deliberately not delegated to a generic
|
||||
// struct validator. The contract needs specific messages for blank strings,
|
||||
// Unicode length and duplicate member IDs, so handlers call the Validators in
|
||||
// validation.go after this strict JSON decoding step.
|
||||
//
|
||||
// BindJSON enforces the request format from the contract: JSON content type,
|
||||
// exactly one JSON value, no unknown fields and correct Go types. Field-level
|
||||
// rules (non-blank strings, lengths, UUID lists) stay in the handlers so their
|
||||
// messages can be specific.
|
||||
func BindJSON(c fiber.Ctx, dst any) error {
|
||||
if contentType := c.Get(fiber.HeaderContentType); !strings.HasPrefix(contentType, "application/json") {
|
||||
return UnsupportedMedia("invalid JSON body")
|
||||
}
|
||||
|
||||
body := c.Body()
|
||||
if len(body) == 0 {
|
||||
return BadRequest("request body is empty")
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(dst); err != nil {
|
||||
return BadRequest("invalid JSON body")
|
||||
}
|
||||
|
||||
var extra json.RawMessage
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
return BadRequest("request body has extra trailing bytes")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
)
|
||||
|
||||
const (
|
||||
ErrorCodeInvalidRequest = "invalid_request"
|
||||
ErrorCodeUnauthorized = "unauthorized"
|
||||
ErrorCodeNotFound = "not_found"
|
||||
ErrorCodeConflict = "conflict"
|
||||
ErrorCodePayloadTooLarge = "payload_too_large"
|
||||
ErrorCodeUnsupportedMedia = "unsupported_media_type"
|
||||
ErrorCodeRateLimited = "rate_limited"
|
||||
ErrorCodeUnavailable = "unavailable"
|
||||
ErrorCodeInternal = "internal_error"
|
||||
)
|
||||
|
||||
type APIErrorResponse struct {
|
||||
Error APIError `json:"error"`
|
||||
}
|
||||
|
||||
type APIError struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func NewError(code, message, requestID string) APIErrorResponse {
|
||||
return APIErrorResponse{
|
||||
Error: APIError{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type AppError struct {
|
||||
Status int
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func NewAppError(status int, code, message string) *AppError {
|
||||
return &AppError{
|
||||
Status: status,
|
||||
Code: code,
|
||||
Message: message,
|
||||
}
|
||||
}
|
||||
|
||||
func BadRequest(message string) *AppError {
|
||||
return NewAppError(fiber.StatusBadRequest, ErrorCodeInvalidRequest, message)
|
||||
}
|
||||
|
||||
func Unauthorized(message string) *AppError {
|
||||
return NewAppError(fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
|
||||
}
|
||||
|
||||
func NotFound(message string) *AppError {
|
||||
return NewAppError(fiber.StatusNotFound, ErrorCodeNotFound, message)
|
||||
}
|
||||
|
||||
func Conflict(message string) *AppError {
|
||||
return NewAppError(fiber.StatusConflict, ErrorCodeConflict, message)
|
||||
}
|
||||
|
||||
func UnsupportedMedia(message string) *AppError {
|
||||
return NewAppError(fiber.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
|
||||
}
|
||||
|
||||
func Internal() *AppError {
|
||||
return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
|
||||
func Unavailable(message string) *AppError {
|
||||
return NewAppError(fiber.StatusServiceUnavailable, ErrorCodeUnavailable, message)
|
||||
}
|
||||
|
||||
// IsCode reports whether err is an AppError with the given contract code.
|
||||
func IsCode(err error, code string) bool {
|
||||
var appErr *AppError
|
||||
return errors.As(err, &appErr) && appErr.Code == code
|
||||
}
|
||||
|
||||
func ErrorCodeFromStatus(status int) string {
|
||||
switch status {
|
||||
case fiber.StatusBadRequest:
|
||||
return ErrorCodeInvalidRequest
|
||||
case fiber.StatusUnauthorized:
|
||||
return ErrorCodeUnauthorized
|
||||
case fiber.StatusNotFound:
|
||||
return ErrorCodeNotFound
|
||||
case fiber.StatusConflict:
|
||||
return ErrorCodeConflict
|
||||
case fiber.StatusRequestEntityTooLarge:
|
||||
return ErrorCodePayloadTooLarge
|
||||
case fiber.StatusUnsupportedMediaType:
|
||||
return ErrorCodeUnsupportedMedia
|
||||
case fiber.StatusTooManyRequests:
|
||||
return ErrorCodeRateLimited
|
||||
case fiber.StatusServiceUnavailable:
|
||||
return ErrorCodeUnavailable
|
||||
default:
|
||||
return ErrorCodeInternal
|
||||
}
|
||||
}
|
||||
|
||||
func getRequestID(c fiber.Ctx) string {
|
||||
if id := string(c.Response().Header.Peek("X-Request-Id")); id != "" {
|
||||
return id
|
||||
}
|
||||
return requestid.FromContext(c)
|
||||
}
|
||||
|
||||
func SendError(c fiber.Ctx, status int, code, message string) error {
|
||||
return c.Status(status).JSON(NewError(code, message, getRequestID(c)))
|
||||
}
|
||||
|
||||
func SendAppError(c fiber.Ctx, err error) error {
|
||||
var appErr *AppError
|
||||
if errors.As(err, &appErr) {
|
||||
return SendError(c, appErr.Status, appErr.Code, appErr.Message)
|
||||
}
|
||||
|
||||
return SendError(c, fiber.StatusInternalServerError,
|
||||
ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
|
||||
// SendChallenge emits a 401 with the WWW-Authenticate value required by the
|
||||
// contract: Basic for login, Bearer for every protected endpoint.
|
||||
func SendChallenge(c fiber.Ctx, challenge, message string) error {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, challenge)
|
||||
return SendError(c, fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
// KeyUserID is the request-scoped key set by the Bearer middleware.
|
||||
KeyUserID = "userID"
|
||||
// KeySessionToken is the raw token of the current request.
|
||||
KeySessionToken = "sessionToken"
|
||||
)
|
||||
|
||||
// UserID returns the authenticated user ID and whether the middleware set it.
|
||||
func UserID(c fiber.Ctx) (uuid.UUID, bool) {
|
||||
userID, ok := c.Locals(KeyUserID).(uuid.UUID)
|
||||
return userID, ok
|
||||
}
|
||||
|
||||
// MustUserID is for handlers mounted behind BearerAuth, where the middleware
|
||||
// guarantees the local. A missing value is a programming error, not a client
|
||||
// error, so it becomes a recovered 500 instead of an anonymous request.
|
||||
func MustUserID(c fiber.Ctx) uuid.UUID {
|
||||
userID, ok := UserID(c)
|
||||
if !ok {
|
||||
panic("common: authenticated user ID is missing from the request context")
|
||||
}
|
||||
return userID
|
||||
}
|
||||
|
||||
// SessionToken returns the raw bearer token of the current request.
|
||||
func SessionToken(c fiber.Ctx) (string, bool) {
|
||||
token, ok := c.Locals(KeySessionToken).(string)
|
||||
return token, ok && token != ""
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// CursorKeyCtx is the opaque keyset position: (created_at, id) plus the
|
||||
// resource/user the cursor belongs to. ContextID stops a cursor from one chat
|
||||
// or user list being replayed against another.
|
||||
type CursorKeyCtx struct {
|
||||
Time time.Time
|
||||
ID uuid.UUID
|
||||
ContextID uuid.UUID
|
||||
}
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func ParseLimit(c fiber.Ctx, defaultLimit int) (int, error) {
|
||||
limitStr, exists := c.Queries()["limit"]
|
||||
if !exists {
|
||||
return defaultLimit, nil
|
||||
}
|
||||
if strings.TrimSpace(limitStr) == "" {
|
||||
return 0, BadRequest("limit param declared but empty")
|
||||
}
|
||||
|
||||
limit, err := strconv.Atoi(limitStr)
|
||||
if err != nil || limit < 1 || limit > 100 {
|
||||
return 0, BadRequest("limit must be an integer between 1 and 100")
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
func ParseCursor(c fiber.Ctx) (*CursorKeyCtx, error) {
|
||||
cursorStr, exists := c.Queries()["cursor"]
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
if strings.TrimSpace(cursorStr) == "" {
|
||||
return nil, BadRequest("cursor param declared but empty")
|
||||
}
|
||||
|
||||
cursor, ok := DecodeCursor(cursorStr)
|
||||
if !ok {
|
||||
return nil, BadRequest("invalid cursor format")
|
||||
}
|
||||
return cursor, nil
|
||||
}
|
||||
|
||||
func EncodeCursor(key CursorKeyCtx) string {
|
||||
raw := key.Time.UTC().Format(time.RFC3339Nano) + "|" + key.ID.String() + "|" + key.ContextID.String()
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func DecodeCursor(cursor string) (*CursorKeyCtx, bool) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parsedTime, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
parsedID, err := uuid.Parse(parts[1])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
parsedContext, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &CursorKeyCtx{Time: parsedTime, ID: parsedID, ContextID: parsedContext}, true
|
||||
}
|
||||
|
||||
// NextCursor returns a cursor pointing at the last item of a page when more
|
||||
// rows exist. limit+1 rows are fetched by the store, so a non-nil cursor means
|
||||
// the next page is known to be non-empty at read time.
|
||||
func NextCursor[T interface {
|
||||
GetID() uuid.UUID
|
||||
GetCreatedAt() time.Time
|
||||
}](items []T, hasMore bool, contextID uuid.UUID) *string {
|
||||
if !hasMore || len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
last := items[len(items)-1]
|
||||
encoded := EncodeCursor(CursorKeyCtx{
|
||||
Time: last.GetCreatedAt(),
|
||||
ID: last.GetID(),
|
||||
ContextID: contextID,
|
||||
})
|
||||
return &encoded
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCursorRoundTrip(t *testing.T) {
|
||||
want := CursorKeyCtx{
|
||||
Time: time.Date(2026, 10, 20, 12, 30, 45, 123456789, time.UTC),
|
||||
ID: uuid.MustParse("11111111-1111-4111-8111-111111111111"),
|
||||
ContextID: uuid.MustParse("22222222-2222-4222-8222-222222222222"),
|
||||
}
|
||||
|
||||
encoded := EncodeCursor(want)
|
||||
got, ok := DecodeCursor(encoded)
|
||||
if !ok {
|
||||
t.Fatal("cursor did not decode")
|
||||
}
|
||||
if !got.Time.Equal(want.Time) || got.ID != want.ID || got.ContextID != want.ContextID {
|
||||
t.Fatalf("cursor round trip changed the key: %+v", got)
|
||||
}
|
||||
|
||||
for _, invalid := range []string{"not-base64!", "", "aGVsbG8"} {
|
||||
if _, ok := DecodeCursor(invalid); ok {
|
||||
t.Fatalf("invalid cursor %q was accepted", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePasswordRange(t *testing.T) {
|
||||
cases := []struct {
|
||||
password string
|
||||
valid bool
|
||||
}{
|
||||
{"short", false},
|
||||
{"12345678901", false},
|
||||
{"123456789012", true},
|
||||
{"пароль-из-двенадцати", true},
|
||||
{"😀", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := ValidatePassword(tc.password) == ""; got != tc.valid {
|
||||
t.Fatalf("ValidatePassword(%q) valid=%v, want %v", tc.password, got, tc.valid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// storageTimePrecision is the maximum precision shared by PostgreSQL
|
||||
// timestamptz columns and the JSON representation. PostgreSQL stores
|
||||
// microseconds, so keeping the same boundary in Go prevents a create response
|
||||
// from showing more precision than a later read can reproduce.
|
||||
const storageTimePrecision = time.Microsecond
|
||||
|
||||
type RFCFormTime time.Time
|
||||
|
||||
func (t RFCFormTime) MarshalJSON() ([]byte, error) {
|
||||
// RFC 3339 permits an optional fractional second. Use all six digits that
|
||||
// PostgreSQL can store, and omit the fraction only for an exact second.
|
||||
// A fixed six-digit fraction is also accepted by strict consumers that only
|
||||
// understand 3- or 6-digit fractions (for example Python 3.9's parser).
|
||||
utc := time.Time(t).UTC().Truncate(storageTimePrecision)
|
||||
layout := "2006-01-02T15:04:05Z"
|
||||
if utc.Nanosecond() != 0 {
|
||||
layout = "2006-01-02T15:04:05.000000Z"
|
||||
}
|
||||
return json.Marshal(utc.Format(layout))
|
||||
}
|
||||
|
||||
func NowUTC() RFCFormTime {
|
||||
// AGENT: The API used to truncate timestamps to whole seconds to keep
|
||||
// keyset ordering consistent with JSON. RFC 3339 supports fractional seconds
|
||||
// and PostgreSQL has microsecond precision, so use that precision end to end:
|
||||
// timestamps remain ordered after serialization without discarding sub-second
|
||||
// information.
|
||||
return RFCFormTime(time.Now().UTC().Truncate(storageTimePrecision))
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNowUTCHasMicrosecondPrecision(t *testing.T) {
|
||||
now := time.Time(NowUTC())
|
||||
if now.Nanosecond()%1000 != 0 {
|
||||
t.Fatalf("NowUTC() kept precision below a microsecond: %v", now)
|
||||
}
|
||||
if now.Location() != time.UTC {
|
||||
t.Fatalf("NowUTC() location = %v, want UTC", now.Location())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRFCFormTimeSerializesFractionalSeconds(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
value time.Time
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "microseconds",
|
||||
value: time.Date(2026, 10, 26, 12, 34, 56, 123456789, time.UTC),
|
||||
want: `"2026-10-26T12:34:56.123456Z"`,
|
||||
},
|
||||
{
|
||||
name: "exact second",
|
||||
value: time.Date(2026, 10, 26, 12, 34, 56, 0, time.UTC),
|
||||
want: `"2026-10-26T12:34:56Z"`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
encoded, err := json.Marshal(RFCFormTime(tc.value))
|
||||
if err != nil {
|
||||
t.Fatalf("marshal RFC form time: %v", err)
|
||||
}
|
||||
if string(encoded) != tc.want {
|
||||
t.Fatalf("RFC form time = %s, want %s", encoded, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func blank(s string) bool {
|
||||
return strings.TrimSpace(s) == ""
|
||||
}
|
||||
|
||||
func strLenBetween(s string, min, max int) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func ValidateCreateUser(username, displayName string) string {
|
||||
if !usernameRegex.MatchString(username) {
|
||||
return "username must match ^[a-z0-9_]{3,32}$"
|
||||
}
|
||||
|
||||
if blank(displayName) {
|
||||
return "display_name must not be empty or only whitespace"
|
||||
}
|
||||
|
||||
if !strLenBetween(displayName, 1, 100) {
|
||||
return "display_name must be between 1 and 100 Unicode code points"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidatePassword(password string) string {
|
||||
if blank(password) {
|
||||
return "password must not be empty or only whitespace"
|
||||
}
|
||||
|
||||
if !strLenBetween(password, 12, 128) {
|
||||
return "password must be between 12 and 128 Unicode code points"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidateChatTitle(title string) string {
|
||||
if blank(title) {
|
||||
return "title must not be empty or only whitespace"
|
||||
}
|
||||
|
||||
if !strLenBetween(title, 1, 100) {
|
||||
return "title must be between 1 and 100 Unicode code points"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidateMessageText(text string) string {
|
||||
if blank(text) {
|
||||
return "text must not be empty or only whitespace"
|
||||
}
|
||||
|
||||
if !strLenBetween(text, 1, 4000) {
|
||||
return "text must be between 1 and 4000 Unicode code points"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
|
||||
if len(ids) < 1 || len(ids) > 100 {
|
||||
return "member_ids must contain between 1 and 100 members"
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]bool, len(ids))
|
||||
callerFound := false
|
||||
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
return "member_ids must not contain duplicates"
|
||||
}
|
||||
|
||||
seen[id] = true
|
||||
|
||||
if id == callerID {
|
||||
callerFound = true
|
||||
}
|
||||
}
|
||||
|
||||
if !callerFound {
|
||||
return "caller must be included in member_ids"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
Reference in New Issue
Block a user