users.go126 lines, 3.4 KB
| 1 | // Package users is sign-up and bearer tokens. |
| 2 | package users |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "crypto/rand" |
| 7 | "crypto/sha256" |
| 8 | "encoding/base64" |
| 9 | "errors" |
| 10 | "net/http" |
| 11 | "regexp" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/fiston-user/murmur/internal/platform/httpx" |
| 17 | "github.com/fiston-user/murmur/internal/timeline" |
| 18 | "github.com/jackc/pgx/v5" |
| 19 | "github.com/jackc/pgx/v5/pgconn" |
| 20 | "github.com/jackc/pgx/v5/pgxpool" |
| 21 | ) |
| 22 | |
| 23 | var validHandle = regexp.MustCompile(`^[a-z0-9_]{3,20}$`) |
| 24 | |
| 25 | type Handler struct { |
| 26 | db *pgxpool.Pool |
| 27 | tl *timeline.Store |
| 28 | |
| 29 | // Remember is how long a token that we looked up is believed. |
| 30 | // Zero means every request asks Postgres, like before. |
| 31 | Remember time.Duration |
| 32 | now func() time.Time |
| 33 | known sync.Map // token hash -> session |
| 34 | } |
| 35 | |
| 36 | // A session is what we remember about a token. |
| 37 | type session struct { |
| 38 | user int64 |
| 39 | until time.Time |
| 40 | } |
| 41 | |
| 42 | func New(db *pgxpool.Pool, tl *timeline.Store) *Handler { |
| 43 | return &Handler{db: db, tl: tl, now: time.Now} |
| 44 | } |
| 45 | |
| 46 | // Create signs a user up and answers with a token, shown once. |
| 47 | func (h *Handler) Create(w http.ResponseWriter, r *http.Request) { |
| 48 | var in struct { |
| 49 | Handle string `json:"handle"` |
| 50 | } |
| 51 | if err := httpx.Decode(w, r, &in); err != nil || !validHandle.MatchString(in.Handle) { |
| 52 | httpx.Error(w, http.StatusBadRequest, "handle must be 3 to 20 of a-z, 0-9 and _") |
| 53 | return |
| 54 | } |
| 55 | b := make([]byte, 32) |
| 56 | rand.Read(b) |
| 57 | token := base64.RawURLEncoding.EncodeToString(b) |
| 58 | hash := sha256.Sum256([]byte(token)) |
| 59 | |
| 60 | var id int64 |
| 61 | err := h.db.QueryRow(r.Context(), |
| 62 | `insert into users (handle, token_hash) values ($1, $2) returning id`, |
| 63 | in.Handle, hash[:]).Scan(&id) |
| 64 | var pgErr *pgconn.PgError |
| 65 | if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation |
| 66 | httpx.Error(w, http.StatusConflict, "that handle is taken") |
| 67 | return |
| 68 | } |
| 69 | if err != nil { |
| 70 | httpx.ServerError(w, r, err) |
| 71 | return |
| 72 | } |
| 73 | httpx.JSON(w, http.StatusCreated, map[string]any{"id": id, "handle": in.Handle, "token": token}) |
| 74 | } |
| 75 | |
| 76 | type ctxKey struct{} |
| 77 | |
| 78 | // Auth lets a request through only with a valid bearer token. |
| 79 | func (h *Handler) Auth(next http.HandlerFunc) http.HandlerFunc { |
| 80 | return func(w http.ResponseWriter, r *http.Request) { |
| 81 | token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") |
| 82 | if !ok { |
| 83 | httpx.Error(w, http.StatusUnauthorized, "missing bearer token") |
| 84 | return |
| 85 | } |
| 86 | hash := sha256.Sum256([]byte(token)) |
| 87 | if s, ok := h.known.Load(hash); ok && h.now().Before(s.(session).until) { |
| 88 | next(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, s.(session).user))) |
| 89 | return |
| 90 | } |
| 91 | |
| 92 | var id int64 |
| 93 | err := h.db.QueryRow(r.Context(), `select id from users where token_hash = $1`, hash[:]).Scan(&id) |
| 94 | if errors.Is(err, pgx.ErrNoRows) { |
| 95 | httpx.Error(w, http.StatusUnauthorized, "invalid token") |
| 96 | return |
| 97 | } |
| 98 | if err != nil { |
| 99 | httpx.ServerError(w, r, err) |
| 100 | return |
| 101 | } |
| 102 | if h.Remember > 0 { |
| 103 | h.known.Store(hash, session{user: id, until: h.now().Add(h.Remember)}) |
| 104 | } |
| 105 | next(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, id))) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // Maybe is Auth for a route that anybody may call. A caller with a token is |
| 110 | // known, and a caller without one is nobody. |
| 111 | func (h *Handler) Maybe(next http.HandlerFunc) http.HandlerFunc { |
| 112 | known := h.Auth(next) |
| 113 | return func(w http.ResponseWriter, r *http.Request) { |
| 114 | if r.Header.Get("Authorization") == "" { |
| 115 | next(w, r) |
| 116 | return |
| 117 | } |
| 118 | known(w, r) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // ID returns the id of the user Auth let through. |
| 123 | func ID(ctx context.Context) int64 { |
| 124 | id, _ := ctx.Value(ctxKey{}).(int64) |
| 125 | return id |
| 126 | } |