forked from mtusi2026/mtusi2026lab2
Перенос минимума из lab1
This commit is contained in:
@@ -0,0 +1,321 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
var uuidRe = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
var limitRe = regexp.MustCompile(`^[0-9]{1,3}$`)
|
||||
var requestIDRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorObject `json:"error"`
|
||||
}
|
||||
|
||||
type errorObject struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type userJSON struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatJSON struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type messageJSON struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatPage struct {
|
||||
Items []chatJSON `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type messagePage struct {
|
||||
Items []messageJSON `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type cursorPayload struct {
|
||||
Scope string `json:"scope"`
|
||||
ID string `json:"id"`
|
||||
At string `json:"at"`
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
wrote bool
|
||||
}
|
||||
|
||||
func (s *statusWriter) WriteHeader(code int) {
|
||||
if s.wrote {
|
||||
return
|
||||
}
|
||||
s.status = code
|
||||
s.wrote = true
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *statusWriter) Write(b []byte) (int, error) {
|
||||
if !s.wrote {
|
||||
s.WriteHeader(http.StatusOK)
|
||||
}
|
||||
return s.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func (a *API) fail(w http.ResponseWriter, r *http.Request, status int, code, message string, retryAfter int) {
|
||||
if retryAfter > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
||||
}
|
||||
writeJSON(w, status, errorEnvelope{Error: errorObject{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestIDFrom(r),
|
||||
}})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(v)
|
||||
}
|
||||
|
||||
func (a *API) readJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
|
||||
media := ""
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" {
|
||||
media = strings.TrimSpace(strings.Split(ct, ";")[0])
|
||||
}
|
||||
if !strings.EqualFold(media, "application/json") {
|
||||
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Нужен Content-Type application/json", 0)
|
||||
return false
|
||||
}
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil || !utf8.Valid(body) || !decodeExactJSON(body, dst) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный JSON", 0)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// decodeExactJSON принимает один JSON-объект: точные имена полей, без хвоста и без замены битого UTF-8.
|
||||
func decodeExactJSON(body []byte, dst any) bool {
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
var fields map[string]json.RawMessage
|
||||
if err := dec.Decode(&fields); err != nil || fields == nil {
|
||||
return false
|
||||
}
|
||||
var trailing json.RawMessage
|
||||
if err := dec.Decode(&trailing); err != io.EOF {
|
||||
return false
|
||||
}
|
||||
allowed, ok := jsonFieldNames(dst)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for name := range fields {
|
||||
if _, ok := allowed[name]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return json.Unmarshal(body, dst) == nil
|
||||
}
|
||||
|
||||
func jsonFieldNames(dst any) (map[string]struct{}, bool) {
|
||||
t := reflect.TypeOf(dst)
|
||||
if t == nil || t.Kind() != reflect.Pointer {
|
||||
return nil, false
|
||||
}
|
||||
t = t.Elem()
|
||||
if t.Kind() != reflect.Struct {
|
||||
return nil, false
|
||||
}
|
||||
names := make(map[string]struct{}, t.NumField())
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
|
||||
if name == "" || name == "-" {
|
||||
return nil, false
|
||||
}
|
||||
names[name] = struct{}{}
|
||||
}
|
||||
return names, true
|
||||
}
|
||||
|
||||
func (a *API) authenticate(w http.ResponseWriter, r *http.Request) (store.User, bool) {
|
||||
raw := strings.TrimSpace(r.Header.Get("X-User-Id"))
|
||||
id, ok := canonicalUUID(raw)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", 0)
|
||||
return store.User{}, false
|
||||
}
|
||||
user, exists := a.store.User(id)
|
||||
if !exists {
|
||||
a.fail(w, r, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", 0)
|
||||
return store.User{}, false
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
func (a *API) pageQuery(w http.ResponseWriter, r *http.Request, scope string) (int, *store.Cursor, bool) {
|
||||
q := r.URL.Query()
|
||||
limit := 50
|
||||
if q.Has("limit") {
|
||||
raw := q.Get("limit")
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || !limitRe.MatchString(raw) || n < 1 || n > 100 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный limit", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
if !q.Has("cursor") {
|
||||
return limit, nil, true
|
||||
}
|
||||
raw := q.Get("cursor")
|
||||
if raw == "" || len(raw) > 512 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
payload, err := decodeCursor(raw)
|
||||
if err != nil || payload.Scope != scope || payload.ID == "" || payload.At == "" {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
at, err := time.Parse("2006-01-02T15:04:05.000000Z", payload.At)
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
id, ok := canonicalUUID(payload.ID)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
return limit, &store.Cursor{ID: id, At: at}, true
|
||||
}
|
||||
|
||||
func asUser(u store.User) userJSON {
|
||||
return userJSON{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: formatTime(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func asChat(c store.Chat) chatJSON {
|
||||
ids := c.MemberIDs
|
||||
if ids == nil {
|
||||
ids = []string{}
|
||||
}
|
||||
return chatJSON{
|
||||
ID: c.ID,
|
||||
Title: c.Title,
|
||||
MemberIDs: ids,
|
||||
CreatedAt: formatTime(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func asMessage(m store.Message) messageJSON {
|
||||
return messageJSON{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.SenderID,
|
||||
Text: m.Text,
|
||||
CreatedAt: formatTime(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func formatTime(t time.Time) string {
|
||||
return t.UTC().Format("2006-01-02T15:04:05.000000Z")
|
||||
}
|
||||
|
||||
func canonicalUUID(s string) (string, bool) {
|
||||
if !uuidRe.MatchString(s) {
|
||||
return "", false
|
||||
}
|
||||
return strings.ToLower(s), true
|
||||
}
|
||||
|
||||
func validText(s string, min, max int) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
incoming := strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
||||
if requestIDRe.MatchString(incoming) {
|
||||
return incoming
|
||||
}
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
func encodeCursor(p cursorPayload) string {
|
||||
raw, err := json.Marshal(p)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func decodeCursor(s string) (cursorPayload, error) {
|
||||
b, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
b, err = base64.URLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return cursorPayload{}, err
|
||||
}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(b))
|
||||
dec.DisallowUnknownFields()
|
||||
var p cursorPayload
|
||||
if err := dec.Decode(&p); err != nil {
|
||||
return cursorPayload{}, err
|
||||
}
|
||||
var trailing json.RawMessage
|
||||
if err := dec.Decode(&trailing); err != io.EOF {
|
||||
if err == nil {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
return cursorPayload{}, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
Reference in New Issue
Block a user