|
| 1 | +package registry |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rand" |
| 6 | + "crypto/sha256" |
| 7 | + "encoding/hex" |
| 8 | + "errors" |
| 9 | + "fmt" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/jackc/pgx/v5" |
| 13 | +) |
| 14 | + |
| 15 | +const sessionTokenBytes = 32 |
| 16 | + |
| 17 | +var ErrSessionNotFound = errors.New("session not found") |
| 18 | + |
| 19 | +func (r *Registry) CreateSession(ctx context.Context, username string, ttl time.Duration) (string, error) { |
| 20 | + token, err := generateSessionToken() |
| 21 | + if err != nil { |
| 22 | + return "", err |
| 23 | + } |
| 24 | + _, _ = r.pool.Exec(ctx, `DELETE FROM health_registry.sessions WHERE expires_at <= NOW()`) |
| 25 | + _, err = r.pool.Exec(ctx, ` |
| 26 | + INSERT INTO health_registry.sessions (id_hash, username, expires_at) |
| 27 | + VALUES ($1, $2, $3) |
| 28 | + `, sessionDigest(token), username, time.Now().Add(ttl)) |
| 29 | + if err != nil { |
| 30 | + return "", fmt.Errorf("create session: %w", err) |
| 31 | + } |
| 32 | + return token, nil |
| 33 | +} |
| 34 | + |
| 35 | +func (r *Registry) GetSessionUser(ctx context.Context, token string) (*User, error) { |
| 36 | + var u User |
| 37 | + var email *string |
| 38 | + err := r.pool.QueryRow(ctx, ` |
| 39 | + SELECT u.username, u.schema_name, u.api_key, u.password_hash, u.email, u.is_admin, u.created_at |
| 40 | + FROM health_registry.sessions s |
| 41 | + JOIN health_registry.users u ON u.username = s.username |
| 42 | + WHERE s.id_hash = $1 AND s.expires_at > NOW() |
| 43 | + `, sessionDigest(token)).Scan( |
| 44 | + &u.Username, &u.SchemaName, &u.APIKey, &u.PasswordHash, &email, &u.IsAdmin, &u.CreatedAt, |
| 45 | + ) |
| 46 | + if err != nil { |
| 47 | + if errors.Is(err, pgx.ErrNoRows) { |
| 48 | + return nil, ErrSessionNotFound |
| 49 | + } |
| 50 | + return nil, err |
| 51 | + } |
| 52 | + if email != nil { |
| 53 | + u.Email = *email |
| 54 | + } |
| 55 | + _, _ = r.pool.Exec(ctx, `UPDATE health_registry.sessions SET last_seen_at = NOW() WHERE id_hash = $1`, sessionDigest(token)) |
| 56 | + return &u, nil |
| 57 | +} |
| 58 | + |
| 59 | +func (r *Registry) DeleteSession(ctx context.Context, token string) error { |
| 60 | + _, err := r.pool.Exec(ctx, `DELETE FROM health_registry.sessions WHERE id_hash = $1`, sessionDigest(token)) |
| 61 | + return err |
| 62 | +} |
| 63 | + |
| 64 | +func generateSessionToken() (string, error) { |
| 65 | + b := make([]byte, sessionTokenBytes) |
| 66 | + if _, err := rand.Read(b); err != nil { |
| 67 | + return "", fmt.Errorf("crypto/rand: %w", err) |
| 68 | + } |
| 69 | + return hex.EncodeToString(b), nil |
| 70 | +} |
| 71 | + |
| 72 | +func sessionDigest(token string) string { |
| 73 | + sum := sha256.Sum256([]byte(token)) |
| 74 | + return hex.EncodeToString(sum[:]) |
| 75 | +} |
0 commit comments