package users import ( "time" "supermarket/internal/db" ) // Limits on signing in. const ( // LockAfter failed sign-ins in a row lock an account, until its owner // resets the password or an admin unlocks it. LockAfter = 10 // ThrottleWindow is how long failures are counted for the limits below. ThrottleWindow = 15 * time.Minute // Within the window, an address may fail this often, and an IP this // often, before sign-ins from them are refused for the rest of it. MaxFailsPerEmail = 5 MaxFailsPerIP = 20 ) // FailedSignIn counts a wrong password or code against the user, and locks // the account at LockAfter. It says whether this failure locked it. func FailedSignIn(d *db.DB, u *User, now time.Time) (lockedNow bool, err error) { if _, err := d.Exec(`UPDATE users SET failed_signins = failed_signins + 1 WHERE id = ?`, u.ID); err != nil { return false, err } u.FailedSignIns++ if u.FailedSignIns < LockAfter || u.Locked() { return false, nil } res, err := d.Exec(`UPDATE users SET locked_at = ? WHERE id = ? AND locked_at = ''`, ts(now), u.ID) if err != nil { return false, err } n, _ := res.RowsAffected() u.LockedAt = now return n == 1, nil } // Unlock clears the failures and the lock: after a sign-in, a password // reset, or an admin's unlock. func Unlock(d *db.DB, id int64) error { _, err := d.Exec(`UPDATE users SET failed_signins = 0, locked_at = '' WHERE id = ?`, id) return err } // Throttle counts events (failed sign-ins, reset emails) by key within a // window. // Fails is how many events key has had in the window so far. func Fails(d *db.DB, key string, window time.Duration, now time.Time) (int, error) { var n int var since string err := d.QueryRow(`SELECT count, since FROM throttle WHERE key = ?`, key).Scan(&n, &since) if err != nil { return 0, nil // none yet (or unreadable: the other checks still hold) } if !parseTS(since).After(now.Add(-window)) { return 0, nil } return n, nil } // Fail counts one event for key, starting a new window if the last one // has passed. func Fail(d *db.DB, key string, window time.Duration, now time.Time) error { old := ts(now.Add(-window)) _, err := d.Exec(`INSERT INTO throttle (key, count, since) VALUES (?, 1, ?) ON CONFLICT (key) DO UPDATE SET count = CASE WHEN throttle.since <= ? THEN 1 ELSE throttle.count + 1 END, since = CASE WHEN throttle.since <= ? THEN excluded.since ELSE throttle.since END`, key, ts(now), old, old) return err } // ClearFails forgets key's events. func ClearFails(d *db.DB, key string) error { _, err := d.Exec(`DELETE FROM throttle WHERE key = ?`, key) return err } // PruneThrottle forgets counts whose window passed a day ago. func PruneThrottle(d *db.DB, now time.Time) error { _, err := d.Exec(`DELETE FROM throttle WHERE since < ?`, ts(now.Add(-24*time.Hour))) return err }