forked from mtusi2026/mtusi2026lab3
feat(app) lab 3 implemented
This commit is contained in:
@@ -9,15 +9,6 @@ import (
|
||||
"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")
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// Package common contains cross-cutting HTTP helpers: contract errors, JSON
|
||||
// binding, validation, cursor pagination and timestamp formatting.
|
||||
package common
|
||||
|
||||
import (
|
||||
@@ -87,8 +89,8 @@ func Unavailable(message string) *AppError {
|
||||
|
||||
// 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
|
||||
appErr, ok := errors.AsType[*AppError](err)
|
||||
return ok && appErr.Code == code
|
||||
}
|
||||
|
||||
func ErrorCodeFromStatus(status int) string {
|
||||
@@ -126,8 +128,7 @@ func SendError(c fiber.Ctx, status int, code, message string) error {
|
||||
}
|
||||
|
||||
func SendAppError(c fiber.Ctx, err error) error {
|
||||
var appErr *AppError
|
||||
if errors.As(err, &appErr) {
|
||||
if appErr, ok := errors.AsType[*AppError](err); ok {
|
||||
return SendError(c, appErr.Status, appErr.Code, appErr.Message)
|
||||
}
|
||||
|
||||
@@ -135,8 +136,6 @@ func SendAppError(c fiber.Ctx, err error) error {
|
||||
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,30 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateIdempotencyKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
key string
|
||||
ok bool
|
||||
}{
|
||||
{name: "hex", key: "4f8c2d1e", ok: true},
|
||||
{name: "allowed punctuation", key: "load-1_a.b:c", ok: true},
|
||||
{name: "empty", key: "", ok: false},
|
||||
{name: "space", key: "two words", ok: false},
|
||||
{name: "slash", key: "a/b", ok: false},
|
||||
{name: "too long", key: strings.Repeat("a", 129), ok: false},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got := ValidateIdempotencyKey(test.key) == ""
|
||||
if got != test.ok {
|
||||
t.Fatalf("ValidateIdempotencyKey(%q) valid = %v, want %v", test.key, got, test.ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -6,21 +6,15 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// KeyUserID is the request-scoped key set by the Bearer middleware.
|
||||
KeyUserID = "userID"
|
||||
// KeySessionToken is the raw token of the current request.
|
||||
KeyUserID = "userID"
|
||||
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 {
|
||||
@@ -29,7 +23,6 @@ func MustUserID(c fiber.Ctx) uuid.UUID {
|
||||
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 != ""
|
||||
|
||||
@@ -10,9 +10,6 @@ import (
|
||||
"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
|
||||
@@ -88,9 +85,6 @@ func DecodeCursor(cursor string) (*CursorKeyCtx, bool) {
|
||||
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
|
||||
|
||||
@@ -29,21 +29,3 @@ func TestCursorRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,21 @@
|
||||
package common
|
||||
|
||||
import "testing"
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,19 +5,15 @@ import (
|
||||
"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.
|
||||
// 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).
|
||||
// RFC 3339 permits an optional fractional second.
|
||||
utc := time.Time(t).UTC().Truncate(storageTimePrecision)
|
||||
layout := "2006-01-02T15:04:05Z"
|
||||
if utc.Nanosecond() != 0 {
|
||||
@@ -27,10 +23,5 @@ func (t RFCFormTime) MarshalJSON() ([]byte, error) {
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
var (
|
||||
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
idempotencyKeyRegex = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
)
|
||||
|
||||
func blank(s string) bool {
|
||||
return strings.TrimSpace(s) == ""
|
||||
@@ -71,6 +74,16 @@ func ValidateMessageText(text string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidateIdempotencyKey(key string) string {
|
||||
if key == "" {
|
||||
return "Idempotency-Key header is required"
|
||||
}
|
||||
if !idempotencyKeyRegex.MatchString(key) {
|
||||
return "Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$"
|
||||
}
|
||||
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"
|
||||
|
||||
Reference in New Issue
Block a user