211 lines
6.0 KiB
Go
211 lines
6.0 KiB
Go
package account
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
var (
|
|
ErrCredentials = errors.New("invalid credentials")
|
|
ErrDuplicate = errors.New("username already in use")
|
|
ErrRevoked = errors.New("device revoked")
|
|
)
|
|
|
|
type User struct {
|
|
ID string `json:"id"`
|
|
Username string `json:"username"`
|
|
}
|
|
|
|
type Device struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Platform string `json:"platform"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
LastActiveAt time.Time `json:"lastActiveAt"`
|
|
RevokedAt *time.Time `json:"revokedAt,omitempty"`
|
|
SignedIn bool `json:"signedIn"`
|
|
}
|
|
|
|
type Identity struct {
|
|
User User `json:"user"`
|
|
Device Device `json:"device"`
|
|
}
|
|
|
|
type Auth struct {
|
|
Identity
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
type Store struct {
|
|
db *pgxpool.Pool
|
|
ttl time.Duration
|
|
dummyHash string
|
|
}
|
|
|
|
func New(db *pgxpool.Pool, ttl time.Duration) *Store {
|
|
return &Store{db: db, ttl: ttl, dummyHash: PasswordHash(Secret())}
|
|
}
|
|
|
|
func (s *Store) Open(ctx context.Context, register bool, username, password, name, platform string, publicKey []byte) (Auth, error) {
|
|
var result Auth
|
|
result.User.Username = username
|
|
var hash string
|
|
if register {
|
|
hash = PasswordHash(password)
|
|
} else {
|
|
err := s.db.QueryRow(ctx, "SELECT id, password_hash FROM users WHERE username=$1", username).Scan(&result.User.ID, &hash)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
VerifyPassword(password, s.dummyHash)
|
|
return Auth{}, ErrCredentials
|
|
}
|
|
if err != nil {
|
|
return Auth{}, err
|
|
}
|
|
if !VerifyPassword(password, hash) {
|
|
return Auth{}, ErrCredentials
|
|
}
|
|
}
|
|
|
|
tx, err := s.db.Begin(ctx)
|
|
if err != nil {
|
|
return Auth{}, err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
if register {
|
|
err = tx.QueryRow(ctx, "INSERT INTO users(username,password_hash) VALUES ($1,$2) RETURNING id", username, hash).Scan(&result.User.ID)
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return Auth{}, ErrDuplicate
|
|
}
|
|
if err != nil {
|
|
return Auth{}, err
|
|
}
|
|
}
|
|
|
|
row := tx.QueryRow(ctx, `
|
|
INSERT INTO devices(user_id, public_key, name, platform)
|
|
VALUES ($1,$2,$3,$4)
|
|
ON CONFLICT (user_id, public_key) DO UPDATE
|
|
SET last_active_at=now(), name=EXCLUDED.name
|
|
WHERE devices.revoked_at IS NULL AND devices.platform=EXCLUDED.platform
|
|
RETURNING id, name, platform, created_at, last_active_at, revoked_at
|
|
`, result.User.ID, publicKey, name, platform)
|
|
if err = scanDevice(row, &result.Device); errors.Is(err, pgx.ErrNoRows) {
|
|
return Auth{}, ErrRevoked
|
|
}
|
|
if err != nil {
|
|
return Auth{}, err
|
|
}
|
|
result.Token = Secret()
|
|
digest := sha256.Sum256([]byte(result.Token))
|
|
if _, err = tx.Exec(ctx, "INSERT INTO sessions VALUES ($1,$2,$3)", digest[:], result.Device.ID, time.Now().Add(s.ttl)); err != nil {
|
|
return Auth{}, err
|
|
}
|
|
result.Device.SignedIn = true
|
|
return result, tx.Commit(ctx)
|
|
}
|
|
|
|
func (s *Store) Session(ctx context.Context, token string) (Identity, error) {
|
|
digest, err := SessionDigest(token)
|
|
if err != nil {
|
|
return Identity{}, err
|
|
}
|
|
return s.SessionByDigest(ctx, digest[:])
|
|
}
|
|
|
|
func SessionDigest(token string) ([32]byte, error) {
|
|
raw, err := Encoding.Strict().DecodeString(token)
|
|
if err != nil || len(raw) != 32 {
|
|
return [32]byte{}, ErrCredentials
|
|
}
|
|
return sha256.Sum256([]byte(token)), nil
|
|
}
|
|
|
|
func (s *Store) SessionByDigest(ctx context.Context, digest []byte) (Identity, error) {
|
|
var identity Identity
|
|
d := &identity.Device
|
|
err := s.db.QueryRow(ctx, `
|
|
SELECT u.id, u.username, d.id, d.name, d.platform, d.created_at, d.last_active_at, d.revoked_at
|
|
FROM sessions s JOIN devices d ON d.id=s.device_id JOIN users u ON u.id=d.user_id
|
|
WHERE token_hash=$1 AND expires_at > now() AND d.revoked_at IS NULL
|
|
`, digest).Scan(&identity.User.ID, &identity.User.Username, &d.ID, &d.Name, &d.Platform, &d.CreatedAt, &d.LastActiveAt, &d.RevokedAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return Identity{}, ErrCredentials
|
|
}
|
|
d.SignedIn = err == nil
|
|
return identity, err
|
|
}
|
|
|
|
func (s *Store) Logout(ctx context.Context, token string) error {
|
|
digest := sha256.Sum256([]byte(token))
|
|
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest[:])
|
|
return err
|
|
}
|
|
|
|
func (s *Store) Devices(ctx context.Context, user string) ([]Device, error) {
|
|
rows, err := s.db.Query(ctx, `
|
|
SELECT id, name, platform, created_at, last_active_at, revoked_at,
|
|
revoked_at IS NULL AND EXISTS (
|
|
SELECT 1 FROM sessions WHERE device_id=devices.id AND expires_at > now()
|
|
)
|
|
FROM devices
|
|
WHERE user_id=$1 ORDER BY created_at DESC
|
|
`, user)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
devices := make([]Device, 0)
|
|
for rows.Next() {
|
|
var device Device
|
|
if err := rows.Scan(&device.ID, &device.Name, &device.Platform, &device.CreatedAt,
|
|
&device.LastActiveAt, &device.RevokedAt, &device.SignedIn); err != nil {
|
|
return nil, err
|
|
}
|
|
devices = append(devices, device)
|
|
}
|
|
return devices, rows.Err()
|
|
}
|
|
|
|
func (s *Store) TouchDevice(ctx context.Context, device string) error {
|
|
_, err := s.db.Exec(ctx, `
|
|
UPDATE devices SET last_active_at=now()
|
|
WHERE id=$1 AND revoked_at IS NULL AND last_active_at < now() - interval '1 minute'
|
|
`, device)
|
|
return err
|
|
}
|
|
|
|
func (s *Store) Revoke(ctx context.Context, user, device string) error {
|
|
tx, err := s.db.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
result, err := tx.Exec(ctx, "UPDATE devices SET revoked_at=COALESCE(revoked_at,now()) WHERE user_id=$1 AND id=$2", user, device)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if result.RowsAffected() == 0 {
|
|
return pgx.ErrNoRows
|
|
}
|
|
if _, err := tx.Exec(ctx, "DELETE FROM sessions WHERE device_id=$1", device); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
func (s *Store) Cleanup(ctx context.Context) error {
|
|
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE expires_at <= now()")
|
|
return err
|
|
}
|
|
|
|
func scanDevice(row pgx.Row, d *Device) error {
|
|
return row.Scan(&d.ID, &d.Name, &d.Platform, &d.CreatedAt, &d.LastActiveAt, &d.RevokedAt)
|
|
}
|