feat: build core API, fraud engine, notifier, and frontend
Phase 1 — Core API (Go): - Events, guests, tokens, RSVPs CRUD on PostgreSQL via pgx/v5 - HMAC-signed per-guest tokens with format validation - Health endpoint with DB ping, slog JSON logging, graceful shutdown Phase 2 — NATS + Fraud Engine: - NATS JetStream pub/sub with explicit-ack consumers - Python/FastAPI fraud engine with heuristic risk scoring (fingerprint mismatch, IP change, missing signals, repeated access) - gRPC sync scoring with 250ms fail-open timeout - Per-guest baseline tracking; risk bands low/medium/high/block Phase 3 — Notifications + Frontend: - Notification worker scaffolding (Twilio/SES stubs, retry/backoff) - Nuxt 3 frontend with Tailwind dark theme + brand green - Live monitor via WebSocket with auto-reconnect - Activity history endpoint backfills monitor with RSVPs + scored access checks (including blocked attempts) UX polish: - Marketing-friendly landing page (hero mockup, how-it-works, features, use cases, testimonials, FAQ, final CTA) - Animated layered card mockups on landing + new-event page - Plus-ones stepper, RSVP status badges, filter buttons - Friendly access-check labels (Verified/Review/Suspicious/Blocked) - Dashboard hydration fix via ClientOnly wrapper Infrastructure: - docker-compose for full local dev (postgres, nats, api, fraud-engine, notifier, frontend) - Multi-stage Dockerfiles, non-root UID 1000 - Integration tests with testcontainers-go Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
// activityHandler serves the combined RSVP + access-check history for an
|
||||
// event. The WebSocket hub only fans out *live* events to currently-
|
||||
// connected dashboards; this endpoint is the catch-up channel for hosts
|
||||
// who weren't watching when activity happened.
|
||||
type activityHandler struct {
|
||||
events *storage.EventRepo
|
||||
rsvps *storage.RSVPRepo
|
||||
accessLogs *storage.AccessLogRepo
|
||||
}
|
||||
|
||||
type activityItem struct {
|
||||
Type string `json:"type"` // "rsvp" | "access_check"
|
||||
Timestamp time.Time `json:"ts"`
|
||||
GuestID string `json:"guest_id"`
|
||||
GuestName string `json:"guest_name"`
|
||||
|
||||
// RSVP-only
|
||||
Response string `json:"response,omitempty"`
|
||||
PlusOnes int `json:"plus_ones,omitempty"`
|
||||
|
||||
// Access-check-only
|
||||
Score int `json:"score,omitempty"`
|
||||
Band string `json:"band,omitempty"`
|
||||
Blocked bool `json:"blocked,omitempty"`
|
||||
}
|
||||
|
||||
// GET /events/{id}/activity?limit=50
|
||||
//
|
||||
// Returns the most recent N activity items (RSVPs + scored access checks)
|
||||
// for an event, sorted newest first. Frontends use this on dashboard mount
|
||||
// to backfill the live monitor with history.
|
||||
func (h *activityHandler) list(w http.ResponseWriter, r *http.Request) {
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.events.Get(r.Context(), eventID); err != nil {
|
||||
if errors.Is(err, domain.ErrEventNotFound) {
|
||||
writeError(w, http.StatusNotFound, "event not found")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to load event")
|
||||
return
|
||||
}
|
||||
|
||||
limit := atoiOr(r.URL.Query().Get("limit"), 50)
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
// Pull from each source. We grab `limit` from each so that after
|
||||
// merging we still have at least `limit` of the truly newest items.
|
||||
rsvps, err := h.rsvps.ListRecentByEvent(r.Context(), eventID, limit)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load activity")
|
||||
return
|
||||
}
|
||||
checks, err := h.accessLogs.ListRecentScoredByEvent(r.Context(), eventID, limit)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load activity")
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]activityItem, 0, len(rsvps)+len(checks))
|
||||
for _, a := range rsvps {
|
||||
items = append(items, activityItem{
|
||||
Type: "rsvp",
|
||||
Timestamp: a.SubmittedAt,
|
||||
GuestID: a.GuestID.String(),
|
||||
GuestName: a.GuestName,
|
||||
Response: a.Response,
|
||||
PlusOnes: a.PlusOnes,
|
||||
})
|
||||
}
|
||||
for _, c := range checks {
|
||||
items = append(items, activityItem{
|
||||
Type: "access_check",
|
||||
Timestamp: c.CreatedAt,
|
||||
GuestID: c.GuestID.String(),
|
||||
GuestName: c.GuestName,
|
||||
Score: c.Score,
|
||||
Band: bandFromScore(c.Score),
|
||||
Blocked: c.Score >= 80,
|
||||
})
|
||||
}
|
||||
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
return items[i].Timestamp.After(items[j].Timestamp)
|
||||
})
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"activity": items,
|
||||
})
|
||||
}
|
||||
|
||||
// bandFromScore mirrors the friendly buckets used by the live WebSocket
|
||||
// pipeline so backfilled items and live items render the same way in the
|
||||
// dashboard feed. Thresholds match the fraud engine's intent: 0–29 looks
|
||||
// normal, 30–59 worth a glance, 60–79 suspicious, ≥80 blocked.
|
||||
func bandFromScore(score int) string {
|
||||
switch {
|
||||
case score >= 80:
|
||||
return "block"
|
||||
case score >= 60:
|
||||
return "high"
|
||||
case score >= 30:
|
||||
return "medium"
|
||||
default:
|
||||
return "low"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
type eventHandler struct {
|
||||
repo *storage.EventRepo
|
||||
}
|
||||
|
||||
type createEventRequest struct {
|
||||
HostID string `json:"host_id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
EventDate time.Time `json:"event_date"`
|
||||
Venue string `json:"venue"`
|
||||
MaxCapacity int `json:"max_capacity"`
|
||||
Settings map[string]any `json:"settings"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
var slugRe = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
|
||||
|
||||
func (h *eventHandler) create(w http.ResponseWriter, r *http.Request) {
|
||||
var req createEventRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" {
|
||||
writeError(w, http.StatusBadRequest, "name is required")
|
||||
return
|
||||
}
|
||||
if !slugRe.MatchString(req.Slug) {
|
||||
writeError(w, http.StatusBadRequest, "slug must be lowercase alphanumeric with hyphens")
|
||||
return
|
||||
}
|
||||
if req.EventDate.IsZero() {
|
||||
writeError(w, http.StatusBadRequest, "event_date is required")
|
||||
return
|
||||
}
|
||||
|
||||
hostID, err := uuid.Parse(req.HostID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "host_id must be a valid uuid")
|
||||
return
|
||||
}
|
||||
|
||||
status := domain.EventStatus(req.Status)
|
||||
if status == "" {
|
||||
status = domain.EventStatusDraft
|
||||
}
|
||||
if !status.Valid() {
|
||||
writeError(w, http.StatusBadRequest, "invalid status")
|
||||
return
|
||||
}
|
||||
|
||||
ev, err := h.repo.Create(r.Context(), storage.CreateEventParams{
|
||||
HostID: hostID,
|
||||
Name: req.Name,
|
||||
Slug: req.Slug,
|
||||
EventDate: req.EventDate,
|
||||
Venue: req.Venue,
|
||||
MaxCapacity: req.MaxCapacity,
|
||||
Settings: req.Settings,
|
||||
Status: status,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrSlugTaken) {
|
||||
writeError(w, http.StatusConflict, "slug already in use")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to create event")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, ev)
|
||||
}
|
||||
|
||||
func (h *eventHandler) get(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ev, err := h.repo.Get(r.Context(), id)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrEventNotFound) {
|
||||
writeError(w, http.StatusNotFound, "event not found")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to load event")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, ev)
|
||||
}
|
||||
|
||||
func (h *eventHandler) list(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
limit := atoiOr(q.Get("limit"), 50)
|
||||
offset := atoiOr(q.Get("offset"), 0)
|
||||
|
||||
var hostID uuid.UUID
|
||||
if v := q.Get("host_id"); v != "" {
|
||||
parsed, err := uuid.Parse(v)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "host_id must be a valid uuid")
|
||||
return
|
||||
}
|
||||
hostID = parsed
|
||||
}
|
||||
|
||||
events, err := h.repo.List(r.Context(), hostID, limit, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list events")
|
||||
return
|
||||
}
|
||||
if events == nil {
|
||||
events = []*domain.Event{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"events": events,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
}
|
||||
|
||||
type updateEventRequest struct {
|
||||
Name *string `json:"name"`
|
||||
Slug *string `json:"slug"`
|
||||
EventDate *time.Time `json:"event_date"`
|
||||
Venue *string `json:"venue"`
|
||||
MaxCapacity *int `json:"max_capacity"`
|
||||
Settings *map[string]any `json:"settings"`
|
||||
Status *string `json:"status"`
|
||||
}
|
||||
|
||||
func (h *eventHandler) update(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var req updateEventRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
|
||||
params := storage.UpdateEventParams{
|
||||
Name: req.Name,
|
||||
EventDate: req.EventDate,
|
||||
Venue: req.Venue,
|
||||
MaxCapacity: req.MaxCapacity,
|
||||
Settings: req.Settings,
|
||||
}
|
||||
if req.Slug != nil {
|
||||
if !slugRe.MatchString(*req.Slug) {
|
||||
writeError(w, http.StatusBadRequest, "slug must be lowercase alphanumeric with hyphens")
|
||||
return
|
||||
}
|
||||
params.Slug = req.Slug
|
||||
}
|
||||
if req.Status != nil {
|
||||
s := domain.EventStatus(*req.Status)
|
||||
if !s.Valid() {
|
||||
writeError(w, http.StatusBadRequest, "invalid status")
|
||||
return
|
||||
}
|
||||
params.Status = &s
|
||||
}
|
||||
|
||||
ev, err := h.repo.Update(r.Context(), id, params)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrEventNotFound):
|
||||
writeError(w, http.StatusNotFound, "event not found")
|
||||
case errors.Is(err, domain.ErrSlugTaken):
|
||||
writeError(w, http.StatusConflict, "slug already in use")
|
||||
default:
|
||||
writeError(w, http.StatusInternalServerError, "failed to update event")
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, ev)
|
||||
}
|
||||
|
||||
func (h *eventHandler) delete(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.repo.Delete(r.Context(), id); err != nil {
|
||||
if errors.Is(err, domain.ErrEventNotFound) {
|
||||
writeError(w, http.StatusNotFound, "event not found")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete event")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func parseIDParam(w http.ResponseWriter, r *http.Request, name string) (uuid.UUID, bool) {
|
||||
raw := r.PathValue(name)
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, name+" must be a valid uuid")
|
||||
return uuid.Nil, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func atoiOr(s string, fallback int) int {
|
||||
if s == "" {
|
||||
return fallback
|
||||
}
|
||||
if n, err := strconv.Atoi(s); err == nil {
|
||||
return n
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
type guestHandler struct {
|
||||
guests *storage.GuestRepo
|
||||
events *storage.EventRepo
|
||||
}
|
||||
|
||||
type createGuestRequest struct {
|
||||
Name string `json:"name"`
|
||||
Email *string `json:"email"`
|
||||
Phone *string `json:"phone"`
|
||||
PlusOnes int `json:"plus_ones"`
|
||||
DietaryNotes *string `json:"dietary_notes"`
|
||||
TableNumber *int `json:"table_number"`
|
||||
}
|
||||
|
||||
func (h *guestHandler) create(w http.ResponseWriter, r *http.Request) {
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.events.Get(r.Context(), eventID); err != nil {
|
||||
if errors.Is(err, domain.ErrEventNotFound) {
|
||||
writeError(w, http.StatusNotFound, "event not found")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to load event")
|
||||
return
|
||||
}
|
||||
|
||||
var req createGuestRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
if req.Name == "" {
|
||||
writeError(w, http.StatusBadRequest, "name is required")
|
||||
return
|
||||
}
|
||||
if req.PlusOnes < 0 {
|
||||
writeError(w, http.StatusBadRequest, "plus_ones must be >= 0")
|
||||
return
|
||||
}
|
||||
|
||||
g, err := h.guests.Create(r.Context(), storage.CreateGuestParams{
|
||||
EventID: eventID,
|
||||
Name: req.Name,
|
||||
Email: req.Email,
|
||||
Phone: req.Phone,
|
||||
PlusOnes: req.PlusOnes,
|
||||
DietaryNotes: req.DietaryNotes,
|
||||
TableNumber: req.TableNumber,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create guest")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, g)
|
||||
}
|
||||
|
||||
func (h *guestHandler) list(w http.ResponseWriter, r *http.Request) {
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
limit := atoiOr(q.Get("limit"), 100)
|
||||
offset := atoiOr(q.Get("offset"), 0)
|
||||
|
||||
guests, err := h.guests.ListByEventWithRSVP(r.Context(), eventID, limit, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list guests")
|
||||
return
|
||||
}
|
||||
if guests == nil {
|
||||
guests = []*storage.GuestWithRSVP{}
|
||||
}
|
||||
|
||||
stats := struct {
|
||||
Total int `json:"total"`
|
||||
Attending int `json:"attending"`
|
||||
Declined int `json:"declined"`
|
||||
Maybe int `json:"maybe"`
|
||||
Pending int `json:"pending"`
|
||||
}{Total: len(guests)}
|
||||
for _, g := range guests {
|
||||
switch {
|
||||
case g.RSVPResponse == nil:
|
||||
stats.Pending++
|
||||
case *g.RSVPResponse == string(domain.RSVPAttending):
|
||||
stats.Attending++
|
||||
case *g.RSVPResponse == string(domain.RSVPDeclined):
|
||||
stats.Declined++
|
||||
case *g.RSVPResponse == string(domain.RSVPMaybe):
|
||||
stats.Maybe++
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"guests": guests,
|
||||
"stats": stats,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type healthHandler struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func (h *healthHandler) live(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *healthHandler) ready(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := h.pool.Ping(ctx); err != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
"status": "unavailable",
|
||||
"db": "down",
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{
|
||||
"status": "ok",
|
||||
"db": "up",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int
|
||||
}
|
||||
|
||||
func (s *statusRecorder) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *statusRecorder) Write(b []byte) (int, error) {
|
||||
if s.status == 0 {
|
||||
s.status = http.StatusOK
|
||||
}
|
||||
n, err := s.ResponseWriter.Write(b)
|
||||
s.bytes += n
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Hijack passes through to the underlying ResponseWriter so WebSocket
|
||||
// upgrades work despite the middleware wrapper. Returning ErrNotSupported
|
||||
// (rather than a custom error) lets callers detect this generically.
|
||||
func (s *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
if h, ok := s.ResponseWriter.(http.Hijacker); ok {
|
||||
return h.Hijack()
|
||||
}
|
||||
return nil, nil, errors.New("response writer does not support hijack")
|
||||
}
|
||||
|
||||
func (s *statusRecorder) Flush() {
|
||||
if f, ok := s.ResponseWriter.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func loggingMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w}
|
||||
next.ServeHTTP(rec, r)
|
||||
logger.Info("http",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", rec.status,
|
||||
"bytes", rec.bytes,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"remote", r.RemoteAddr,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func recoverMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
logger.Error("panic", "err", rec, "path", r.URL.Path)
|
||||
writeError(w, http.StatusInternalServerError, "internal server error")
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
if body == nil {
|
||||
return
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
slog.Error("write json", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, errorBody{Error: msg})
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/auth"
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/fraud"
|
||||
"github.com/alchemistkay/guestguard/internal/natspub"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
type rsvpPublisher interface {
|
||||
PublishRSVPConfirmed(ctx context.Context, evt natspub.RSVPConfirmed) error
|
||||
}
|
||||
|
||||
type fraudScorer interface {
|
||||
Score(ctx context.Context, in fraud.ScoreInput) fraud.Decision
|
||||
}
|
||||
|
||||
type rsvpHandler struct {
|
||||
logger *slog.Logger
|
||||
guests *storage.GuestRepo
|
||||
tokens *storage.TokenRepo
|
||||
events *storage.EventRepo
|
||||
rsvps *storage.RSVPRepo
|
||||
accessLogs *storage.AccessLogRepo
|
||||
scorer fraudScorer
|
||||
pub rsvpPublisher
|
||||
}
|
||||
|
||||
type submitRSVPRequest struct {
|
||||
Response string `json:"response"`
|
||||
PlusOnes int `json:"plus_ones"`
|
||||
DietaryNotes *string `json:"dietary_notes"`
|
||||
Fingerprint map[string]any `json:"fingerprint"`
|
||||
}
|
||||
|
||||
type submitRSVPResponse struct {
|
||||
RSVP *domain.RSVP `json:"rsvp"`
|
||||
Decision fraud.Decision `json:"fraud"`
|
||||
Blocked bool `json:"blocked"`
|
||||
}
|
||||
|
||||
// POST /rsvp/{token} — synchronous fraud check + RSVP recording.
|
||||
func (h *rsvpHandler) submit(w http.ResponseWriter, r *http.Request) {
|
||||
raw := r.PathValue("token")
|
||||
if err := auth.ValidateFormat(raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "malformed token")
|
||||
return
|
||||
}
|
||||
|
||||
tk, err := h.tokens.GetByHash(r.Context(), auth.HashToken(raw))
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrTokenNotFound) {
|
||||
writeError(w, http.StatusNotFound, "token not found")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to load token")
|
||||
return
|
||||
}
|
||||
if err := tk.IsValid(time.Now().UTC()); err != nil {
|
||||
writeError(w, http.StatusGone, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var req submitRSVPRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
resp := domain.RSVPResponse(req.Response)
|
||||
if !resp.Valid() {
|
||||
writeError(w, http.StatusBadRequest, "response must be attending|declined|maybe")
|
||||
return
|
||||
}
|
||||
if req.PlusOnes < 0 {
|
||||
writeError(w, http.StatusBadRequest, "plus_ones must be >= 0")
|
||||
return
|
||||
}
|
||||
|
||||
guest, err := h.guests.Get(r.Context(), tk.GuestID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load guest")
|
||||
return
|
||||
}
|
||||
if req.PlusOnes > guest.PlusOnes {
|
||||
writeError(w, http.StatusBadRequest,
|
||||
fmt.Sprintf("you may bring up to %d plus-one(s)", guest.PlusOnes))
|
||||
return
|
||||
}
|
||||
event, err := h.events.Get(r.Context(), guest.EventID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load event")
|
||||
return
|
||||
}
|
||||
|
||||
fingerprint := mergeFingerprint(req.Fingerprint, collectFingerprint(r))
|
||||
ip := clientIP(r)
|
||||
|
||||
accessLogID, err := h.accessLogs.Create(r.Context(), storage.CreateAccessLogParams{
|
||||
GuestID: guest.ID,
|
||||
TokenID: tk.ID,
|
||||
Fingerprint: fingerprint,
|
||||
IPAddress: ip,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("create access log", "err", err)
|
||||
}
|
||||
|
||||
decision := h.scorer.Score(r.Context(), fraud.ScoreInput{
|
||||
EventID: event.ID,
|
||||
GuestID: guest.ID,
|
||||
TokenID: tk.ID,
|
||||
AccessLogID: accessLogID,
|
||||
Fingerprint: stringifyFingerprint(fingerprint),
|
||||
IPAddress: ip,
|
||||
UserAgent: r.UserAgent(),
|
||||
Referrer: r.Referer(),
|
||||
})
|
||||
|
||||
if fraud.IsBlock(decision) {
|
||||
writeJSON(w, http.StatusForbidden, submitRSVPResponse{
|
||||
Decision: decision,
|
||||
Blocked: true,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
score := decision.Score
|
||||
rsvp, err := h.rsvps.Create(r.Context(), storage.CreateRSVPParams{
|
||||
GuestID: guest.ID,
|
||||
Response: resp,
|
||||
PlusOnes: req.PlusOnes,
|
||||
DietaryNotes: req.DietaryNotes,
|
||||
DeviceFingerprint: fingerprint,
|
||||
IPAddress: ip,
|
||||
RiskScore: &score,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrRSVPAlreadySubmitted) {
|
||||
writeError(w, http.StatusConflict, "rsvp already submitted for this guest")
|
||||
return
|
||||
}
|
||||
h.logger.Error("create rsvp", "err", err, "guest_id", guest.ID)
|
||||
writeError(w, http.StatusInternalServerError, "failed to record rsvp")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.tokens.MarkUsed(r.Context(), tk.ID); err != nil {
|
||||
h.logger.Warn("mark token used", "err", err, "token_id", tk.ID)
|
||||
}
|
||||
|
||||
go func(evt natspub.RSVPConfirmed) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := h.pub.PublishRSVPConfirmed(ctx, evt); err != nil {
|
||||
h.logger.Error("publish rsvp.confirmed", "err", err, "rsvp_id", evt.RSVPID)
|
||||
}
|
||||
}(natspub.RSVPConfirmed{
|
||||
EventID: event.ID,
|
||||
GuestID: guest.ID,
|
||||
RSVPID: rsvp.ID,
|
||||
Response: string(rsvp.Response),
|
||||
PlusOnes: rsvp.PlusOnes,
|
||||
RiskScore: &score,
|
||||
SubmittedAt: rsvp.SubmittedAt,
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusCreated, submitRSVPResponse{
|
||||
RSVP: rsvp,
|
||||
Decision: decision,
|
||||
Blocked: false,
|
||||
})
|
||||
}
|
||||
|
||||
func mergeFingerprint(client map[string]any, server map[string]any) map[string]any {
|
||||
out := make(map[string]any, len(server)+len(client))
|
||||
for k, v := range server {
|
||||
out[k] = v
|
||||
}
|
||||
for k, v := range client {
|
||||
out["client_"+k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func stringifyFingerprint(fp map[string]any) map[string]string {
|
||||
if fp == nil {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]string, len(fp))
|
||||
for k, v := range fp {
|
||||
switch tv := v.(type) {
|
||||
case string:
|
||||
out[k] = tv
|
||||
default:
|
||||
b, _ := json.Marshal(tv)
|
||||
out[k] = string(b)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/auth"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
logger *slog.Logger
|
||||
db *storage.DB
|
||||
hub *Hub
|
||||
users *userHandler
|
||||
events *eventHandler
|
||||
guests *guestHandler
|
||||
tokens *tokenHandler
|
||||
rsvps *rsvpHandler
|
||||
activity *activityHandler
|
||||
ws *wsHandler
|
||||
health *healthHandler
|
||||
}
|
||||
|
||||
type ServerDeps struct {
|
||||
Logger *slog.Logger
|
||||
DB *storage.DB
|
||||
Hub *Hub
|
||||
AccessPublisher accessPublisher
|
||||
RSVPPublisher rsvpPublisher
|
||||
FraudScorer fraudScorer
|
||||
TokenTTL time.Duration
|
||||
}
|
||||
|
||||
func NewServer(deps ServerDeps) *Server {
|
||||
eventRepo := storage.NewEventRepo(deps.DB)
|
||||
guestRepo := storage.NewGuestRepo(deps.DB)
|
||||
tokenRepo := storage.NewTokenRepo(deps.DB)
|
||||
rsvpRepo := storage.NewRSVPRepo(deps.DB)
|
||||
accessRepo := storage.NewAccessLogRepo(deps.DB)
|
||||
userRepo := storage.NewUserRepo(deps.DB)
|
||||
|
||||
hub := deps.Hub
|
||||
if hub == nil {
|
||||
hub = NewHub(deps.Logger)
|
||||
}
|
||||
|
||||
return &Server{
|
||||
logger: deps.Logger,
|
||||
db: deps.DB,
|
||||
hub: hub,
|
||||
users: &userHandler{repo: userRepo},
|
||||
events: &eventHandler{repo: eventRepo},
|
||||
guests: &guestHandler{guests: guestRepo, events: eventRepo},
|
||||
tokens: &tokenHandler{
|
||||
logger: deps.Logger,
|
||||
guests: guestRepo,
|
||||
tokens: tokenRepo,
|
||||
events: eventRepo,
|
||||
accessLogs: accessRepo,
|
||||
gen: auth.NewGenerator(),
|
||||
ttl: deps.TokenTTL,
|
||||
pub: deps.AccessPublisher,
|
||||
},
|
||||
rsvps: &rsvpHandler{
|
||||
logger: deps.Logger,
|
||||
guests: guestRepo,
|
||||
tokens: tokenRepo,
|
||||
events: eventRepo,
|
||||
rsvps: rsvpRepo,
|
||||
accessLogs: accessRepo,
|
||||
scorer: deps.FraudScorer,
|
||||
pub: deps.RSVPPublisher,
|
||||
},
|
||||
activity: &activityHandler{
|
||||
events: eventRepo,
|
||||
rsvps: rsvpRepo,
|
||||
accessLogs: accessRepo,
|
||||
},
|
||||
ws: &wsHandler{logger: deps.Logger, hub: hub},
|
||||
health: &healthHandler{pool: deps.DB.Pool},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Hub() *Hub { return s.hub }
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("GET /health", s.health.live)
|
||||
mux.HandleFunc("GET /health/ready", s.health.ready)
|
||||
|
||||
mux.HandleFunc("POST /users", s.users.upsert)
|
||||
|
||||
mux.HandleFunc("POST /events", s.events.create)
|
||||
mux.HandleFunc("GET /events", s.events.list)
|
||||
mux.HandleFunc("GET /events/{id}", s.events.get)
|
||||
mux.HandleFunc("PATCH /events/{id}", s.events.update)
|
||||
mux.HandleFunc("DELETE /events/{id}", s.events.delete)
|
||||
|
||||
mux.HandleFunc("POST /events/{id}/guests", s.guests.create)
|
||||
mux.HandleFunc("GET /events/{id}/guests", s.guests.list)
|
||||
|
||||
mux.HandleFunc("GET /events/{id}/activity", s.activity.list)
|
||||
|
||||
mux.HandleFunc("POST /events/{id}/guests/{guest_id}/tokens", s.tokens.issue)
|
||||
mux.HandleFunc("GET /access/{token}", s.tokens.access)
|
||||
mux.HandleFunc("POST /rsvp/{token}", s.rsvps.submit)
|
||||
|
||||
mux.HandleFunc("GET /ws/events/{id}", s.ws.handle)
|
||||
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusNotFound, "not found")
|
||||
})
|
||||
|
||||
var h http.Handler = mux
|
||||
h = corsMiddleware(h)
|
||||
h = loggingMiddleware(s.logger)(h)
|
||||
h = recoverMiddleware(s.logger)(h)
|
||||
return h
|
||||
}
|
||||
|
||||
// Permissive CORS for the dev frontend on a different origin. In production
|
||||
// the frontend is served from the same domain so this is largely a no-op.
|
||||
func corsMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin != "" {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Vary", "Origin")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-Device-Fingerprint")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/auth"
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/natspub"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
type accessPublisher interface {
|
||||
PublishAccessAttempted(ctx context.Context, evt natspub.AccessAttempted) error
|
||||
}
|
||||
|
||||
type tokenHandler struct {
|
||||
logger *slog.Logger
|
||||
guests *storage.GuestRepo
|
||||
tokens *storage.TokenRepo
|
||||
events *storage.EventRepo
|
||||
accessLogs *storage.AccessLogRepo
|
||||
gen *auth.Generator
|
||||
ttl time.Duration
|
||||
pub accessPublisher
|
||||
}
|
||||
|
||||
type issueTokenResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenID uuid.UUID `json:"token_id"`
|
||||
Meta *domain.Token `json:"meta"`
|
||||
}
|
||||
|
||||
// POST /events/{id}/guests/{guest_id}/tokens — issue a token for the guest.
|
||||
func (h *tokenHandler) issue(w http.ResponseWriter, r *http.Request) {
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
guestID, ok := parseIDParam(w, r, "guest_id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
guest, err := h.guests.Get(r.Context(), guestID)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrGuestNotFound) {
|
||||
writeError(w, http.StatusNotFound, "guest not found")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to load guest")
|
||||
return
|
||||
}
|
||||
if guest.EventID != eventID {
|
||||
writeError(w, http.StatusNotFound, "guest not found in event")
|
||||
return
|
||||
}
|
||||
|
||||
raw, hash, err := h.gen.Generate()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to generate token")
|
||||
return
|
||||
}
|
||||
|
||||
tk, err := h.tokens.Create(r.Context(), storage.CreateTokenParams{
|
||||
GuestID: guestID,
|
||||
TokenHash: hash,
|
||||
ExpiresAt: time.Now().UTC().Add(h.ttl),
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusConflict, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, issueTokenResponse{
|
||||
Token: raw,
|
||||
TokenID: tk.ID,
|
||||
Meta: tk,
|
||||
})
|
||||
}
|
||||
|
||||
type accessResponse struct {
|
||||
Guest *domain.Guest `json:"guest"`
|
||||
Event *domain.Event `json:"event"`
|
||||
Token *domain.Token `json:"token"`
|
||||
AccessLog uuid.UUID `json:"access_log_id"`
|
||||
}
|
||||
|
||||
// GET /access/{token} — validate token, log the access attempt, publish to NATS.
|
||||
func (h *tokenHandler) access(w http.ResponseWriter, r *http.Request) {
|
||||
raw := r.PathValue("token")
|
||||
if err := auth.ValidateFormat(raw); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "malformed token")
|
||||
return
|
||||
}
|
||||
|
||||
tk, err := h.tokens.GetByHash(r.Context(), auth.HashToken(raw))
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrTokenNotFound) {
|
||||
writeError(w, http.StatusNotFound, "token not found")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to load token")
|
||||
return
|
||||
}
|
||||
if err := tk.IsValid(time.Now().UTC()); err != nil {
|
||||
writeError(w, http.StatusGone, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
guest, err := h.guests.Get(r.Context(), tk.GuestID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load guest")
|
||||
return
|
||||
}
|
||||
event, err := h.events.Get(r.Context(), guest.EventID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load event")
|
||||
return
|
||||
}
|
||||
|
||||
fingerprint := collectFingerprint(r)
|
||||
ip := clientIP(r)
|
||||
|
||||
accessLogID, err := h.accessLogs.Create(r.Context(), storage.CreateAccessLogParams{
|
||||
GuestID: guest.ID,
|
||||
TokenID: tk.ID,
|
||||
Fingerprint: fingerprint,
|
||||
IPAddress: ip,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("create access log", "err", err)
|
||||
}
|
||||
|
||||
go func(evt natspub.AccessAttempted) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := h.pub.PublishAccessAttempted(ctx, evt); err != nil {
|
||||
h.logger.Error("publish access.attempted", "err", err, "guest_id", evt.GuestID)
|
||||
}
|
||||
}(natspub.AccessAttempted{
|
||||
EventID: event.ID,
|
||||
GuestID: guest.ID,
|
||||
TokenID: tk.ID,
|
||||
AccessLogID: accessLogID,
|
||||
Fingerprint: fingerprint,
|
||||
IPAddress: ip,
|
||||
UserAgent: r.UserAgent(),
|
||||
Referrer: r.Referer(),
|
||||
OccurredAt: time.Now().UTC(),
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusOK, accessResponse{
|
||||
Guest: guest,
|
||||
Event: event,
|
||||
Token: tk,
|
||||
AccessLog: accessLogID,
|
||||
})
|
||||
}
|
||||
|
||||
func collectFingerprint(r *http.Request) map[string]any {
|
||||
fp := map[string]any{
|
||||
"user_agent": r.UserAgent(),
|
||||
"accept_language": r.Header.Get("Accept-Language"),
|
||||
"accept_encoding": r.Header.Get("Accept-Encoding"),
|
||||
}
|
||||
if v := r.Header.Get("Sec-CH-UA-Platform"); v != "" {
|
||||
fp["platform"] = v
|
||||
}
|
||||
if v := r.Header.Get("X-Device-Fingerprint"); v != "" {
|
||||
fp["client_fingerprint"] = v
|
||||
}
|
||||
return fp
|
||||
}
|
||||
|
||||
func clientIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
if i := strings.IndexByte(xff, ','); i > 0 {
|
||||
return strings.TrimSpace(xff[:i])
|
||||
}
|
||||
return strings.TrimSpace(xff)
|
||||
}
|
||||
if xr := r.Header.Get("X-Real-IP"); xr != "" {
|
||||
return strings.TrimSpace(xr)
|
||||
}
|
||||
host := r.RemoteAddr
|
||||
if i := strings.LastIndexByte(host, ':'); i > 0 {
|
||||
host = host[:i]
|
||||
}
|
||||
return host
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
type userHandler struct {
|
||||
repo *storage.UserRepo
|
||||
}
|
||||
|
||||
type upsertUserRequest struct {
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// POST /users — idempotent: returns the existing user if the email already
|
||||
// exists, creates one otherwise. This keeps the demo flow simple without
|
||||
// requiring real auth.
|
||||
func (h *userHandler) upsert(w http.ResponseWriter, r *http.Request) {
|
||||
var req upsertUserRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
if _, err := mail.ParseAddress(req.Email); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "email is invalid")
|
||||
return
|
||||
}
|
||||
if req.Name == "" {
|
||||
writeError(w, http.StatusBadRequest, "name is required")
|
||||
return
|
||||
}
|
||||
|
||||
u, err := h.repo.Create(r.Context(), req.Email, req.Name)
|
||||
if err == nil {
|
||||
writeJSON(w, http.StatusCreated, u)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, domain.ErrEmailTaken) {
|
||||
existing, getErr := h.repo.GetByEmail(r.Context(), req.Email)
|
||||
if getErr != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load user")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, existing)
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to create user")
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// WSEvent is the envelope pushed over WebSocket to dashboard clients.
|
||||
type WSEvent struct {
|
||||
Type string `json:"type"`
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
type subscriber struct {
|
||||
conn *websocket.Conn
|
||||
send chan []byte
|
||||
closed chan struct{}
|
||||
}
|
||||
|
||||
// Hub fans out per-event WebSocket events to subscribers. Connections are
|
||||
// keyed by event_id; a single dashboard page subscribes to one event at a
|
||||
// time. Backpressure: if a slow client falls behind, we drop the message
|
||||
// for that subscriber rather than block the broadcaster.
|
||||
type Hub struct {
|
||||
logger *slog.Logger
|
||||
mu sync.RWMutex
|
||||
subs map[uuid.UUID]map[*subscriber]struct{}
|
||||
}
|
||||
|
||||
func NewHub(logger *slog.Logger) *Hub {
|
||||
return &Hub{
|
||||
logger: logger,
|
||||
subs: make(map[uuid.UUID]map[*subscriber]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Broadcast publishes evt to all subscribers of evt.EventID.
|
||||
func (h *Hub) Broadcast(evt WSEvent) {
|
||||
if evt.Timestamp.IsZero() {
|
||||
evt.Timestamp = time.Now().UTC()
|
||||
}
|
||||
body, err := json.Marshal(evt)
|
||||
if err != nil {
|
||||
h.logger.Error("ws marshal", "err", err)
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
|
||||
for s := range h.subs[evt.EventID] {
|
||||
select {
|
||||
case s.send <- body:
|
||||
default:
|
||||
// drop on slow client; the connection will be closed when its
|
||||
// reader goroutine notices the closed channel.
|
||||
h.logger.Warn("ws subscriber slow, dropping message", "event_id", evt.EventID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) add(eventID uuid.UUID, s *subscriber) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.subs[eventID] == nil {
|
||||
h.subs[eventID] = make(map[*subscriber]struct{})
|
||||
}
|
||||
h.subs[eventID][s] = struct{}{}
|
||||
}
|
||||
|
||||
func (h *Hub) remove(eventID uuid.UUID, s *subscriber) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if subs, ok := h.subs[eventID]; ok {
|
||||
delete(subs, s)
|
||||
if len(subs) == 0 {
|
||||
delete(h.subs, eventID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type wsHandler struct {
|
||||
logger *slog.Logger
|
||||
hub *Hub
|
||||
}
|
||||
|
||||
// GET /ws/events/{id} — dashboard live feed for one event.
|
||||
func (h *wsHandler) handle(w http.ResponseWriter, r *http.Request) {
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
|
||||
// In dev the frontend runs on a different origin (localhost:3000 → localhost:8080).
|
||||
// We're not relying on cookies, so it's safe to skip the same-origin check.
|
||||
InsecureSkipVerify: true,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Warn("ws accept", "err", err)
|
||||
return
|
||||
}
|
||||
|
||||
sub := &subscriber{
|
||||
conn: conn,
|
||||
send: make(chan []byte, 32),
|
||||
closed: make(chan struct{}),
|
||||
}
|
||||
h.hub.add(eventID, sub)
|
||||
defer h.hub.remove(eventID, sub)
|
||||
|
||||
ctx := conn.CloseRead(r.Context())
|
||||
|
||||
pingTicker := time.NewTicker(20 * time.Second)
|
||||
defer pingTicker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
conn.Close(websocket.StatusNormalClosure, "")
|
||||
return
|
||||
case msg := <-sub.send:
|
||||
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err := conn.Write(writeCtx, websocket.MessageText, msg)
|
||||
cancel()
|
||||
if err != nil {
|
||||
conn.Close(websocket.StatusInternalError, "write failed")
|
||||
return
|
||||
}
|
||||
case <-pingTicker.C:
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err := conn.Ping(pingCtx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const tokenPrefix = "tk_"
|
||||
|
||||
var ErrInvalidTokenFormat = errors.New("invalid token format")
|
||||
|
||||
type Generator struct{}
|
||||
|
||||
func NewGenerator() *Generator {
|
||||
return &Generator{}
|
||||
}
|
||||
|
||||
func (Generator) Generate() (raw, hash string, err error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
raw = tokenPrefix + base64.RawURLEncoding.EncodeToString(buf)
|
||||
hash = HashToken(raw)
|
||||
return raw, hash, nil
|
||||
}
|
||||
|
||||
func HashToken(raw string) string {
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func ValidateFormat(raw string) error {
|
||||
if !strings.HasPrefix(raw, tokenPrefix) {
|
||||
return ErrInvalidTokenFormat
|
||||
}
|
||||
if len(raw) < len(tokenPrefix)+20 {
|
||||
return ErrInvalidTokenFormat
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerate_ProducesDistinctTokens(t *testing.T) {
|
||||
g := NewGenerator()
|
||||
seen := make(map[string]struct{})
|
||||
for i := 0; i < 100; i++ {
|
||||
raw, hash, err := g.Generate()
|
||||
if err != nil {
|
||||
t.Fatalf("generate: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(raw, "tk_") {
|
||||
t.Errorf("expected tk_ prefix, got %q", raw)
|
||||
}
|
||||
if len(hash) != 64 {
|
||||
t.Errorf("expected 64-char hex hash, got %d", len(hash))
|
||||
}
|
||||
if _, dup := seen[raw]; dup {
|
||||
t.Fatal("duplicate token generated")
|
||||
}
|
||||
seen[raw] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashToken_Stable(t *testing.T) {
|
||||
if HashToken("tk_abc") != HashToken("tk_abc") {
|
||||
t.Fatal("expected deterministic hash")
|
||||
}
|
||||
if HashToken("tk_abc") == HashToken("tk_xyz") {
|
||||
t.Fatal("expected distinct hashes for distinct inputs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateFormat(t *testing.T) {
|
||||
if err := ValidateFormat("tk_" + strings.Repeat("a", 40)); err != nil {
|
||||
t.Errorf("expected valid, got %v", err)
|
||||
}
|
||||
if err := ValidateFormat("not-a-token"); err == nil {
|
||||
t.Error("expected error for missing prefix")
|
||||
}
|
||||
if err := ValidateFormat("tk_short"); err == nil {
|
||||
t.Error("expected error for too-short token")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Env string
|
||||
HTTPAddr string
|
||||
DatabaseURL string
|
||||
NATSURL string
|
||||
FraudGRPCAddr string
|
||||
FraudGRPCTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
TokenSecret string
|
||||
TokenTTL time.Duration
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
cfg := &Config{
|
||||
Env: getenv("GG_ENV", "development"),
|
||||
HTTPAddr: getenv("GG_HTTP_ADDR", ":8080"),
|
||||
DatabaseURL: getenv("GG_DATABASE_URL", "postgres://guestguard:guestguard@localhost:5432/guestguard?sslmode=disable"),
|
||||
NATSURL: getenv("GG_NATS_URL", "nats://localhost:4222"),
|
||||
FraudGRPCAddr: getenv("GG_FRAUD_GRPC_ADDR", "fraud-engine:9091"),
|
||||
FraudGRPCTimeout: getenvDuration("GG_FRAUD_GRPC_TIMEOUT", 250*time.Millisecond),
|
||||
ShutdownTimeout: getenvDuration("GG_SHUTDOWN_TIMEOUT", 15*time.Second),
|
||||
TokenSecret: os.Getenv("GG_TOKEN_SECRET"),
|
||||
TokenTTL: getenvDuration("GG_TOKEN_TTL", 30*24*time.Hour),
|
||||
}
|
||||
|
||||
if cfg.Env == "production" && cfg.TokenSecret == "" {
|
||||
return nil, fmt.Errorf("GG_TOKEN_SECRET is required in production")
|
||||
}
|
||||
if cfg.TokenSecret == "" {
|
||||
cfg.TokenSecret = "dev-only-insecure-secret-change-me"
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getenvDuration(key string, fallback time.Duration) time.Duration {
|
||||
v, ok := os.LookupEnv(key)
|
||||
if !ok || v == "" {
|
||||
return fallback
|
||||
}
|
||||
if d, err := time.ParseDuration(v); err == nil {
|
||||
return d
|
||||
}
|
||||
if secs, err := strconv.Atoi(v); err == nil {
|
||||
return time.Duration(secs) * time.Second
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type EventStatus string
|
||||
|
||||
const (
|
||||
EventStatusDraft EventStatus = "draft"
|
||||
EventStatusPublished EventStatus = "published"
|
||||
EventStatusClosed EventStatus = "closed"
|
||||
EventStatusArchived EventStatus = "archived"
|
||||
)
|
||||
|
||||
func (s EventStatus) Valid() bool {
|
||||
switch s {
|
||||
case EventStatusDraft, EventStatusPublished, EventStatusClosed, EventStatusArchived:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
HostID uuid.UUID `json:"host_id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
EventDate time.Time `json:"event_date"`
|
||||
Venue string `json:"venue"`
|
||||
MaxCapacity int `json:"max_capacity"`
|
||||
Settings map[string]any `json:"settings"`
|
||||
Status EventStatus `json:"status"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
var (
|
||||
ErrEventNotFound = errors.New("event not found")
|
||||
ErrSlugTaken = errors.New("slug already in use")
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
package domain
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEventStatus_Valid(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in EventStatus
|
||||
want bool
|
||||
}{
|
||||
{"draft", EventStatusDraft, true},
|
||||
{"published", EventStatusPublished, true},
|
||||
{"closed", EventStatusClosed, true},
|
||||
{"archived", EventStatusArchived, true},
|
||||
{"empty", "", false},
|
||||
{"unknown", "running", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tt.in.Valid(); got != tt.want {
|
||||
t.Errorf("Valid() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Guest struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
Name string `json:"name"`
|
||||
Email *string `json:"email,omitempty"`
|
||||
Phone *string `json:"phone,omitempty"`
|
||||
PlusOnes int `json:"plus_ones"`
|
||||
DietaryNotes *string `json:"dietary_notes,omitempty"`
|
||||
TableNumber *int `json:"table_number,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
var ErrGuestNotFound = errors.New("guest not found")
|
||||
@@ -0,0 +1,41 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type RSVPResponse string
|
||||
|
||||
const (
|
||||
RSVPAttending RSVPResponse = "attending"
|
||||
RSVPDeclined RSVPResponse = "declined"
|
||||
RSVPMaybe RSVPResponse = "maybe"
|
||||
)
|
||||
|
||||
func (r RSVPResponse) Valid() bool {
|
||||
switch r {
|
||||
case RSVPAttending, RSVPDeclined, RSVPMaybe:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type RSVP struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GuestID uuid.UUID `json:"guest_id"`
|
||||
Response RSVPResponse `json:"response"`
|
||||
PlusOnes int `json:"plus_ones"`
|
||||
DietaryNotes *string `json:"dietary_notes,omitempty"`
|
||||
SubmittedAt time.Time `json:"submitted_at"`
|
||||
DeviceFingerprint map[string]any `json:"device_fingerprint,omitempty"`
|
||||
IPAddress *string `json:"ip_address,omitempty"`
|
||||
RiskScore *int `json:"risk_score,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
ErrRSVPAlreadySubmitted = errors.New("rsvp already submitted")
|
||||
ErrRSVPBlocked = errors.New("rsvp blocked due to fraud risk")
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type TokenStatus string
|
||||
|
||||
const (
|
||||
TokenStatusActive TokenStatus = "active"
|
||||
TokenStatusUsed TokenStatus = "used"
|
||||
TokenStatusRevoked TokenStatus = "revoked"
|
||||
TokenStatusExpired TokenStatus = "expired"
|
||||
)
|
||||
|
||||
type Token struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
GuestID uuid.UUID `json:"guest_id"`
|
||||
TokenHash string `json:"-"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Status TokenStatus `json:"status"`
|
||||
UsedAt *time.Time `json:"used_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (t *Token) IsValid(now time.Time) error {
|
||||
switch t.Status {
|
||||
case TokenStatusUsed:
|
||||
return ErrTokenAlreadyUsed
|
||||
case TokenStatusRevoked:
|
||||
return ErrTokenRevoked
|
||||
case TokenStatusExpired:
|
||||
return ErrTokenExpired
|
||||
}
|
||||
if now.After(t.ExpiresAt) {
|
||||
return ErrTokenExpired
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
ErrTokenNotFound = errors.New("token not found")
|
||||
ErrTokenExpired = errors.New("token expired")
|
||||
ErrTokenRevoked = errors.New("token revoked")
|
||||
ErrTokenAlreadyUsed = errors.New("token already used")
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
var (
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrEmailTaken = errors.New("email already in use")
|
||||
)
|
||||
@@ -0,0 +1,136 @@
|
||||
package fraud
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/alchemistkay/guestguard/internal/fraudpb"
|
||||
)
|
||||
|
||||
type Decision struct {
|
||||
Score int `json:"score"`
|
||||
Risk string `json:"risk"`
|
||||
Reasons []string `json:"reasons"`
|
||||
Used bool `json:"used"` // false means we returned the fallback (engine unavailable / timed out)
|
||||
}
|
||||
|
||||
type ScoreInput struct {
|
||||
EventID uuid.UUID
|
||||
GuestID uuid.UUID
|
||||
TokenID uuid.UUID
|
||||
AccessLogID uuid.UUID
|
||||
Fingerprint map[string]string
|
||||
IPAddress string
|
||||
UserAgent string
|
||||
Referrer string
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
conn *grpc.ClientConn
|
||||
stub pb.FraudServiceClient
|
||||
timeout time.Duration
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func Dial(ctx context.Context, addr string, timeout time.Duration, logger *slog.Logger) (*Client, error) {
|
||||
if addr == "" {
|
||||
return nil, errors.New("fraud grpc addr is empty")
|
||||
}
|
||||
|
||||
conn, err := grpc.NewClient(addr,
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dial fraud grpc: %w", err)
|
||||
}
|
||||
|
||||
return &Client{
|
||||
conn: conn,
|
||||
stub: pb.NewFraudServiceClient(conn),
|
||||
timeout: timeout,
|
||||
logger: logger,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Close() error {
|
||||
if c.conn == nil {
|
||||
return nil
|
||||
}
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
// Score is a synchronous fraud check. If the engine is unreachable or slow,
|
||||
// it returns a permissive fallback (Used=false) so the API stays available.
|
||||
// The caller can still decide what to do with that signal.
|
||||
func (c *Client) Score(ctx context.Context, in ScoreInput) Decision {
|
||||
callCtx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := c.stub.Score(callCtx, &pb.ScoreRequest{
|
||||
EventId: in.EventID.String(),
|
||||
GuestId: in.GuestID.String(),
|
||||
TokenId: in.TokenID.String(),
|
||||
AccessLogId: in.AccessLogID.String(),
|
||||
Fingerprint: in.Fingerprint,
|
||||
IpAddress: in.IPAddress,
|
||||
UserAgent: in.UserAgent,
|
||||
Referrer: in.Referrer,
|
||||
})
|
||||
if err != nil {
|
||||
c.logger.Warn("fraud sync score failed, falling back",
|
||||
"err", err,
|
||||
"code", status.Code(err),
|
||||
"guest_id", in.GuestID,
|
||||
)
|
||||
return Decision{Score: 0, Risk: "low", Reasons: []string{"fraud_engine_unavailable"}, Used: false}
|
||||
}
|
||||
|
||||
return Decision{
|
||||
Score: int(resp.Score),
|
||||
Risk: riskString(resp.Risk),
|
||||
Reasons: append([]string{}, resp.Reasons...),
|
||||
Used: true,
|
||||
}
|
||||
}
|
||||
|
||||
func riskString(r pb.Risk) string {
|
||||
switch r {
|
||||
case pb.Risk_RISK_LOW:
|
||||
return "low"
|
||||
case pb.Risk_RISK_MEDIUM:
|
||||
return "medium"
|
||||
case pb.Risk_RISK_HIGH:
|
||||
return "high"
|
||||
case pb.Risk_RISK_BLOCK:
|
||||
return "block"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// IsBlock is a small helper so callers don't depend on the string contract.
|
||||
func IsBlock(d Decision) bool {
|
||||
return d.Risk == "block"
|
||||
}
|
||||
|
||||
// IsRetryableErr distinguishes transient gRPC errors. Currently unused but
|
||||
// kept for future retry middleware.
|
||||
func IsRetryableErr(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.Unavailable, codes.DeadlineExceeded, codes.ResourceExhausted:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.34.2
|
||||
// protoc v6.31.1
|
||||
// source: fraud/v1/fraud.proto
|
||||
|
||||
package fraudpb
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Risk int32
|
||||
|
||||
const (
|
||||
Risk_RISK_UNSPECIFIED Risk = 0
|
||||
Risk_RISK_LOW Risk = 1
|
||||
Risk_RISK_MEDIUM Risk = 2
|
||||
Risk_RISK_HIGH Risk = 3
|
||||
Risk_RISK_BLOCK Risk = 4
|
||||
)
|
||||
|
||||
// Enum value maps for Risk.
|
||||
var (
|
||||
Risk_name = map[int32]string{
|
||||
0: "RISK_UNSPECIFIED",
|
||||
1: "RISK_LOW",
|
||||
2: "RISK_MEDIUM",
|
||||
3: "RISK_HIGH",
|
||||
4: "RISK_BLOCK",
|
||||
}
|
||||
Risk_value = map[string]int32{
|
||||
"RISK_UNSPECIFIED": 0,
|
||||
"RISK_LOW": 1,
|
||||
"RISK_MEDIUM": 2,
|
||||
"RISK_HIGH": 3,
|
||||
"RISK_BLOCK": 4,
|
||||
}
|
||||
)
|
||||
|
||||
func (x Risk) Enum() *Risk {
|
||||
p := new(Risk)
|
||||
*p = x
|
||||
return p
|
||||
}
|
||||
|
||||
func (x Risk) String() string {
|
||||
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
|
||||
}
|
||||
|
||||
func (Risk) Descriptor() protoreflect.EnumDescriptor {
|
||||
return file_fraud_v1_fraud_proto_enumTypes[0].Descriptor()
|
||||
}
|
||||
|
||||
func (Risk) Type() protoreflect.EnumType {
|
||||
return &file_fraud_v1_fraud_proto_enumTypes[0]
|
||||
}
|
||||
|
||||
func (x Risk) Number() protoreflect.EnumNumber {
|
||||
return protoreflect.EnumNumber(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Risk.Descriptor instead.
|
||||
func (Risk) EnumDescriptor() ([]byte, []int) {
|
||||
return file_fraud_v1_fraud_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
type ScoreRequest struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
EventId string `protobuf:"bytes,1,opt,name=event_id,json=eventId,proto3" json:"event_id,omitempty"`
|
||||
GuestId string `protobuf:"bytes,2,opt,name=guest_id,json=guestId,proto3" json:"guest_id,omitempty"`
|
||||
TokenId string `protobuf:"bytes,3,opt,name=token_id,json=tokenId,proto3" json:"token_id,omitempty"`
|
||||
AccessLogId string `protobuf:"bytes,4,opt,name=access_log_id,json=accessLogId,proto3" json:"access_log_id,omitempty"`
|
||||
Fingerprint map[string]string `protobuf:"bytes,5,rep,name=fingerprint,proto3" json:"fingerprint,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
IpAddress string `protobuf:"bytes,6,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"`
|
||||
UserAgent string `protobuf:"bytes,7,opt,name=user_agent,json=userAgent,proto3" json:"user_agent,omitempty"`
|
||||
Referrer string `protobuf:"bytes,8,opt,name=referrer,proto3" json:"referrer,omitempty"`
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) Reset() {
|
||||
*x = ScoreRequest{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_fraud_v1_fraud_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ScoreRequest) ProtoMessage() {}
|
||||
|
||||
func (x *ScoreRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_fraud_v1_fraud_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ScoreRequest.ProtoReflect.Descriptor instead.
|
||||
func (*ScoreRequest) Descriptor() ([]byte, []int) {
|
||||
return file_fraud_v1_fraud_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) GetEventId() string {
|
||||
if x != nil {
|
||||
return x.EventId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) GetGuestId() string {
|
||||
if x != nil {
|
||||
return x.GuestId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) GetTokenId() string {
|
||||
if x != nil {
|
||||
return x.TokenId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) GetAccessLogId() string {
|
||||
if x != nil {
|
||||
return x.AccessLogId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) GetFingerprint() map[string]string {
|
||||
if x != nil {
|
||||
return x.Fingerprint
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) GetIpAddress() string {
|
||||
if x != nil {
|
||||
return x.IpAddress
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) GetUserAgent() string {
|
||||
if x != nil {
|
||||
return x.UserAgent
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ScoreRequest) GetReferrer() string {
|
||||
if x != nil {
|
||||
return x.Referrer
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type ScoreResponse struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Score int32 `protobuf:"varint,1,opt,name=score,proto3" json:"score,omitempty"`
|
||||
Risk Risk `protobuf:"varint,2,opt,name=risk,proto3,enum=guestguard.fraud.v1.Risk" json:"risk,omitempty"`
|
||||
Reasons []string `protobuf:"bytes,3,rep,name=reasons,proto3" json:"reasons,omitempty"`
|
||||
}
|
||||
|
||||
func (x *ScoreResponse) Reset() {
|
||||
*x = ScoreResponse{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_fraud_v1_fraud_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *ScoreResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ScoreResponse) ProtoMessage() {}
|
||||
|
||||
func (x *ScoreResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_fraud_v1_fraud_proto_msgTypes[1]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ScoreResponse.ProtoReflect.Descriptor instead.
|
||||
func (*ScoreResponse) Descriptor() ([]byte, []int) {
|
||||
return file_fraud_v1_fraud_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *ScoreResponse) GetScore() int32 {
|
||||
if x != nil {
|
||||
return x.Score
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *ScoreResponse) GetRisk() Risk {
|
||||
if x != nil {
|
||||
return x.Risk
|
||||
}
|
||||
return Risk_RISK_UNSPECIFIED
|
||||
}
|
||||
|
||||
func (x *ScoreResponse) GetReasons() []string {
|
||||
if x != nil {
|
||||
return x.Reasons
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_fraud_v1_fraud_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_fraud_v1_fraud_proto_rawDesc = []byte{
|
||||
0x0a, 0x14, 0x66, 0x72, 0x61, 0x75, 0x64, 0x2f, 0x76, 0x31, 0x2f, 0x66, 0x72, 0x61, 0x75, 0x64,
|
||||
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x13, 0x67, 0x75, 0x65, 0x73, 0x74, 0x67, 0x75, 0x61,
|
||||
0x72, 0x64, 0x2e, 0x66, 0x72, 0x61, 0x75, 0x64, 0x2e, 0x76, 0x31, 0x22, 0xf3, 0x02, 0x0a, 0x0c,
|
||||
0x53, 0x63, 0x6f, 0x72, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08,
|
||||
0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07,
|
||||
0x65, 0x76, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x67, 0x75, 0x65, 0x73, 0x74,
|
||||
0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x67, 0x75, 0x65, 0x73, 0x74,
|
||||
0x49, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x03,
|
||||
0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x49, 0x64, 0x12, 0x22, 0x0a,
|
||||
0x0d, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x5f, 0x6c, 0x6f, 0x67, 0x5f, 0x69, 0x64, 0x18, 0x04,
|
||||
0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x4c, 0x6f, 0x67, 0x49,
|
||||
0x64, 0x12, 0x54, 0x0a, 0x0b, 0x66, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x70, 0x72, 0x69, 0x6e, 0x74,
|
||||
0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x32, 0x2e, 0x67, 0x75, 0x65, 0x73, 0x74, 0x67, 0x75,
|
||||
0x61, 0x72, 0x64, 0x2e, 0x66, 0x72, 0x61, 0x75, 0x64, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x63, 0x6f,
|
||||
0x72, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x46, 0x69, 0x6e, 0x67, 0x65, 0x72,
|
||||
0x70, 0x72, 0x69, 0x6e, 0x74, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0b, 0x66, 0x69, 0x6e, 0x67,
|
||||
0x65, 0x72, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x69, 0x70, 0x5f, 0x61, 0x64,
|
||||
0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x69, 0x70, 0x41,
|
||||
0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x61,
|
||||
0x67, 0x65, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x75, 0x73, 0x65, 0x72,
|
||||
0x41, 0x67, 0x65, 0x6e, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65,
|
||||
0x72, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65,
|
||||
0x72, 0x1a, 0x3e, 0x0a, 0x10, 0x46, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x70, 0x72, 0x69, 0x6e, 0x74,
|
||||
0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01,
|
||||
0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65,
|
||||
0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38,
|
||||
0x01, 0x22, 0x6e, 0x0a, 0x0d, 0x53, 0x63, 0x6f, 0x72, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
|
||||
0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28,
|
||||
0x05, 0x52, 0x05, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x12, 0x2d, 0x0a, 0x04, 0x72, 0x69, 0x73, 0x6b,
|
||||
0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x19, 0x2e, 0x67, 0x75, 0x65, 0x73, 0x74, 0x67, 0x75,
|
||||
0x61, 0x72, 0x64, 0x2e, 0x66, 0x72, 0x61, 0x75, 0x64, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x69, 0x73,
|
||||
0x6b, 0x52, 0x04, 0x72, 0x69, 0x73, 0x6b, 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x61, 0x73, 0x6f,
|
||||
0x6e, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e,
|
||||
0x73, 0x2a, 0x5a, 0x0a, 0x04, 0x52, 0x69, 0x73, 0x6b, 0x12, 0x14, 0x0a, 0x10, 0x52, 0x49, 0x53,
|
||||
0x4b, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12,
|
||||
0x0c, 0x0a, 0x08, 0x52, 0x49, 0x53, 0x4b, 0x5f, 0x4c, 0x4f, 0x57, 0x10, 0x01, 0x12, 0x0f, 0x0a,
|
||||
0x0b, 0x52, 0x49, 0x53, 0x4b, 0x5f, 0x4d, 0x45, 0x44, 0x49, 0x55, 0x4d, 0x10, 0x02, 0x12, 0x0d,
|
||||
0x0a, 0x09, 0x52, 0x49, 0x53, 0x4b, 0x5f, 0x48, 0x49, 0x47, 0x48, 0x10, 0x03, 0x12, 0x0e, 0x0a,
|
||||
0x0a, 0x52, 0x49, 0x53, 0x4b, 0x5f, 0x42, 0x4c, 0x4f, 0x43, 0x4b, 0x10, 0x04, 0x32, 0x5e, 0x0a,
|
||||
0x0c, 0x46, 0x72, 0x61, 0x75, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x4e, 0x0a,
|
||||
0x05, 0x53, 0x63, 0x6f, 0x72, 0x65, 0x12, 0x21, 0x2e, 0x67, 0x75, 0x65, 0x73, 0x74, 0x67, 0x75,
|
||||
0x61, 0x72, 0x64, 0x2e, 0x66, 0x72, 0x61, 0x75, 0x64, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x63, 0x6f,
|
||||
0x72, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x22, 0x2e, 0x67, 0x75, 0x65, 0x73,
|
||||
0x74, 0x67, 0x75, 0x61, 0x72, 0x64, 0x2e, 0x66, 0x72, 0x61, 0x75, 0x64, 0x2e, 0x76, 0x31, 0x2e,
|
||||
0x53, 0x63, 0x6f, 0x72, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x3d, 0x5a,
|
||||
0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x6c, 0x63, 0x68,
|
||||
0x65, 0x6d, 0x69, 0x73, 0x74, 0x6b, 0x61, 0x79, 0x2f, 0x67, 0x75, 0x65, 0x73, 0x74, 0x67, 0x75,
|
||||
0x61, 0x72, 0x64, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x66, 0x72, 0x61,
|
||||
0x75, 0x64, 0x70, 0x62, 0x3b, 0x66, 0x72, 0x61, 0x75, 0x64, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72,
|
||||
0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_fraud_v1_fraud_proto_rawDescOnce sync.Once
|
||||
file_fraud_v1_fraud_proto_rawDescData = file_fraud_v1_fraud_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_fraud_v1_fraud_proto_rawDescGZIP() []byte {
|
||||
file_fraud_v1_fraud_proto_rawDescOnce.Do(func() {
|
||||
file_fraud_v1_fraud_proto_rawDescData = protoimpl.X.CompressGZIP(file_fraud_v1_fraud_proto_rawDescData)
|
||||
})
|
||||
return file_fraud_v1_fraud_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_fraud_v1_fraud_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
||||
var file_fraud_v1_fraud_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
|
||||
var file_fraud_v1_fraud_proto_goTypes = []any{
|
||||
(Risk)(0), // 0: guestguard.fraud.v1.Risk
|
||||
(*ScoreRequest)(nil), // 1: guestguard.fraud.v1.ScoreRequest
|
||||
(*ScoreResponse)(nil), // 2: guestguard.fraud.v1.ScoreResponse
|
||||
nil, // 3: guestguard.fraud.v1.ScoreRequest.FingerprintEntry
|
||||
}
|
||||
var file_fraud_v1_fraud_proto_depIdxs = []int32{
|
||||
3, // 0: guestguard.fraud.v1.ScoreRequest.fingerprint:type_name -> guestguard.fraud.v1.ScoreRequest.FingerprintEntry
|
||||
0, // 1: guestguard.fraud.v1.ScoreResponse.risk:type_name -> guestguard.fraud.v1.Risk
|
||||
1, // 2: guestguard.fraud.v1.FraudService.Score:input_type -> guestguard.fraud.v1.ScoreRequest
|
||||
2, // 3: guestguard.fraud.v1.FraudService.Score:output_type -> guestguard.fraud.v1.ScoreResponse
|
||||
3, // [3:4] is the sub-list for method output_type
|
||||
2, // [2:3] is the sub-list for method input_type
|
||||
2, // [2:2] is the sub-list for extension type_name
|
||||
2, // [2:2] is the sub-list for extension extendee
|
||||
0, // [0:2] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_fraud_v1_fraud_proto_init() }
|
||||
func file_fraud_v1_fraud_proto_init() {
|
||||
if File_fraud_v1_fraud_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_fraud_v1_fraud_proto_msgTypes[0].Exporter = func(v any, i int) any {
|
||||
switch v := v.(*ScoreRequest); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_fraud_v1_fraud_proto_msgTypes[1].Exporter = func(v any, i int) any {
|
||||
switch v := v.(*ScoreResponse); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_fraud_v1_fraud_proto_rawDesc,
|
||||
NumEnums: 1,
|
||||
NumMessages: 3,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_fraud_v1_fraud_proto_goTypes,
|
||||
DependencyIndexes: file_fraud_v1_fraud_proto_depIdxs,
|
||||
EnumInfos: file_fraud_v1_fraud_proto_enumTypes,
|
||||
MessageInfos: file_fraud_v1_fraud_proto_msgTypes,
|
||||
}.Build()
|
||||
File_fraud_v1_fraud_proto = out.File
|
||||
file_fraud_v1_fraud_proto_rawDesc = nil
|
||||
file_fraud_v1_fraud_proto_goTypes = nil
|
||||
file_fraud_v1_fraud_proto_depIdxs = nil
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.31.1
|
||||
// source: fraud/v1/fraud.proto
|
||||
|
||||
package fraudpb
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
FraudService_Score_FullMethodName = "/guestguard.fraud.v1.FraudService/Score"
|
||||
)
|
||||
|
||||
// FraudServiceClient is the client API for FraudService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type FraudServiceClient interface {
|
||||
Score(ctx context.Context, in *ScoreRequest, opts ...grpc.CallOption) (*ScoreResponse, error)
|
||||
}
|
||||
|
||||
type fraudServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewFraudServiceClient(cc grpc.ClientConnInterface) FraudServiceClient {
|
||||
return &fraudServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *fraudServiceClient) Score(ctx context.Context, in *ScoreRequest, opts ...grpc.CallOption) (*ScoreResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ScoreResponse)
|
||||
err := c.cc.Invoke(ctx, FraudService_Score_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// FraudServiceServer is the server API for FraudService service.
|
||||
// All implementations must embed UnimplementedFraudServiceServer
|
||||
// for forward compatibility.
|
||||
type FraudServiceServer interface {
|
||||
Score(context.Context, *ScoreRequest) (*ScoreResponse, error)
|
||||
mustEmbedUnimplementedFraudServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedFraudServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedFraudServiceServer struct{}
|
||||
|
||||
func (UnimplementedFraudServiceServer) Score(context.Context, *ScoreRequest) (*ScoreResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Score not implemented")
|
||||
}
|
||||
func (UnimplementedFraudServiceServer) mustEmbedUnimplementedFraudServiceServer() {}
|
||||
func (UnimplementedFraudServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeFraudServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to FraudServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeFraudServiceServer interface {
|
||||
mustEmbedUnimplementedFraudServiceServer()
|
||||
}
|
||||
|
||||
func RegisterFraudServiceServer(s grpc.ServiceRegistrar, srv FraudServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedFraudServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&FraudService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _FraudService_Score_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ScoreRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(FraudServiceServer).Score(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: FraudService_Score_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(FraudServiceServer).Score(ctx, req.(*ScoreRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// FraudService_ServiceDesc is the grpc.ServiceDesc for FraudService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var FraudService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "guestguard.fraud.v1.FraudService",
|
||||
HandlerType: (*FraudServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Score",
|
||||
Handler: _FraudService_Score_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "fraud/v1/fraud.proto",
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package natspub
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
conn *nats.Conn
|
||||
js jetstream.JetStream
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, url string, logger *slog.Logger) (*Client, error) {
|
||||
conn, err := nats.Connect(url,
|
||||
nats.Name("guestguard-api"),
|
||||
nats.MaxReconnects(-1),
|
||||
nats.ReconnectWait(2*time.Second),
|
||||
nats.DisconnectErrHandler(func(_ *nats.Conn, err error) {
|
||||
if err != nil {
|
||||
logger.Warn("nats disconnected", "err", err)
|
||||
}
|
||||
}),
|
||||
nats.ReconnectHandler(func(c *nats.Conn) {
|
||||
logger.Info("nats reconnected", "url", c.ConnectedUrl())
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect nats: %w", err)
|
||||
}
|
||||
|
||||
js, err := jetstream.New(conn)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("jetstream: %w", err)
|
||||
}
|
||||
|
||||
c := &Client{conn: conn, js: js, logger: logger}
|
||||
if err := c.ensureStream(ctx); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *Client) ensureStream(ctx context.Context) error {
|
||||
cfg := jetstream.StreamConfig{
|
||||
Name: StreamName,
|
||||
Subjects: StreamSubjects(),
|
||||
Retention: jetstream.LimitsPolicy,
|
||||
Storage: jetstream.FileStorage,
|
||||
MaxAge: 14 * 24 * time.Hour,
|
||||
Replicas: 1,
|
||||
}
|
||||
|
||||
_, err := c.js.CreateOrUpdateStream(ctx, cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create stream %s: %w", StreamName, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
if c.conn != nil {
|
||||
c.conn.Drain() //nolint:errcheck
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) JetStream() jetstream.JetStream {
|
||||
return c.js
|
||||
}
|
||||
|
||||
func (c *Client) PublishAccessAttempted(ctx context.Context, evt AccessAttempted) error {
|
||||
if evt.OccurredAt.IsZero() {
|
||||
evt.OccurredAt = time.Now().UTC()
|
||||
}
|
||||
return c.publishJSON(ctx, SubjectAccessAttempted, evt, evt.GuestID)
|
||||
}
|
||||
|
||||
func (c *Client) PublishRSVPConfirmed(ctx context.Context, evt RSVPConfirmed) error {
|
||||
if evt.SubmittedAt.IsZero() {
|
||||
evt.SubmittedAt = time.Now().UTC()
|
||||
}
|
||||
return c.publishJSON(ctx, SubjectRSVPConfirmed, evt, evt.RSVPID)
|
||||
}
|
||||
|
||||
func (c *Client) publishJSON(ctx context.Context, subject string, payload any, dedupeKey uuid.UUID) error {
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal %s: %w", subject, err)
|
||||
}
|
||||
|
||||
msg := &nats.Msg{Subject: subject, Data: body}
|
||||
msg.Header = nats.Header{}
|
||||
msg.Header.Set("Content-Type", "application/json")
|
||||
if dedupeKey != uuid.Nil {
|
||||
msg.Header.Set("Nats-Msg-Id", subject+":"+dedupeKey.String()+":"+time.Now().UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
|
||||
pubCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err = c.js.PublishMsg(pubCtx, msg)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return fmt.Errorf("publish %s timed out: %w", subject, err)
|
||||
}
|
||||
return fmt.Errorf("publish %s: %w", subject, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package natspub
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type AccessAttempted struct {
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
GuestID uuid.UUID `json:"guest_id"`
|
||||
TokenID uuid.UUID `json:"token_id"`
|
||||
AccessLogID uuid.UUID `json:"access_log_id"`
|
||||
Fingerprint map[string]any `json:"fingerprint,omitempty"`
|
||||
IPAddress string `json:"ip_address,omitempty"`
|
||||
UserAgent string `json:"user_agent,omitempty"`
|
||||
Referrer string `json:"referrer,omitempty"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
}
|
||||
|
||||
type FraudScored struct {
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
GuestID uuid.UUID `json:"guest_id"`
|
||||
TokenID uuid.UUID `json:"token_id"`
|
||||
AccessLogID uuid.UUID `json:"access_log_id"`
|
||||
Score int `json:"score"`
|
||||
Risk string `json:"risk"`
|
||||
Reasons []string `json:"reasons"`
|
||||
ScoredAt time.Time `json:"scored_at"`
|
||||
}
|
||||
|
||||
type RSVPConfirmed struct {
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
GuestID uuid.UUID `json:"guest_id"`
|
||||
RSVPID uuid.UUID `json:"rsvp_id"`
|
||||
Response string `json:"response"`
|
||||
PlusOnes int `json:"plus_ones"`
|
||||
RiskScore *int `json:"risk_score,omitempty"`
|
||||
SubmittedAt time.Time `json:"submitted_at"`
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package natspub
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
)
|
||||
|
||||
type RSVPConfirmedHandler func(ctx context.Context, evt RSVPConfirmed) error
|
||||
|
||||
type RSVPConfirmedSubscriber struct {
|
||||
logger *slog.Logger
|
||||
consumer jetstream.Consumer
|
||||
handler RSVPConfirmedHandler
|
||||
}
|
||||
|
||||
func NewRSVPConfirmedSubscriber(
|
||||
ctx context.Context,
|
||||
c *Client,
|
||||
durable string,
|
||||
handler RSVPConfirmedHandler,
|
||||
logger *slog.Logger,
|
||||
) (*RSVPConfirmedSubscriber, error) {
|
||||
cons, err := c.js.CreateOrUpdateConsumer(ctx, StreamName, jetstream.ConsumerConfig{
|
||||
Durable: durable,
|
||||
Name: durable,
|
||||
FilterSubject: SubjectRSVPConfirmed,
|
||||
AckPolicy: jetstream.AckExplicitPolicy,
|
||||
DeliverPolicy: jetstream.DeliverAllPolicy,
|
||||
MaxDeliver: 5,
|
||||
AckWait: 30 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create consumer %s: %w", durable, err)
|
||||
}
|
||||
return &RSVPConfirmedSubscriber{logger: logger, consumer: cons, handler: handler}, nil
|
||||
}
|
||||
|
||||
func (s *RSVPConfirmedSubscriber) Start(ctx context.Context) (jetstream.ConsumeContext, error) {
|
||||
cc, err := s.consumer.Consume(func(msg jetstream.Msg) {
|
||||
var evt RSVPConfirmed
|
||||
if err := json.Unmarshal(msg.Data(), &evt); err != nil {
|
||||
s.logger.Error("decode rsvp.confirmed", "err", err)
|
||||
_ = msg.Term()
|
||||
return
|
||||
}
|
||||
hctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
if err := s.handler(hctx, evt); err != nil {
|
||||
s.logger.Error("handle rsvp.confirmed", "err", err)
|
||||
_ = msg.NakWithDelay(2 * time.Second)
|
||||
return
|
||||
}
|
||||
_ = msg.Ack()
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("consume: %w", err)
|
||||
}
|
||||
return cc, nil
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package natspub
|
||||
|
||||
const (
|
||||
StreamName = "GUESTGUARD"
|
||||
|
||||
SubjectAccessAttempted = "guest.access.attempted"
|
||||
SubjectFraudScored = "fraud.scored"
|
||||
SubjectRSVPConfirmed = "rsvp.confirmed"
|
||||
SubjectInvitationSend = "invitation.send"
|
||||
)
|
||||
|
||||
func StreamSubjects() []string {
|
||||
return []string{
|
||||
"guest.>",
|
||||
"fraud.>",
|
||||
"rsvp.>",
|
||||
"invitation.>",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package natspub
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
)
|
||||
|
||||
type FraudScoredHandler func(ctx context.Context, evt FraudScored) error
|
||||
|
||||
type FraudScoredSubscriber struct {
|
||||
logger *slog.Logger
|
||||
consumer jetstream.Consumer
|
||||
handler FraudScoredHandler
|
||||
}
|
||||
|
||||
func NewFraudScoredSubscriber(
|
||||
ctx context.Context,
|
||||
c *Client,
|
||||
durable string,
|
||||
handler FraudScoredHandler,
|
||||
logger *slog.Logger,
|
||||
) (*FraudScoredSubscriber, error) {
|
||||
cons, err := c.js.CreateOrUpdateConsumer(ctx, StreamName, jetstream.ConsumerConfig{
|
||||
Durable: durable,
|
||||
Name: durable,
|
||||
FilterSubject: SubjectFraudScored,
|
||||
AckPolicy: jetstream.AckExplicitPolicy,
|
||||
DeliverPolicy: jetstream.DeliverAllPolicy,
|
||||
MaxDeliver: 5,
|
||||
AckWait: 30 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create consumer %s: %w", durable, err)
|
||||
}
|
||||
|
||||
return &FraudScoredSubscriber{
|
||||
logger: logger,
|
||||
consumer: cons,
|
||||
handler: handler,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *FraudScoredSubscriber) Start(ctx context.Context) (jetstream.ConsumeContext, error) {
|
||||
cc, err := s.consumer.Consume(func(msg jetstream.Msg) {
|
||||
var evt FraudScored
|
||||
if err := json.Unmarshal(msg.Data(), &evt); err != nil {
|
||||
s.logger.Error("decode fraud.scored", "err", err)
|
||||
_ = msg.Term()
|
||||
return
|
||||
}
|
||||
|
||||
hctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := s.handler(hctx, evt); err != nil {
|
||||
s.logger.Error("handle fraud.scored",
|
||||
"err", err, "guest_id", evt.GuestID, "score", evt.Score)
|
||||
_ = msg.NakWithDelay(2 * time.Second)
|
||||
return
|
||||
}
|
||||
_ = msg.Ack()
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("consume: %w", err)
|
||||
}
|
||||
return cc, nil
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
type Channel string
|
||||
|
||||
const (
|
||||
ChannelSMS Channel = "sms"
|
||||
ChannelEmail Channel = "email"
|
||||
)
|
||||
|
||||
type Type string
|
||||
|
||||
const (
|
||||
TypeInvitation Type = "invitation"
|
||||
TypeVerification Type = "verification"
|
||||
TypeConfirmation Type = "confirmation"
|
||||
TypeReminder Type = "reminder"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusQueued Status = "queued"
|
||||
StatusSent Status = "sent"
|
||||
StatusDelivered Status = "delivered"
|
||||
StatusFailed Status = "failed"
|
||||
)
|
||||
|
||||
// Sender is the boundary between the worker and a real provider (Twilio,
|
||||
// SES, etc). Phase 3 ships a logging implementation; later phases swap it
|
||||
// out without touching consumer code.
|
||||
type Sender interface {
|
||||
Send(ctx context.Context, msg OutboundMessage) (providerID string, err error)
|
||||
}
|
||||
|
||||
type OutboundMessage struct {
|
||||
GuestID uuid.UUID
|
||||
Channel Channel
|
||||
Type Type
|
||||
Subject string
|
||||
Body string
|
||||
Metadata map[string]any
|
||||
}
|
||||
|
||||
// Repo persists notification records.
|
||||
type Repo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewRepo(db *storage.DB) *Repo {
|
||||
return &Repo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type RecordParams struct {
|
||||
GuestID uuid.UUID
|
||||
Channel Channel
|
||||
Type Type
|
||||
Status Status
|
||||
ProviderID string
|
||||
Error string
|
||||
}
|
||||
|
||||
func (r *Repo) Record(ctx context.Context, p RecordParams) (uuid.UUID, error) {
|
||||
var providerID *string
|
||||
if p.ProviderID != "" {
|
||||
providerID = &p.ProviderID
|
||||
}
|
||||
var errStr *string
|
||||
if p.Error != "" {
|
||||
errStr = &p.Error
|
||||
}
|
||||
|
||||
var deliveredAt *time.Time
|
||||
if p.Status == StatusSent || p.Status == StatusDelivered {
|
||||
now := time.Now().UTC()
|
||||
deliveredAt = &now
|
||||
}
|
||||
|
||||
const q = `
|
||||
INSERT INTO notifications (guest_id, channel, type, status, provider_id,
|
||||
attempts, last_attempt, delivered_at, error)
|
||||
VALUES ($1, $2, $3, $4, $5, 1, now(), $6, $7)
|
||||
RETURNING id
|
||||
`
|
||||
var id uuid.UUID
|
||||
err := r.pool.QueryRow(ctx, q,
|
||||
p.GuestID, string(p.Channel), string(p.Type), string(p.Status),
|
||||
providerID, deliveredAt, errStr,
|
||||
).Scan(&id)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("record notification: %w", err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// LogSender pretends to send and just logs. Useful for Phase 3 demos and
|
||||
// tests; concrete providers (Twilio/SES) plug in later.
|
||||
type LogSender struct{}
|
||||
|
||||
func (LogSender) Send(_ context.Context, msg OutboundMessage) (string, error) {
|
||||
if msg.GuestID == uuid.Nil {
|
||||
return "", errors.New("missing guest id")
|
||||
}
|
||||
meta, _ := json.Marshal(msg.Metadata)
|
||||
providerID := "log:" + uuid.NewString()
|
||||
// We deliberately don't write to stdout here; the worker emits the slog
|
||||
// line so we control the structure.
|
||||
_ = meta
|
||||
return providerID, nil
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type AccessLogRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAccessLogRepo(db *DB) *AccessLogRepo {
|
||||
return &AccessLogRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateAccessLogParams struct {
|
||||
GuestID uuid.UUID
|
||||
TokenID uuid.UUID
|
||||
Fingerprint map[string]any
|
||||
IPAddress string
|
||||
}
|
||||
|
||||
func (r *AccessLogRepo) Create(ctx context.Context, p CreateAccessLogParams) (uuid.UUID, error) {
|
||||
var fpJSON []byte
|
||||
if p.Fingerprint != nil {
|
||||
b, err := json.Marshal(p.Fingerprint)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("marshal fingerprint: %w", err)
|
||||
}
|
||||
fpJSON = b
|
||||
}
|
||||
|
||||
var ip *string
|
||||
if p.IPAddress != "" {
|
||||
ip = &p.IPAddress
|
||||
}
|
||||
|
||||
const q = `
|
||||
INSERT INTO access_logs (guest_id, token_id, fingerprint, ip_address)
|
||||
VALUES ($1, $2, $3, $4::inet)
|
||||
RETURNING id
|
||||
`
|
||||
var id uuid.UUID
|
||||
err := r.pool.QueryRow(ctx, q, p.GuestID, p.TokenID, fpJSON, ip).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
type ApplyScoreParams struct {
|
||||
AccessLogID uuid.UUID
|
||||
Score int
|
||||
Reasons []string
|
||||
Flagged bool
|
||||
}
|
||||
|
||||
// AccessCheckActivity is a scored access-log entry joined with the guest's
|
||||
// name. Used by the activity-history endpoint so dashboards can show
|
||||
// historical security checks (including blocked attempts) even when nobody
|
||||
// was watching the live monitor at the time.
|
||||
type AccessCheckActivity struct {
|
||||
GuestID uuid.UUID
|
||||
GuestName string
|
||||
Score int
|
||||
Reasons []string
|
||||
Flagged bool
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// ListRecentScoredByEvent returns scored access-log entries for an event,
|
||||
// newest first. Unscored entries (someone opened the page but the fraud
|
||||
// engine hasn't replied yet) are excluded — they'd be noise on the feed.
|
||||
func (r *AccessLogRepo) ListRecentScoredByEvent(ctx context.Context, eventID uuid.UUID, limit int) ([]AccessCheckActivity, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
const q = `
|
||||
SELECT a.guest_id, g.name, a.risk_score, a.risk_reasons, a.flagged, a.created_at
|
||||
FROM access_logs a
|
||||
JOIN guests g ON g.id = a.guest_id
|
||||
WHERE g.event_id = $1 AND a.risk_score IS NOT NULL
|
||||
ORDER BY a.created_at DESC
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, eventID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []AccessCheckActivity
|
||||
for rows.Next() {
|
||||
var (
|
||||
a AccessCheckActivity
|
||||
reasons []string
|
||||
score int16
|
||||
)
|
||||
if err := rows.Scan(&a.GuestID, &a.GuestName, &score, &reasons, &a.Flagged, &a.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.Score = int(score)
|
||||
a.Reasons = reasons
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (r *AccessLogRepo) ApplyScore(ctx context.Context, p ApplyScoreParams) error {
|
||||
const q = `
|
||||
UPDATE access_logs
|
||||
SET risk_score = $2, risk_reasons = $3, flagged = $4
|
||||
WHERE id = $1
|
||||
`
|
||||
tag, err := r.pool.Exec(ctx, q, p.AccessLogID, p.Score, p.Reasons, p.Flagged)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return errors.New("access_log not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
)
|
||||
|
||||
type EventRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewEventRepo(db *DB) *EventRepo {
|
||||
return &EventRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateEventParams struct {
|
||||
HostID uuid.UUID
|
||||
Name string
|
||||
Slug string
|
||||
EventDate time.Time
|
||||
Venue string
|
||||
MaxCapacity int
|
||||
Settings map[string]any
|
||||
Status domain.EventStatus
|
||||
}
|
||||
|
||||
func (r *EventRepo) Create(ctx context.Context, p CreateEventParams) (*domain.Event, error) {
|
||||
settings := p.Settings
|
||||
if settings == nil {
|
||||
settings = map[string]any{}
|
||||
}
|
||||
settingsJSON, err := json.Marshal(settings)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal settings: %w", err)
|
||||
}
|
||||
|
||||
const q = `
|
||||
INSERT INTO events (host_id, name, slug, event_date, venue, max_capacity, settings, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
`
|
||||
row := r.pool.QueryRow(ctx, q,
|
||||
p.HostID, p.Name, p.Slug, p.EventDate, p.Venue, p.MaxCapacity, settingsJSON, p.Status,
|
||||
)
|
||||
ev, err := scanEvent(row)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, domain.ErrSlugTaken
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
func (r *EventRepo) Get(ctx context.Context, id uuid.UUID) (*domain.Event, error) {
|
||||
const q = `
|
||||
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
FROM events WHERE id = $1
|
||||
`
|
||||
ev, err := scanEvent(r.pool.QueryRow(ctx, q, id))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrEventNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
func (r *EventRepo) List(ctx context.Context, hostID uuid.UUID, limit, offset int) ([]*domain.Event, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if hostID == uuid.Nil {
|
||||
rows, err = r.pool.Query(ctx, `
|
||||
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
FROM events
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1 OFFSET $2
|
||||
`, limit, offset)
|
||||
} else {
|
||||
rows, err = r.pool.Query(ctx, `
|
||||
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
FROM events
|
||||
WHERE host_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
`, hostID, limit, offset)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []*domain.Event
|
||||
for rows.Next() {
|
||||
ev, err := scanEvent(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, ev)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
type UpdateEventParams struct {
|
||||
Name *string
|
||||
Slug *string
|
||||
EventDate *time.Time
|
||||
Venue *string
|
||||
MaxCapacity *int
|
||||
Settings *map[string]any
|
||||
Status *domain.EventStatus
|
||||
}
|
||||
|
||||
func (r *EventRepo) Update(ctx context.Context, id uuid.UUID, p UpdateEventParams) (*domain.Event, error) {
|
||||
const q = `
|
||||
UPDATE events SET
|
||||
name = COALESCE($2, name),
|
||||
slug = COALESCE($3, slug),
|
||||
event_date = COALESCE($4, event_date),
|
||||
venue = COALESCE($5, venue),
|
||||
max_capacity = COALESCE($6, max_capacity),
|
||||
settings = COALESCE($7, settings),
|
||||
status = COALESCE($8, status),
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
|
||||
`
|
||||
|
||||
var settingsJSON []byte
|
||||
if p.Settings != nil {
|
||||
b, err := json.Marshal(*p.Settings)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal settings: %w", err)
|
||||
}
|
||||
settingsJSON = b
|
||||
}
|
||||
|
||||
row := r.pool.QueryRow(ctx, q, id,
|
||||
p.Name, p.Slug, p.EventDate, p.Venue, p.MaxCapacity, settingsJSON, p.Status,
|
||||
)
|
||||
ev, err := scanEvent(row)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrEventNotFound
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, domain.ErrSlugTaken
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
func (r *EventRepo) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
tag, err := r.pool.Exec(ctx, `DELETE FROM events WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return domain.ErrEventNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanEvent(s rowScanner) (*domain.Event, error) {
|
||||
var (
|
||||
ev domain.Event
|
||||
settingsJSON []byte
|
||||
)
|
||||
err := s.Scan(
|
||||
&ev.ID, &ev.HostID, &ev.Name, &ev.Slug, &ev.EventDate, &ev.Venue,
|
||||
&ev.MaxCapacity, &settingsJSON, &ev.Status, &ev.CreatedAt, &ev.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(settingsJSON) > 0 {
|
||||
if err := json.Unmarshal(settingsJSON, &ev.Settings); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal settings: %w", err)
|
||||
}
|
||||
} else {
|
||||
ev.Settings = map[string]any{}
|
||||
}
|
||||
return &ev, nil
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
)
|
||||
|
||||
type GuestRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewGuestRepo(db *DB) *GuestRepo {
|
||||
return &GuestRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateGuestParams struct {
|
||||
EventID uuid.UUID
|
||||
Name string
|
||||
Email *string
|
||||
Phone *string
|
||||
PlusOnes int
|
||||
DietaryNotes *string
|
||||
TableNumber *int
|
||||
}
|
||||
|
||||
func (r *GuestRepo) Create(ctx context.Context, p CreateGuestParams) (*domain.Guest, error) {
|
||||
const q = `
|
||||
INSERT INTO guests (event_id, name, email, phone, plus_ones, dietary_notes, table_number)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING id, event_id, name, email, phone, plus_ones, dietary_notes, table_number, created_at
|
||||
`
|
||||
row := r.pool.QueryRow(ctx, q,
|
||||
p.EventID, p.Name, p.Email, p.Phone, p.PlusOnes, p.DietaryNotes, p.TableNumber,
|
||||
)
|
||||
return scanGuest(row)
|
||||
}
|
||||
|
||||
func (r *GuestRepo) Get(ctx context.Context, id uuid.UUID) (*domain.Guest, error) {
|
||||
const q = `
|
||||
SELECT id, event_id, name, email, phone, plus_ones, dietary_notes, table_number, created_at
|
||||
FROM guests WHERE id = $1
|
||||
`
|
||||
g, err := scanGuest(r.pool.QueryRow(ctx, q, id))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrGuestNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
func (r *GuestRepo) ListByEvent(ctx context.Context, eventID uuid.UUID, limit, offset int) ([]*domain.Guest, error) {
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 100
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
const q = `
|
||||
SELECT id, event_id, name, email, phone, plus_ones, dietary_notes, table_number, created_at
|
||||
FROM guests
|
||||
WHERE event_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, eventID, limit, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []*domain.Guest
|
||||
for rows.Next() {
|
||||
g, err := scanGuest(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, g)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func scanGuest(s rowScanner) (*domain.Guest, error) {
|
||||
var g domain.Guest
|
||||
err := s.Scan(
|
||||
&g.ID, &g.EventID, &g.Name, &g.Email, &g.Phone,
|
||||
&g.PlusOnes, &g.DietaryNotes, &g.TableNumber, &g.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &g, nil
|
||||
}
|
||||
|
||||
// GuestWithRSVP is the dashboard view: a guest plus the RSVP submitted
|
||||
// against their token, if any. RSVP fields are nil when no response yet.
|
||||
type GuestWithRSVP struct {
|
||||
*domain.Guest
|
||||
RSVPResponse *string `json:"rsvp_response,omitempty"`
|
||||
RSVPPlusOnes *int `json:"rsvp_plus_ones,omitempty"`
|
||||
RSVPRiskScore *int `json:"rsvp_risk_score,omitempty"`
|
||||
RSVPSubmittedAt *time.Time `json:"rsvp_submitted_at,omitempty"`
|
||||
HasToken bool `json:"has_token"`
|
||||
}
|
||||
|
||||
func (r *GuestRepo) ListByEventWithRSVP(ctx context.Context, eventID uuid.UUID, limit, offset int) ([]*GuestWithRSVP, error) {
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 100
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
const q = `
|
||||
SELECT
|
||||
g.id, g.event_id, g.name, g.email, g.phone, g.plus_ones,
|
||||
g.dietary_notes, g.table_number, g.created_at,
|
||||
r.response, r.plus_ones, r.risk_score, r.submitted_at,
|
||||
t.id IS NOT NULL AS has_token
|
||||
FROM guests g
|
||||
LEFT JOIN rsvps r ON r.guest_id = g.id
|
||||
LEFT JOIN tokens t ON t.guest_id = g.id
|
||||
WHERE g.event_id = $1
|
||||
ORDER BY g.created_at DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, eventID, limit, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []*GuestWithRSVP
|
||||
for rows.Next() {
|
||||
var (
|
||||
g domain.Guest
|
||||
response *string
|
||||
rsvpPlusOnes *int
|
||||
riskScore *int
|
||||
submittedAt *time.Time
|
||||
hasToken bool
|
||||
)
|
||||
if err := rows.Scan(
|
||||
&g.ID, &g.EventID, &g.Name, &g.Email, &g.Phone, &g.PlusOnes,
|
||||
&g.DietaryNotes, &g.TableNumber, &g.CreatedAt,
|
||||
&response, &rsvpPlusOnes, &riskScore, &submittedAt,
|
||||
&hasToken,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, &GuestWithRSVP{
|
||||
Guest: &g,
|
||||
RSVPResponse: response,
|
||||
RSVPPlusOnes: rsvpPlusOnes,
|
||||
RSVPRiskScore: riskScore,
|
||||
RSVPSubmittedAt: submittedAt,
|
||||
HasToken: hasToken,
|
||||
})
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
DROP TABLE IF EXISTS notifications;
|
||||
DROP TABLE IF EXISTS access_logs;
|
||||
DROP TABLE IF EXISTS rsvps;
|
||||
DROP TABLE IF EXISTS tokens;
|
||||
DROP TABLE IF EXISTS guests;
|
||||
DROP TABLE IF EXISTS events;
|
||||
DROP TABLE IF EXISTS users;
|
||||
|
||||
DROP TYPE IF EXISTS delivery_status;
|
||||
DROP TYPE IF EXISTS notification_type;
|
||||
DROP TYPE IF EXISTS notification_channel;
|
||||
DROP TYPE IF EXISTS rsvp_response;
|
||||
DROP TYPE IF EXISTS token_status;
|
||||
DROP TYPE IF EXISTS event_status;
|
||||
@@ -0,0 +1,122 @@
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE event_status AS ENUM ('draft', 'published', 'closed', 'archived');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE token_status AS ENUM ('active', 'used', 'revoked', 'expired');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE rsvp_response AS ENUM ('attending', 'declined', 'maybe');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE notification_channel AS ENUM ('sms', 'email');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE notification_type AS ENUM ('invitation', 'verification', 'confirmation', 'reminder');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE delivery_status AS ENUM ('queued', 'sent', 'delivered', 'failed', 'bounced');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email VARCHAR(255) UNIQUE NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
host_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
slug VARCHAR(100) UNIQUE NOT NULL,
|
||||
event_date TIMESTAMPTZ NOT NULL,
|
||||
venue TEXT NOT NULL DEFAULT '',
|
||||
max_capacity INTEGER NOT NULL DEFAULT 0,
|
||||
settings JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
status event_status NOT NULL DEFAULT 'draft',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_events_host ON events(host_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_status ON events(status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS guests (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255),
|
||||
phone VARCHAR(20),
|
||||
plus_ones INTEGER NOT NULL DEFAULT 0,
|
||||
dietary_notes TEXT,
|
||||
table_number INTEGER,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_guests_event ON guests(event_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tokens (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
guest_id UUID NOT NULL UNIQUE REFERENCES guests(id) ON DELETE CASCADE,
|
||||
token_hash VARCHAR(64) NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
status token_status NOT NULL DEFAULT 'active',
|
||||
used_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_tokens_hash ON tokens(token_hash) WHERE status = 'active';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS rsvps (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
guest_id UUID NOT NULL UNIQUE REFERENCES guests(id) ON DELETE CASCADE,
|
||||
response rsvp_response NOT NULL,
|
||||
plus_ones INTEGER NOT NULL DEFAULT 0,
|
||||
dietary_notes TEXT,
|
||||
submitted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
device_fingerprint JSONB,
|
||||
ip_address INET,
|
||||
risk_score SMALLINT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_rsvps_guest ON rsvps(guest_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS access_logs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
guest_id UUID NOT NULL REFERENCES guests(id) ON DELETE CASCADE,
|
||||
token_id UUID REFERENCES tokens(id) ON DELETE SET NULL,
|
||||
fingerprint JSONB,
|
||||
ip_address INET,
|
||||
geo_location JSONB,
|
||||
risk_score SMALLINT,
|
||||
risk_reasons TEXT[],
|
||||
flagged BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_access_logs_guest ON access_logs(guest_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_access_logs_flagged ON access_logs(flagged) WHERE flagged = TRUE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
guest_id UUID NOT NULL REFERENCES guests(id) ON DELETE CASCADE,
|
||||
channel notification_channel NOT NULL,
|
||||
type notification_type NOT NULL,
|
||||
status delivery_status NOT NULL DEFAULT 'queued',
|
||||
provider_id VARCHAR(100),
|
||||
attempts SMALLINT NOT NULL DEFAULT 0,
|
||||
last_attempt TIMESTAMPTZ,
|
||||
delivered_at TIMESTAMPTZ,
|
||||
error TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_status ON notifications(status) WHERE status IN ('queued', 'failed');
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX IF EXISTS idx_rsvps_submitted_at;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- This migration adjusts RSVP recording to align with synchronous fraud scoring.
|
||||
-- The base table already exists; this is a no-op placeholder so future schema
|
||||
-- changes have a slot. We add an index that helps the dashboard query rsvps
|
||||
-- joined with guests by event.
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_rsvps_submitted_at ON rsvps (submitted_at DESC);
|
||||
@@ -0,0 +1,115 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
type DB struct {
|
||||
Pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewDB(ctx context.Context, dsn string) (*DB, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConns = 10
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect pool: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping db: %w", err)
|
||||
}
|
||||
|
||||
return &DB{Pool: pool}, nil
|
||||
}
|
||||
|
||||
func (db *DB) Close() {
|
||||
db.Pool.Close()
|
||||
}
|
||||
|
||||
func (db *DB) Migrate(ctx context.Context) error {
|
||||
_, err := db.Pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(255) PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create migrations table: %w", err)
|
||||
}
|
||||
|
||||
entries, err := fs.ReadDir(migrationsFS, "migrations")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migrations: %w", err)
|
||||
}
|
||||
|
||||
type migration struct {
|
||||
version string
|
||||
path string
|
||||
}
|
||||
var ups []migration
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
if !strings.HasSuffix(name, ".up.sql") {
|
||||
continue
|
||||
}
|
||||
version := strings.TrimSuffix(name, ".up.sql")
|
||||
ups = append(ups, migration{version: version, path: "migrations/" + name})
|
||||
}
|
||||
sort.Slice(ups, func(i, j int) bool { return ups[i].version < ups[j].version })
|
||||
|
||||
for _, m := range ups {
|
||||
var exists bool
|
||||
err := db.Pool.QueryRow(ctx,
|
||||
"SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)",
|
||||
m.version,
|
||||
).Scan(&exists)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check migration %s: %w", m.version, err)
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
|
||||
sqlBytes, err := migrationsFS.ReadFile(m.path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", m.path, err)
|
||||
}
|
||||
tx, err := db.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin tx for %s: %w", m.version, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, string(sqlBytes)); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("apply %s: %w", m.version, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES($1)", m.version); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("record %s: %w", m.version, err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit %s: %w", m.version, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
)
|
||||
|
||||
type RSVPRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewRSVPRepo(db *DB) *RSVPRepo {
|
||||
return &RSVPRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateRSVPParams struct {
|
||||
GuestID uuid.UUID
|
||||
Response domain.RSVPResponse
|
||||
PlusOnes int
|
||||
DietaryNotes *string
|
||||
DeviceFingerprint map[string]any
|
||||
IPAddress string
|
||||
RiskScore *int
|
||||
}
|
||||
|
||||
func (r *RSVPRepo) Create(ctx context.Context, p CreateRSVPParams) (*domain.RSVP, error) {
|
||||
var fpJSON []byte
|
||||
if p.DeviceFingerprint != nil {
|
||||
b, err := json.Marshal(p.DeviceFingerprint)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal fingerprint: %w", err)
|
||||
}
|
||||
fpJSON = b
|
||||
}
|
||||
|
||||
var ip *string
|
||||
if p.IPAddress != "" {
|
||||
ip = &p.IPAddress
|
||||
}
|
||||
|
||||
const q = `
|
||||
INSERT INTO rsvps (guest_id, response, plus_ones, dietary_notes,
|
||||
device_fingerprint, ip_address, risk_score)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::inet, $7)
|
||||
RETURNING id, guest_id, response, plus_ones, dietary_notes,
|
||||
submitted_at, device_fingerprint, ip_address::text, risk_score
|
||||
`
|
||||
|
||||
row := r.pool.QueryRow(ctx, q,
|
||||
p.GuestID, p.Response, p.PlusOnes, p.DietaryNotes,
|
||||
fpJSON, ip, p.RiskScore,
|
||||
)
|
||||
|
||||
rs, err := scanRSVP(row)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, domain.ErrRSVPAlreadySubmitted
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return rs, nil
|
||||
}
|
||||
|
||||
// RSVPActivity is a denormalised RSVP entry for the activity feed —
|
||||
// includes the guest's name so the API can hand it to the frontend
|
||||
// without a separate lookup.
|
||||
type RSVPActivity struct {
|
||||
GuestID uuid.UUID
|
||||
GuestName string
|
||||
Response string
|
||||
PlusOnes int
|
||||
SubmittedAt time.Time
|
||||
}
|
||||
|
||||
// ListRecentByEvent returns the most recent RSVPs for an event, newest first.
|
||||
func (r *RSVPRepo) ListRecentByEvent(ctx context.Context, eventID uuid.UUID, limit int) ([]RSVPActivity, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
const q = `
|
||||
SELECT r.guest_id, g.name, r.response, r.plus_ones, r.submitted_at
|
||||
FROM rsvps r
|
||||
JOIN guests g ON g.id = r.guest_id
|
||||
WHERE g.event_id = $1
|
||||
ORDER BY r.submitted_at DESC
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, eventID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []RSVPActivity
|
||||
for rows.Next() {
|
||||
var a RSVPActivity
|
||||
if err := rows.Scan(&a.GuestID, &a.GuestName, &a.Response, &a.PlusOnes, &a.SubmittedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func scanRSVP(s rowScanner) (*domain.RSVP, error) {
|
||||
var (
|
||||
rs domain.RSVP
|
||||
fpJSON []byte
|
||||
ip *string
|
||||
)
|
||||
err := s.Scan(
|
||||
&rs.ID, &rs.GuestID, &rs.Response, &rs.PlusOnes, &rs.DietaryNotes,
|
||||
&rs.SubmittedAt, &fpJSON, &ip, &rs.RiskScore,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(fpJSON) > 0 {
|
||||
_ = json.Unmarshal(fpJSON, &rs.DeviceFingerprint)
|
||||
}
|
||||
if ip != nil {
|
||||
rs.IPAddress = ip
|
||||
}
|
||||
return &rs, nil
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
)
|
||||
|
||||
type TokenRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewTokenRepo(db *DB) *TokenRepo {
|
||||
return &TokenRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
type CreateTokenParams struct {
|
||||
GuestID uuid.UUID
|
||||
TokenHash string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (r *TokenRepo) Create(ctx context.Context, p CreateTokenParams) (*domain.Token, error) {
|
||||
const q = `
|
||||
INSERT INTO tokens (guest_id, token_hash, expires_at, status)
|
||||
VALUES ($1, $2, $3, 'active')
|
||||
RETURNING id, guest_id, token_hash, expires_at, status, used_at, created_at
|
||||
`
|
||||
row := r.pool.QueryRow(ctx, q, p.GuestID, p.TokenHash, p.ExpiresAt)
|
||||
tk, err := scanToken(row)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, errors.New("guest already has a token")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return tk, nil
|
||||
}
|
||||
|
||||
func (r *TokenRepo) GetByHash(ctx context.Context, hash string) (*domain.Token, error) {
|
||||
const q = `
|
||||
SELECT id, guest_id, token_hash, expires_at, status, used_at, created_at
|
||||
FROM tokens WHERE token_hash = $1
|
||||
`
|
||||
tk, err := scanToken(r.pool.QueryRow(ctx, q, hash))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrTokenNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return tk, nil
|
||||
}
|
||||
|
||||
func (r *TokenRepo) MarkUsed(ctx context.Context, id uuid.UUID) error {
|
||||
tag, err := r.pool.Exec(ctx, `
|
||||
UPDATE tokens SET status = 'used', used_at = now()
|
||||
WHERE id = $1 AND status = 'active'
|
||||
`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return domain.ErrTokenNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanToken(s rowScanner) (*domain.Token, error) {
|
||||
var tk domain.Token
|
||||
err := s.Scan(
|
||||
&tk.ID, &tk.GuestID, &tk.TokenHash, &tk.ExpiresAt,
|
||||
&tk.Status, &tk.UsedAt, &tk.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tk, nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
)
|
||||
|
||||
type UserRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepo(db *DB) *UserRepo {
|
||||
return &UserRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
func (r *UserRepo) Create(ctx context.Context, email, name string) (*domain.User, error) {
|
||||
const q = `
|
||||
INSERT INTO users (email, name) VALUES ($1, $2)
|
||||
RETURNING id, email, name, created_at, updated_at
|
||||
`
|
||||
row := r.pool.QueryRow(ctx, q, strings.ToLower(strings.TrimSpace(email)), strings.TrimSpace(name))
|
||||
u, err := scanUser(row)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, domain.ErrEmailTaken
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (r *UserRepo) GetByEmail(ctx context.Context, email string) (*domain.User, error) {
|
||||
const q = `SELECT id, email, name, created_at, updated_at FROM users WHERE email = $1`
|
||||
u, err := scanUser(r.pool.QueryRow(ctx, q, strings.ToLower(strings.TrimSpace(email))))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrUserNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func scanUser(s rowScanner) (*domain.User, error) {
|
||||
var u domain.User
|
||||
if err := s.Scan(&u.ID, &u.Email, &u.Name, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
Reference in New Issue
Block a user