Changeset 0.32.0 (#206)
This commit is contained in:
53
server/store/postgres/tickets.go
Normal file
53
server/store/postgres/tickets.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
// TicketStore manages WS auth tickets in Postgres.
|
||||
// v0.32.0: replaces in-memory sync.Map for cross-pod validation.
|
||||
type TicketStore struct{}
|
||||
|
||||
func NewTicketStore() *TicketStore { return &TicketStore{} }
|
||||
|
||||
func (s *TicketStore) Issue(ctx context.Context, userID string) (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
id := hex.EncodeToString(b)
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
INSERT INTO ws_tickets (id, user_id, expires_at)
|
||||
VALUES ($1, $2, NOW() + INTERVAL '30 seconds')`, id, userID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (s *TicketStore) Validate(ctx context.Context, ticketID string) (string, bool) {
|
||||
var userID string
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
DELETE FROM ws_tickets
|
||||
WHERE id = $1 AND expires_at > NOW()
|
||||
RETURNING user_id`, ticketID).Scan(&userID)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return "", false
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
return userID, true
|
||||
}
|
||||
|
||||
func (s *TicketStore) Reap(ctx context.Context) (int, error) {
|
||||
res, err := DB.ExecContext(ctx, `DELETE FROM ws_tickets WHERE expires_at <= NOW()`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return int(n), nil
|
||||
}
|
||||
Reference in New Issue
Block a user