Changeset 0.32.0 (#206)
This commit is contained in:
54
server/store/sqlite/tickets.go
Normal file
54
server/store/sqlite/tickets.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
// TicketStore manages WS auth tickets in SQLite.
|
||||
// v0.32.0: functional parity for single-process test coverage.
|
||||
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 (?, ?, datetime('now', '+30 seconds'))`, id, userID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (s *TicketStore) Validate(ctx context.Context, ticketID string) (string, bool) {
|
||||
// SQLite has no DELETE ... RETURNING. Two-step: select then delete.
|
||||
var userID string
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT user_id FROM ws_tickets
|
||||
WHERE id = ? AND expires_at > datetime('now')`, ticketID).Scan(&userID)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return "", false
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
DB.ExecContext(ctx, `DELETE FROM ws_tickets WHERE id = ?`, ticketID)
|
||||
return userID, true
|
||||
}
|
||||
|
||||
func (s *TicketStore) Reap(ctx context.Context) (int, error) {
|
||||
res, err := DB.ExecContext(ctx, `DELETE FROM ws_tickets WHERE expires_at <= datetime('now')`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return int(n), nil
|
||||
}
|
||||
Reference in New Issue
Block a user