Phase 10, part 1: users, sessions and form tokens
Schema 32 adds users, memberships and sessions, on both databases. internal/users keeps accounts (Argon2id passwords), roles and modules, and sessions whose rows hold only a hash of the cookie's value; they end after a week unused or 30 days. On the server edition, every page but the public ones needs a session and sends others to /signin. Every edition's forms now carry a CSRF token (a cookie repeated in each form, added as pages render; htmx sends it as a header), besides the same-origin check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Session lengths: a session ends after a week unused, and after 30 days
|
||||
// whatever happens.
|
||||
const (
|
||||
SessionIdle = 7 * 24 * time.Hour
|
||||
SessionMax = 30 * 24 * time.Hour
|
||||
// seenEvery is how often a session's last use is written down: not on
|
||||
// every request.
|
||||
seenEvery = time.Minute
|
||||
)
|
||||
|
||||
// Session is a signed-in browser. Its ID is the hash of the cookie's
|
||||
// value: a copy of the database doesn't let anyone in.
|
||||
type Session struct {
|
||||
ID string
|
||||
User int64
|
||||
Created time.Time
|
||||
Seen time.Time
|
||||
Expires time.Time
|
||||
IP string
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
// ErrNoSession is a cookie that leads nowhere: unknown, ended or expired,
|
||||
// or its user can't sign in any more.
|
||||
var ErrNoSession = errors.New("not signed in")
|
||||
|
||||
func hashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// NewToken is 32 random bytes, for a cookie or a link.
|
||||
func NewToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// StartSession signs a user in: it returns the token for the cookie.
|
||||
func StartSession(d *db.DB, user int64, ip, userAgent string, now time.Time) (string, *Session, error) {
|
||||
token, err := NewToken()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if len(userAgent) > 300 {
|
||||
userAgent = userAgent[:300]
|
||||
}
|
||||
s := &Session{ID: hashToken(token), User: user, Created: now, Seen: now, Expires: expiry(now, now), IP: ip, UserAgent: userAgent}
|
||||
_, err = d.Exec(`INSERT INTO sessions (id, user_id, created_at, seen_at, expires_at, ip, user_agent) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
s.ID, s.User, ts(s.Created), ts(s.Seen), ts(s.Expires), s.IP, s.UserAgent)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return token, s, nil
|
||||
}
|
||||
|
||||
// expiry is when a session created at created, last used at seen, ends.
|
||||
func expiry(created, seen time.Time) time.Time {
|
||||
idle, max := seen.Add(SessionIdle), created.Add(SessionMax)
|
||||
if idle.Before(max) {
|
||||
return idle
|
||||
}
|
||||
return max
|
||||
}
|
||||
|
||||
const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent`
|
||||
|
||||
func scanSession(row interface{ Scan(...any) error }) (*Session, error) {
|
||||
var s Session
|
||||
var created, seen, expires string
|
||||
if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.Created, s.Seen, s.Expires = parseTS(created), parseTS(seen), parseTS(expires)
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// Lookup finds the session and user a cookie's token belongs to, and
|
||||
// notes that it was used. Only active users have sessions that work.
|
||||
func Lookup(d *db.DB, token string, now time.Time) (*Session, *User, error) {
|
||||
if token == "" {
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
s, err := scanSession(d.QueryRow(`SELECT `+sessionCols+` FROM sessions WHERE id = ?`, hashToken(token)))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !now.Before(s.Expires) {
|
||||
_, _ = d.Exec(`DELETE FROM sessions WHERE id = ?`, s.ID)
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
u, err := ByID(d, s.User)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if u.Status != Active {
|
||||
return nil, nil, ErrNoSession
|
||||
}
|
||||
if now.Sub(s.Seen) >= seenEvery {
|
||||
s.Seen, s.Expires = now, expiry(s.Created, now)
|
||||
if _, err := d.Exec(`UPDATE sessions SET seen_at = ?, expires_at = ? WHERE id = ?`, ts(s.Seen), ts(s.Expires), s.ID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
return s, u, nil
|
||||
}
|
||||
|
||||
// EndSession signs a cookie's session out.
|
||||
func EndSession(d *db.DB, token string) error {
|
||||
_, err := d.Exec(`DELETE FROM sessions WHERE id = ?`, hashToken(token))
|
||||
return err
|
||||
}
|
||||
|
||||
// EndSessionByID signs one of a user's sessions out, by its ID (from
|
||||
// Sessions): only theirs.
|
||||
func EndSessionByID(d *db.DB, user int64, id string) error {
|
||||
_, err := d.Exec(`DELETE FROM sessions WHERE id = ? AND user_id = ?`, id, user)
|
||||
return err
|
||||
}
|
||||
|
||||
// EndOtherSessions signs a user out everywhere but the session keep (""
|
||||
// for everywhere). It returns how many ended.
|
||||
func EndOtherSessions(d *db.DB, user int64, keep string) (int64, error) {
|
||||
res, err := d.Exec(`DELETE FROM sessions WHERE user_id = ? AND id <> ?`, user, keep)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// Sessions are a user's sessions, the most recently used first.
|
||||
func Sessions(d *db.DB, user int64, now time.Time) ([]*Session, error) {
|
||||
rows, err := d.Query(`SELECT `+sessionCols+` FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY seen_at DESC`, user, ts(now))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*Session
|
||||
for rows.Next() {
|
||||
s, err := scanSession(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// PruneSessions deletes the sessions that have ended.
|
||||
func PruneSessions(d *db.DB, now time.Time) (int64, error) {
|
||||
res, err := d.Exec(`DELETE FROM sessions WHERE expires_at <= ?`, ts(now))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
Reference in New Issue
Block a user