forked from mtusi2026/mtusi2026lab2
2 lab
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
package authpw
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
memoryKiB = 19 * 1024
|
||||
timeCost = 1
|
||||
threads = 1
|
||||
keyLen = 32
|
||||
saltLen = 16
|
||||
)
|
||||
|
||||
func Hash(password string) (string, error) {
|
||||
salt := make([]byte, saltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := argon2.IDKey([]byte(password), salt, timeCost, memoryKiB, threads, keyLen)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, memoryKiB, timeCost, threads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(sum),
|
||||
), nil
|
||||
}
|
||||
|
||||
func Verify(password, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return false
|
||||
}
|
||||
memory, time, parallelism, ok := parseParams(parts[3])
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(want) == 0 {
|
||||
return false
|
||||
}
|
||||
sum := argon2.IDKey([]byte(password), salt, time, memory, parallelism, uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(sum, want) == 1
|
||||
}
|
||||
|
||||
func parseParams(raw string) (uint32, uint32, uint8, bool) {
|
||||
var memory, time uint32
|
||||
var parallelism uint8
|
||||
for _, item := range strings.Split(raw, ",") {
|
||||
key, value, ok := strings.Cut(item, "=")
|
||||
if !ok {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
switch key {
|
||||
case "m":
|
||||
n, err := strconv.ParseUint(value, 10, 32)
|
||||
if err != nil || n == 0 || n > 1024*1024 {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
memory = uint32(n)
|
||||
case "t":
|
||||
n, err := strconv.ParseUint(value, 10, 32)
|
||||
if err != nil || n == 0 || n > 10 {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
time = uint32(n)
|
||||
case "p":
|
||||
n, err := strconv.ParseUint(value, 10, 8)
|
||||
if err != nil || n == 0 || n > 4 {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
parallelism = uint8(n)
|
||||
default:
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
}
|
||||
if memory == 0 || time == 0 || parallelism == 0 {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
return memory, time, parallelism, true
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package authpw
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestHashVerifiesOnlyTheSamePassword(t *testing.T) {
|
||||
encoded, err := Hash("correct-horse-battery")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !Verify("correct-horse-battery", encoded) {
|
||||
t.Fatal("same password rejected")
|
||||
}
|
||||
if Verify("correct-horse-batteries", encoded) {
|
||||
t.Fatal("other password accepted")
|
||||
}
|
||||
if Verify("correct-horse-battery", "sha256:nope") {
|
||||
t.Fatal("foreign encoding accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi.local/messenger/internal/authpw"
|
||||
"mtusi.local/messenger/internal/model"
|
||||
)
|
||||
|
||||
func (a *API) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := readJSON(w, r, &body); err != nil {
|
||||
a.writeReadError(w, r, err)
|
||||
return
|
||||
}
|
||||
if !model.ValidUsername(body.Username) || !model.ValidLabel(body.DisplayName, 100) || !model.ValidPassword(body.Password) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Недопустимое имя или отображаемое имя", requestID(r))
|
||||
return
|
||||
}
|
||||
hash, err := authpw.Hash(body.Password)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", requestID(r))
|
||||
return
|
||||
}
|
||||
user, err := a.db.CreateUser(r.Context(), body.Username, body.DisplayName, hash)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err, "Недопустимое имя или отображаемое имя")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, userToJSON(user))
|
||||
}
|
||||
|
||||
func (a *API) createSession(w http.ResponseWriter, r *http.Request) {
|
||||
if !bodyEmpty(r) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный JSON", requestID(r))
|
||||
return
|
||||
}
|
||||
username, password, ok := basicCredentials(r)
|
||||
if !ok {
|
||||
writeUnauthorized(w, r, true)
|
||||
return
|
||||
}
|
||||
user, hash, err := a.db.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, model.ErrUnavailable) {
|
||||
writeStoreError(w, r, err, "")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
user = model.User{}
|
||||
hash = ""
|
||||
}
|
||||
if !model.ValidPassword(password) || !a.checkPassword(password, hash) || user.ID == "" {
|
||||
writeUnauthorized(w, r, true)
|
||||
return
|
||||
}
|
||||
token, expires, err := a.session.Create(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err, "")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, sessionJSON{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: apiTime(expires),
|
||||
User: userToJSON(user),
|
||||
})
|
||||
}
|
||||
|
||||
func (a *API) revokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := bearerToken(r)
|
||||
if !ok {
|
||||
writeUnauthorized(w, r, false)
|
||||
return
|
||||
}
|
||||
if _, err := a.session.Lookup(r.Context(), token); err != nil {
|
||||
if errors.Is(err, model.ErrUnavailable) {
|
||||
writeStoreError(w, r, err, "")
|
||||
return
|
||||
}
|
||||
writeUnauthorized(w, r, false)
|
||||
return
|
||||
}
|
||||
if err := a.session.Revoke(r.Context(), token); err != nil {
|
||||
writeStoreError(w, r, err, "")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (a *API) currentUser(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, userToJSON(user))
|
||||
}
|
||||
|
||||
func (a *API) createChat(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := readJSON(w, r, &body); err != nil {
|
||||
a.writeReadError(w, r, err)
|
||||
return
|
||||
}
|
||||
chat, err := a.db.CreateChat(r.Context(), user.ID, body.Title, body.MemberIDs)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err, "Неверный список участников или название чата")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, chatToJSON(chat))
|
||||
}
|
||||
|
||||
func (a *API) listChats(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, cursor, ok := a.pageQuery(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if cursor != nil && cursor.Resource != model.ResourceChats {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный cursor или limit", requestID(r))
|
||||
return
|
||||
}
|
||||
items, next, err := a.db.ListChats(r.Context(), user.ID, limit, cursor)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err, "Неверный cursor или limit")
|
||||
return
|
||||
}
|
||||
page := chatPageJSON{Items: make([]chatJSON, 0, len(items)), NextCursor: next}
|
||||
for _, item := range items {
|
||||
page.Items = append(page.Items, chatToJSON(item))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (a *API) getChat(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID, ok := pathChatID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chat, err := a.db.Chat(r.Context(), chatID, user.ID)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err, "Неверный идентификатор чата")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatToJSON(chat))
|
||||
}
|
||||
|
||||
func (a *API) createMessage(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID, ok := pathChatID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.db.Chat(r.Context(), chatID, user.ID); err != nil {
|
||||
writeStoreError(w, r, err, "Неверный идентификатор чата")
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := readJSON(w, r, &body); err != nil {
|
||||
a.writeReadError(w, r, err)
|
||||
return
|
||||
}
|
||||
msg, err := a.db.AddMessage(r.Context(), chatID, user.ID, body.Text)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err, "Недопустимый текст сообщения")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, messageToJSON(msg))
|
||||
}
|
||||
|
||||
func (a *API) listMessages(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.requireUser(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chatID, ok := pathChatID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, cursor, ok := a.pageQuery(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if cursor != nil && (cursor.Resource != model.ResourceMessages || cursor.ChatID != chatID) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный cursor или limit", requestID(r))
|
||||
return
|
||||
}
|
||||
items, next, err := a.db.ListMessages(r.Context(), chatID, user.ID, limit, cursor)
|
||||
if err != nil {
|
||||
writeStoreError(w, r, err, "Неверный cursor или limit")
|
||||
return
|
||||
}
|
||||
page := messagePageJSON{Items: make([]messageJSON, 0, len(items)), NextCursor: next}
|
||||
for _, item := range items {
|
||||
page.Items = append(page.Items, messageToJSON(item))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (a *API) pageQuery(w http.ResponseWriter, r *http.Request) (int, *model.Cursor, bool) {
|
||||
limit, err := parseLimit(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный cursor или limit", requestID(r))
|
||||
return 0, nil, false
|
||||
}
|
||||
cursor, err := parseCursor(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный cursor или limit", requestID(r))
|
||||
return 0, nil, false
|
||||
}
|
||||
return limit, cursor, true
|
||||
}
|
||||
|
||||
func (a *API) writeReadError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if errors.Is(err, errTooLarge) {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, "payload_too_large", "Слишком большой запрос", requestID(r))
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный JSON", requestID(r))
|
||||
}
|
||||
|
||||
func pathChatID(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
chatID := strings.ToLower(r.PathValue("chat_id"))
|
||||
if !model.ValidUUID(chatID) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный идентификатор чата", requestID(r))
|
||||
return "", false
|
||||
}
|
||||
return chatID, true
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"mtusi.local/messenger/internal/jsonstrict"
|
||||
"mtusi.local/messenger/internal/model"
|
||||
)
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
wrote bool
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
if w.wrote {
|
||||
return
|
||||
}
|
||||
w.status = status
|
||||
w.wrote = true
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(body []byte) (int, error) {
|
||||
if !w.wrote {
|
||||
w.status = http.StatusOK
|
||||
w.wrote = true
|
||||
}
|
||||
return w.ResponseWriter.Write(body)
|
||||
}
|
||||
|
||||
type apiTime time.Time
|
||||
|
||||
func (t apiTime) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + model.FormatTime(time.Time(t)) + `"`), nil
|
||||
}
|
||||
|
||||
type userJSON struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt apiTime `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatJSON struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt apiTime `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 apiTime `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatPageJSON struct {
|
||||
Items []chatJSON `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type messagePageJSON struct {
|
||||
Items []messageJSON `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type sessionJSON struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt apiTime `json:"expires_at"`
|
||||
User userJSON `json:"user"`
|
||||
}
|
||||
|
||||
func userToJSON(user model.User) userJSON {
|
||||
return userJSON{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: apiTime(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func chatToJSON(chat model.Chat) chatJSON {
|
||||
members := chat.MemberIDs
|
||||
if members == nil {
|
||||
members = []string{}
|
||||
}
|
||||
return chatJSON{
|
||||
ID: chat.ID,
|
||||
Title: chat.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: apiTime(chat.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func messageToJSON(msg model.Message) messageJSON {
|
||||
return messageJSON{
|
||||
ID: msg.ID,
|
||||
ChatID: msg.ChatID,
|
||||
SenderID: msg.SenderID,
|
||||
Text: msg.Text,
|
||||
CreatedAt: apiTime(msg.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(value)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, code, message, requestID string) {
|
||||
writeJSON(w, status, map[string]any{
|
||||
"error": map[string]string{
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": requestID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func writeUnauthorized(w http.ResponseWriter, r *http.Request, basic bool) {
|
||||
if basic {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
} else {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", requestID(r))
|
||||
}
|
||||
|
||||
func readJSON(w http.ResponseWriter, r *http.Request, dst any) error {
|
||||
media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || media != "application/json" {
|
||||
return errBadJSON
|
||||
}
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64*1024))
|
||||
if err != nil {
|
||||
var tooBig *http.MaxBytesError
|
||||
if errors.As(err, &tooBig) {
|
||||
return errTooLarge
|
||||
}
|
||||
return errBadJSON
|
||||
}
|
||||
if err := jsonstrict.Decode(body, dst); err != nil {
|
||||
return errBadJSON
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func bodyEmpty(r *http.Request) bool {
|
||||
if r.Body == nil {
|
||||
return true
|
||||
}
|
||||
buf := make([]byte, 1)
|
||||
n, err := r.Body.Read(buf)
|
||||
if n > 0 {
|
||||
return false
|
||||
}
|
||||
return err == io.EOF || err == nil
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
var raw [16]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
return "request"
|
||||
}
|
||||
return hex.EncodeToString(raw[:])
|
||||
}
|
||||
|
||||
var (
|
||||
errBadJSON = errors.New("bad json")
|
||||
errTooLarge = errors.New("too large")
|
||||
)
|
||||
@@ -0,0 +1,224 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"mtusi.local/messenger/internal/authpw"
|
||||
"mtusi.local/messenger/internal/model"
|
||||
"mtusi.local/messenger/internal/pgstore"
|
||||
"mtusi.local/messenger/internal/sessions"
|
||||
)
|
||||
|
||||
type API struct {
|
||||
db *pgstore.Store
|
||||
session *sessions.Store
|
||||
log *slog.Logger
|
||||
dummy string
|
||||
draining atomic.Bool
|
||||
}
|
||||
|
||||
func New(db *pgstore.Store, session *sessions.Store, logger *slog.Logger, dummyHash string) *API {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &API{db: db, session: session, log: logger, dummy: dummyHash}
|
||||
}
|
||||
|
||||
func (a *API) StartDraining() {
|
||||
a.draining.Store(true)
|
||||
}
|
||||
|
||||
func (a *API) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", a.live)
|
||||
mux.HandleFunc("GET /health/ready", a.ready)
|
||||
mux.HandleFunc("POST /api/v1/users", a.createUser)
|
||||
mux.HandleFunc("GET /api/v1/users/me", a.currentUser)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", a.createSession)
|
||||
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.revokeSession)
|
||||
mux.HandleFunc("POST /api/v1/chats", a.createChat)
|
||||
mux.HandleFunc("GET /api/v1/chats", a.listChats)
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", a.getChat)
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.createMessage)
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.listMessages)
|
||||
mux.HandleFunc("/", a.notFound)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
id := newRequestID()
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Second)
|
||||
defer cancel()
|
||||
ctx = context.WithValue(ctx, requestIDKey{}, id)
|
||||
r = r.WithContext(ctx)
|
||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
sw.Header().Set("X-Request-Id", id)
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
a.log.Error("panic", "request_id", id, "method", r.Method, "path", r.URL.Path)
|
||||
a.log.Error("panic_stack", "request_id", id, "stack", string(debug.Stack()))
|
||||
if !sw.wrote {
|
||||
writeError(sw, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", id)
|
||||
}
|
||||
}
|
||||
a.log.Info("request",
|
||||
"request_id", id,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", sw.status,
|
||||
"duration_ms", float64(time.Since(started).Microseconds())/1000,
|
||||
)
|
||||
}()
|
||||
if a.draining.Load() && r.URL.Path != "/health/live" {
|
||||
writeError(sw, http.StatusServiceUnavailable, "unavailable", "Сервер завершает работу", id)
|
||||
return
|
||||
}
|
||||
mux.ServeHTTP(sw, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *API) live(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (a *API) ready(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := a.db.Ping(ctx); err != nil || a.session.Ping(ctx) != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", requestID(r))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (a *API) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusNotFound, "not_found", "Объект не найден", requestID(r))
|
||||
}
|
||||
|
||||
func (a *API) requireUser(w http.ResponseWriter, r *http.Request) (model.User, bool) {
|
||||
token, ok := bearerToken(r)
|
||||
if !ok {
|
||||
writeUnauthorized(w, r, false)
|
||||
return model.User{}, false
|
||||
}
|
||||
userID, err := a.session.Lookup(r.Context(), token)
|
||||
if errors.Is(err, model.ErrUnavailable) {
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", requestID(r))
|
||||
return model.User{}, false
|
||||
}
|
||||
if err != nil {
|
||||
writeUnauthorized(w, r, false)
|
||||
return model.User{}, false
|
||||
}
|
||||
user, err := a.db.UserByID(r.Context(), userID)
|
||||
if errors.Is(err, model.ErrUnavailable) {
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", requestID(r))
|
||||
return model.User{}, false
|
||||
}
|
||||
if err != nil {
|
||||
writeUnauthorized(w, r, false)
|
||||
return model.User{}, false
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) (string, bool) {
|
||||
scheme, param, ok := splitAuth(r.Header.Get("Authorization"))
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") || len(param) < 32 || strings.ContainsAny(param, " \t") {
|
||||
return "", false
|
||||
}
|
||||
return param, true
|
||||
}
|
||||
|
||||
func basicCredentials(r *http.Request) (string, string, bool) {
|
||||
scheme, param, ok := splitAuth(r.Header.Get("Authorization"))
|
||||
if !ok || !strings.EqualFold(scheme, "Basic") {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(param)
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
username, password, ok := strings.Cut(string(raw), ":")
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
return username, password, true
|
||||
}
|
||||
|
||||
func splitAuth(header string) (string, string, bool) {
|
||||
scheme, param, ok := strings.Cut(strings.TrimSpace(header), " ")
|
||||
if !ok || scheme == "" || strings.TrimSpace(param) == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return scheme, strings.TrimSpace(param), true
|
||||
}
|
||||
|
||||
func parseLimit(r *http.Request) (int, error) {
|
||||
values, ok := r.URL.Query()["limit"]
|
||||
if !ok {
|
||||
return 50, nil
|
||||
}
|
||||
if len(values) != 1 {
|
||||
return 0, errBadQuery
|
||||
}
|
||||
n, err := strconv.Atoi(values[0])
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, errBadQuery
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func parseCursor(r *http.Request) (*model.Cursor, error) {
|
||||
values, ok := r.URL.Query()["cursor"]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
return nil, errBadQuery
|
||||
}
|
||||
cursor, err := model.DecodeCursor(values[0])
|
||||
if err != nil {
|
||||
return nil, errBadQuery
|
||||
}
|
||||
return &cursor, nil
|
||||
}
|
||||
|
||||
func writeStoreError(w http.ResponseWriter, r *http.Request, err error, invalidMessage string) {
|
||||
switch {
|
||||
case errors.Is(err, model.ErrConflict):
|
||||
writeError(w, http.StatusConflict, "conflict", "Имя пользователя уже занято", requestID(r))
|
||||
case errors.Is(err, model.ErrNotFound):
|
||||
writeError(w, http.StatusNotFound, "not_found", "Объект не найден", requestID(r))
|
||||
case errors.Is(err, model.ErrUnavailable):
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", requestID(r))
|
||||
default:
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", invalidMessage, requestID(r))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *API) checkPassword(password, encoded string) bool {
|
||||
if encoded == "" {
|
||||
encoded = a.dummy
|
||||
}
|
||||
return authpw.Verify(password, encoded)
|
||||
}
|
||||
|
||||
type requestIDKey struct{}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
id, _ := r.Context().Value(requestIDKey{}).(string)
|
||||
if id == "" {
|
||||
id = newRequestID()
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
var errBadQuery = errors.New("bad query")
|
||||
@@ -0,0 +1,108 @@
|
||||
package jsonstrict
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var ErrInvalid = errors.New("invalid json")
|
||||
|
||||
func Decode(body []byte, dst any) error {
|
||||
if !utf8.Valid(body) {
|
||||
return ErrInvalid
|
||||
}
|
||||
keys, err := objectKeys(body)
|
||||
if err != nil {
|
||||
return ErrInvalid
|
||||
}
|
||||
allowed := tagNames(dst)
|
||||
for _, key := range keys {
|
||||
if _, ok := allowed[key]; !ok {
|
||||
return ErrInvalid
|
||||
}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return ErrInvalid
|
||||
}
|
||||
var trailer struct{}
|
||||
if err := dec.Decode(&trailer); !errors.Is(err, io.EOF) {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func objectKeys(body []byte) ([]string, error) {
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
token, err := dec.Token()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
delim, ok := token.(json.Delim)
|
||||
if !ok || delim != '{' {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
var keys []string
|
||||
for dec.More() {
|
||||
keyToken, err := dec.Token()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key, ok := keyToken.(string)
|
||||
if !ok {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
if _, dup := seen[key]; dup {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
keys = append(keys, key)
|
||||
var skip json.RawMessage
|
||||
if err := dec.Decode(&skip); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
token, err = dec.Token()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
delim, ok = token.(json.Delim)
|
||||
if !ok || delim != '}' {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
var trailer struct{}
|
||||
if err := dec.Decode(&trailer); !errors.Is(err, io.EOF) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func tagNames(dst any) map[string]struct{} {
|
||||
value := reflect.TypeOf(dst)
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
if value.Kind() == reflect.Pointer {
|
||||
value = value.Elem()
|
||||
}
|
||||
names := make(map[string]struct{})
|
||||
if value.Kind() != reflect.Struct {
|
||||
return names
|
||||
}
|
||||
for i := 0; i < value.NumField(); i++ {
|
||||
tag := value.Field(i).Tag.Get("json")
|
||||
name := strings.Split(tag, ",")[0]
|
||||
if name == "" || name == "-" {
|
||||
continue
|
||||
}
|
||||
names[name] = struct{}{}
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func Apply(ctx context.Context, pool *pgxpool.Pool, dir string) error {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migrations: %w", err)
|
||||
}
|
||||
var names []string
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||
continue
|
||||
}
|
||||
names = append(names, entry.Name())
|
||||
}
|
||||
sort.Strings(names)
|
||||
if len(names) == 0 {
|
||||
return fmt.Errorf("no sql migrations in %s", dir)
|
||||
}
|
||||
_, err = pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range names {
|
||||
var exists bool
|
||||
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
body, err := os.ReadFile(filepath.Join(dir, name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, stmt := range statements(string(body)) {
|
||||
if _, err := tx.Exec(ctx, stmt); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, name); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func statements(body string) []string {
|
||||
parts := strings.Split(body, ";")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
stmt := strings.TrimSpace(part)
|
||||
if stmt != "" {
|
||||
out = append(out, stmt)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi.local/messenger/internal/jsonstrict"
|
||||
)
|
||||
|
||||
const (
|
||||
ResourceMessages = "messages"
|
||||
ResourceChats = "chats"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalid = errors.New("invalid")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
|
||||
usernameRE = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
uuidRE = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string
|
||||
ChatID string
|
||||
SenderID string
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Cursor struct {
|
||||
Resource string
|
||||
ChatID string
|
||||
Time time.Time
|
||||
ID string
|
||||
}
|
||||
|
||||
type cursorWire struct {
|
||||
V int `json:"v"`
|
||||
Resource string `json:"r"`
|
||||
ChatID string `json:"c,omitempty"`
|
||||
Time string `json:"t"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func ValidUUID(value string) bool {
|
||||
return uuidRE.MatchString(strings.ToLower(value))
|
||||
}
|
||||
|
||||
func NormalizeUUID(value string) (string, bool) {
|
||||
id := strings.ToLower(strings.TrimSpace(value))
|
||||
if !uuidRE.MatchString(id) {
|
||||
return "", false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func ValidUsername(value string) bool {
|
||||
return usernameRE.MatchString(value)
|
||||
}
|
||||
|
||||
func ValidLabel(value string, max int) bool {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(value)
|
||||
return n >= 1 && n <= max
|
||||
}
|
||||
|
||||
func ValidPassword(value string) bool {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(value)
|
||||
return n >= 12 && n <= 128
|
||||
}
|
||||
|
||||
func FormatTime(value time.Time) string {
|
||||
return value.UTC().Format("2006-01-02T15:04:05.000000Z")
|
||||
}
|
||||
|
||||
func NewID() (string, error) {
|
||||
var raw [16]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
raw[6] = (raw[6] & 0x0f) | 0x40
|
||||
raw[8] = (raw[8] & 0x3f) | 0x80
|
||||
enc := hex.EncodeToString(raw[:])
|
||||
return enc[0:8] + "-" + enc[8:12] + "-" + enc[12:16] + "-" + enc[16:20] + "-" + enc[20:32], nil
|
||||
}
|
||||
|
||||
func EncodeCursor(cursor Cursor) (string, error) {
|
||||
raw, err := json.Marshal(cursorWire{
|
||||
V: 1,
|
||||
Resource: cursor.Resource,
|
||||
ChatID: cursor.ChatID,
|
||||
Time: FormatTime(cursor.Time),
|
||||
ID: cursor.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw), nil
|
||||
}
|
||||
|
||||
func DecodeCursor(token string) (Cursor, error) {
|
||||
if token == "" {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
var payload cursorWire
|
||||
if err := jsonstrict.Decode(raw, &payload); err != nil {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
if payload.V != 1 || !ValidUUID(payload.ID) {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
switch payload.Resource {
|
||||
case ResourceMessages:
|
||||
if !ValidUUID(payload.ChatID) {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
case ResourceChats:
|
||||
if payload.ChatID != "" {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
default:
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
ts, err := time.Parse("2006-01-02T15:04:05.000000Z", payload.Time)
|
||||
if err != nil {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
return Cursor{
|
||||
Resource: payload.Resource,
|
||||
ChatID: strings.ToLower(payload.ChatID),
|
||||
Time: ts.UTC(),
|
||||
ID: strings.ToLower(payload.ID),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
package pgstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi.local/messenger/internal/model"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
if !model.ValidUsername(username) || !model.ValidLabel(displayName, 100) || passwordHash == "" {
|
||||
return model.User{}, model.ErrInvalid
|
||||
}
|
||||
id, err := model.NewID()
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
created := time.Now().UTC().Truncate(time.Microsecond)
|
||||
user := model.User{ID: id, Username: username, DisplayName: displayName, CreatedAt: created}
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)`,
|
||||
user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
|
||||
if err != nil {
|
||||
return model.User{}, classify(err)
|
||||
}
|
||||
return s.UserByID(ctx, user.ID)
|
||||
}
|
||||
|
||||
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
|
||||
id, ok := model.NormalizeUUID(id)
|
||||
if !ok {
|
||||
return model.User{}, model.ErrNotFound
|
||||
}
|
||||
user, _, err := s.scanUser(ctx, `
|
||||
SELECT id::text, username, display_name, created_at, password_hash
|
||||
FROM users WHERE id = $1::uuid`, id)
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
|
||||
if !model.ValidUsername(username) {
|
||||
return model.User{}, "", model.ErrNotFound
|
||||
}
|
||||
return s.scanUser(ctx, `
|
||||
SELECT id::text, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = $1`, username)
|
||||
}
|
||||
|
||||
func (s *Store) CreateChat(ctx context.Context, caller, title string, memberIDs []string) (model.Chat, error) {
|
||||
if !model.ValidLabel(title, 100) || len(memberIDs) < 1 || len(memberIDs) > 100 {
|
||||
return model.Chat{}, model.ErrInvalid
|
||||
}
|
||||
caller, ok := model.NormalizeUUID(caller)
|
||||
if !ok {
|
||||
return model.Chat{}, model.ErrInvalid
|
||||
}
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
members := make([]string, 0, len(memberIDs))
|
||||
callerSeen := false
|
||||
for _, raw := range memberIDs {
|
||||
id, ok := model.NormalizeUUID(raw)
|
||||
if !ok {
|
||||
return model.Chat{}, model.ErrInvalid
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
return model.Chat{}, model.ErrInvalid
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == caller {
|
||||
callerSeen = true
|
||||
}
|
||||
members = append(members, id)
|
||||
}
|
||||
if !callerSeen {
|
||||
return model.Chat{}, model.ErrInvalid
|
||||
}
|
||||
id, err := model.NewID()
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
created := time.Now().UTC().Truncate(time.Microsecond)
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, classify(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`, id, title, created); err != nil {
|
||||
return model.Chat{}, classify(err)
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT $1::uuid, ord.id::uuid, ord.pos::int - 1
|
||||
FROM unnest($2::text[]) WITH ORDINALITY AS ord(id, pos)
|
||||
JOIN users AS u ON u.id = ord.id::uuid`, id, members)
|
||||
if err != nil {
|
||||
return model.Chat{}, classify(err)
|
||||
}
|
||||
if int(tag.RowsAffected()) != len(members) {
|
||||
return model.Chat{}, model.ErrInvalid
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, classify(err)
|
||||
}
|
||||
return model.Chat{ID: id, Title: title, MemberIDs: members, CreatedAt: created}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Chat(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
||||
chatID, ok := model.NormalizeUUID(chatID)
|
||||
if !ok {
|
||||
return model.Chat{}, model.ErrInvalid
|
||||
}
|
||||
userID, ok = model.NormalizeUUID(userID)
|
||||
if !ok {
|
||||
return model.Chat{}, model.ErrInvalid
|
||||
}
|
||||
var chat model.Chat
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
COALESCE((
|
||||
SELECT array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chat_members AS cm WHERE cm.chat_id = c.id
|
||||
), '{}'::text[])
|
||||
FROM chats AS c
|
||||
JOIN chat_members AS mine ON mine.chat_id = c.id AND mine.user_id = $2::uuid
|
||||
WHERE c.id = $1::uuid`, chatID, userID).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
if err != nil {
|
||||
return model.Chat{}, classify(err)
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
if chat.MemberIDs == nil {
|
||||
chat.MemberIDs = []string{}
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListChats(ctx context.Context, userID string, limit int, cursor *model.Cursor) ([]model.Chat, *string, error) {
|
||||
userID, ok := model.NormalizeUUID(userID)
|
||||
if !ok {
|
||||
return nil, nil, model.ErrInvalid
|
||||
}
|
||||
if cursor != nil && cursor.Resource != model.ResourceChats {
|
||||
return nil, nil, model.ErrInvalid
|
||||
}
|
||||
var afterTime *time.Time
|
||||
var afterID *string
|
||||
if cursor != nil {
|
||||
t := cursor.Time
|
||||
id := cursor.ID
|
||||
afterTime = &t
|
||||
afterID = &id
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
COALESCE((
|
||||
SELECT array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chat_members AS cm WHERE cm.chat_id = c.id
|
||||
), '{}'::text[])
|
||||
FROM chats AS c
|
||||
JOIN chat_members AS mine ON mine.chat_id = c.id AND mine.user_id = $1::uuid
|
||||
WHERE $2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`, userID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, nil, classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]model.Chat, 0)
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
||||
return nil, nil, classify(err)
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
if chat.MemberIDs == nil {
|
||||
chat.MemberIDs = []string{}
|
||||
}
|
||||
items = append(items, chat)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, classify(err)
|
||||
}
|
||||
return pageChats(items, limit)
|
||||
}
|
||||
|
||||
func (s *Store) AddMessage(ctx context.Context, chatID, senderID, text string) (model.Message, error) {
|
||||
if !model.ValidLabel(text, 4000) {
|
||||
return model.Message{}, model.ErrInvalid
|
||||
}
|
||||
chatID, ok := model.NormalizeUUID(chatID)
|
||||
if !ok {
|
||||
return model.Message{}, model.ErrInvalid
|
||||
}
|
||||
senderID, ok = model.NormalizeUUID(senderID)
|
||||
if !ok {
|
||||
return model.Message{}, model.ErrInvalid
|
||||
}
|
||||
id, err := model.NewID()
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
created := time.Now().UTC().Truncate(time.Microsecond)
|
||||
var msg model.Message
|
||||
err = s.pool.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $1::uuid, $2::uuid, $3::uuid, $4, $5
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members
|
||||
WHERE chat_id = $2::uuid AND user_id = $3::uuid
|
||||
)
|
||||
RETURNING id::text, chat_id::text, sender_id::text, text, created_at`,
|
||||
id, chatID, senderID, text, created).Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, model.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, classify(err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID, userID string, limit int, cursor *model.Cursor) ([]model.Message, *string, error) {
|
||||
chatID, ok := model.NormalizeUUID(chatID)
|
||||
if !ok {
|
||||
return nil, nil, model.ErrInvalid
|
||||
}
|
||||
userID, ok = model.NormalizeUUID(userID)
|
||||
if !ok {
|
||||
return nil, nil, model.ErrInvalid
|
||||
}
|
||||
if cursor != nil && (cursor.Resource != model.ResourceMessages || cursor.ChatID != chatID) {
|
||||
return nil, nil, model.ErrInvalid
|
||||
}
|
||||
if _, err := s.Chat(ctx, chatID, userID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var afterTime *time.Time
|
||||
var afterID *string
|
||||
if cursor != nil {
|
||||
t := cursor.Time
|
||||
id := cursor.ID
|
||||
afterTime = &t
|
||||
afterID = &id
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1::uuid
|
||||
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3::uuid))
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4`, chatID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, nil, classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]model.Message, 0)
|
||||
for rows.Next() {
|
||||
var msg model.Message
|
||||
if err := rows.Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt); err != nil {
|
||||
return nil, nil, classify(err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
items = append(items, msg)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, classify(err)
|
||||
}
|
||||
return pageMessages(items, limit, chatID)
|
||||
}
|
||||
|
||||
func (s *Store) scanUser(ctx context.Context, query string, arg any) (model.User, string, error) {
|
||||
var user model.User
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx, query, arg).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
|
||||
if err != nil {
|
||||
return model.User{}, "", classify(err)
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, hash, nil
|
||||
}
|
||||
|
||||
func pageMessages(items []model.Message, limit int, chatID string) ([]model.Message, *string, error) {
|
||||
if len(items) <= limit {
|
||||
return items, nil, nil
|
||||
}
|
||||
items = items[:limit]
|
||||
last := items[len(items)-1]
|
||||
token, err := model.EncodeCursor(model.Cursor{
|
||||
Resource: model.ResourceMessages,
|
||||
ChatID: chatID,
|
||||
Time: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return items, &token, nil
|
||||
}
|
||||
|
||||
func pageChats(items []model.Chat, limit int) ([]model.Chat, *string, error) {
|
||||
if len(items) <= limit {
|
||||
return items, nil, nil
|
||||
}
|
||||
items = items[:limit]
|
||||
last := items[len(items)-1]
|
||||
token, err := model.EncodeCursor(model.Cursor{
|
||||
Resource: model.ResourceChats,
|
||||
Time: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return items, &token, nil
|
||||
}
|
||||
|
||||
func classify(err error) error {
|
||||
if err == nil || errors.Is(err, model.ErrInvalid) || errors.Is(err, model.ErrConflict) || errors.Is(err, model.ErrNotFound) || errors.Is(err, model.ErrUnavailable) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.ErrNotFound
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return model.ErrConflict
|
||||
case "23503", "23514", "23502", "22P02":
|
||||
return model.ErrInvalid
|
||||
default:
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
}
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi.local/messenger/internal/model"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
type record struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
func New(client *redis.Client, ttl time.Duration) *Store {
|
||||
return &Store{client: client, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.client.Ping(ctx).Err(); err != nil {
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Create(ctx context.Context, userID string) (string, time.Time, error) {
|
||||
var raw [32]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw[:])
|
||||
expires := time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
|
||||
body, err := json.Marshal(record{UserID: userID, ExpiresAt: expires})
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
if err := s.client.Set(ctx, key(token), body, s.ttl).Err(); err != nil {
|
||||
return "", time.Time{}, model.ErrUnavailable
|
||||
}
|
||||
return token, expires, nil
|
||||
}
|
||||
|
||||
func (s *Store) Lookup(ctx context.Context, token string) (string, error) {
|
||||
body, err := s.client.Get(ctx, key(token)).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", model.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", model.ErrUnavailable
|
||||
}
|
||||
var item record
|
||||
if err := json.Unmarshal(body, &item); err != nil || item.UserID == "" {
|
||||
return "", model.ErrNotFound
|
||||
}
|
||||
if !item.ExpiresAt.After(time.Now()) {
|
||||
_ = s.client.Del(ctx, key(token)).Err()
|
||||
return "", model.ErrNotFound
|
||||
}
|
||||
return item.UserID, nil
|
||||
}
|
||||
|
||||
func (s *Store) Revoke(ctx context.Context, token string) error {
|
||||
if err := s.client.Del(ctx, key(token)).Err(); err != nil {
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func key(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "sess:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
Reference in New Issue
Block a user