Admins make the client's secret under Settings → Sign-in, which shows the entry for the Core's idproviders.yml (the secret's PBKDF2-SHA512 hash, the redirect address, PKCE). People sign in with their Core account: invited ones are matched by verified email, then by subject; optionally anyone at the Core's domain joins. Passwords can be turned off but for the owner's, and signing out ends the Core's session where it can. On multi-tenant, the team is found by its proved domain. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
195 lines
5.8 KiB
Go
195 lines
5.8 KiB
Go
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
|
|
Team int64 // the team it works in (multi-tenant: switchable)
|
|
// A platform admin viewing a team: until when, and why.
|
|
ViewUntil time.Time
|
|
ViewReason string
|
|
Via string // password or core
|
|
}
|
|
|
|
// 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) {
|
|
return StartSessionIn(d, user, Team, ip, userAgent, now)
|
|
}
|
|
|
|
// StartSessionIn signs a user in to work in a team.
|
|
func StartSessionIn(d *db.DB, user, team 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, Team: team}
|
|
_, err = d.Exec(`INSERT INTO sessions (id, user_id, created_at, seen_at, expires_at, ip, user_agent, team_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
s.ID, s.User, ts(s.Created), ts(s.Seen), ts(s.Expires), s.IP, s.UserAgent, s.Team)
|
|
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, team_id, view_until, view_reason, via`
|
|
|
|
func scanSession(row interface{ Scan(...any) error }) (*Session, error) {
|
|
var s Session
|
|
var created, seen, expires, until string
|
|
if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent, &s.Team, &until, &s.ViewReason, &s.Via); err != nil {
|
|
return nil, err
|
|
}
|
|
s.Created, s.Seen, s.Expires, s.ViewUntil = parseTS(created), parseTS(seen), parseTS(expires), parseTS(until)
|
|
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()
|
|
}
|
|
|
|
// SetVia records how a session signed in.
|
|
func SetVia(d *db.DB, id, via string) error {
|
|
_, err := d.Exec(`UPDATE sessions SET via = ? WHERE id = ?`, via, id)
|
|
return err
|
|
}
|