feat(devices): P2 sessions 表 + 在线/最后登录/客户端版本
ci-pangolin / Lint — shellcheck (push) Successful in 8s
ci-pangolin / OpenAPI Sync Check (push) Successful in 18s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Successful in 6s
ci-pangolin / Flutter — analyze + test (push) Successful in 24s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (push) Successful in 5s
ci-pangolin / Codegen Drift — token 生成物未漂移 (push) Successful in 4s
ci-pangolin / Go — build + test (push) Successful in 11s
ci-pangolin / E2E Smoke — L4 进程级端到端 (push) Successful in 14s
ci-pangolin / Go — integration (mysql/redis testcontainers) (push) Failing after 4m13s
ci-pangolin / Golden — 视觉回归 (components + auth) (push) Successful in 14s
ci-pangolin / Lint — shellcheck (push) Successful in 8s
ci-pangolin / OpenAPI Sync Check (push) Successful in 18s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Successful in 6s
ci-pangolin / Flutter — analyze + test (push) Successful in 24s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (push) Successful in 5s
ci-pangolin / Codegen Drift — token 生成物未漂移 (push) Successful in 4s
ci-pangolin / Go — build + test (push) Successful in 11s
ci-pangolin / E2E Smoke — L4 进程级端到端 (push) Successful in 14s
ci-pangolin / Go — integration (mysql/redis testcontainers) (push) Failing after 4m13s
ci-pangolin / Golden — 视觉回归 (components + auth) (push) Successful in 14s
migration 000016(mysql+sqlite,含 down):新增 sessions 表(绑 device+refresh JTI) + devices 加 client_version/totp_trusted_until。devices 唯一键改 + platform CHECK 加 linux(需 SQLite 表重建)拆出后续迁移,降风险。 后端:新 internal/sessions Store(Create/Rotate/Revoke/RevokeByDevice/ LastLoginByDevice);TokenManager 外露 refresh JTI(IssueWithJTI/RefreshWithJTI/ ParseRefreshJTI);auth.Service 注入 SessionStore——登录建会话、刷新轮换、登出吊销; DeviceRegistrar 返回 deviceID;ReportUsage 心跳 touch devices.last_seen(在线判定); devices.ListDevices 经 LastLoginSource 注入返回 online(last_seen<3min)/client_version/ last_login;RegisterIfAbsent 存 client_version。 客户端:Device model 加 online/clientVersion/lastLogin(fromJson 自动解析)。 测试:sessions store 3 例 + ListDevices 在线/最后登录 + device model 2 例 + migration v16;全量 go test/flutter test 绿。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -11,15 +11,16 @@ type fakeRegistrar struct {
|
||||
userID int64
|
||||
meta DeviceMeta
|
||||
}
|
||||
err error
|
||||
deviceID int64
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeRegistrar) RegisterDevice(_ context.Context, userID int64, meta DeviceMeta) error {
|
||||
func (f *fakeRegistrar) RegisterDevice(_ context.Context, userID int64, meta DeviceMeta) (int64, error) {
|
||||
f.calls = append(f.calls, struct {
|
||||
userID int64
|
||||
meta DeviceMeta
|
||||
}{userID, meta})
|
||||
return f.err
|
||||
return f.deviceID, f.err
|
||||
}
|
||||
|
||||
// Register/Login with a device should trigger RegisterDevice with the meta.
|
||||
@@ -36,7 +37,7 @@ func TestService_RegisterDevice_OnRegisterAndLogin(t *testing.T) {
|
||||
t.Fatalf("SendCode: %v", err)
|
||||
}
|
||||
code := codeInRedis(t, svc, email)
|
||||
if _, e := svc.Register(ctx, email, code, pw, meta); e != nil {
|
||||
if _, e := svc.Register(ctx, email, code, pw, "1.2.3.4", meta); e != nil {
|
||||
t.Fatalf("Register: %v", e)
|
||||
}
|
||||
if len(reg.calls) != 1 || reg.calls[0].meta.DeviceID != "dev-uuid-1" || reg.calls[0].meta.Platform != "macos" {
|
||||
@@ -64,7 +65,7 @@ func TestService_RegisterDevice_BestEffort(t *testing.T) {
|
||||
t.Fatalf("SendCode: %v", err)
|
||||
}
|
||||
code := codeInRedis(t, svc, email)
|
||||
if _, e := svc.Register(ctx, email, code, "supersecret", DeviceMeta{DeviceID: "x", Platform: "windows"}); e != nil {
|
||||
if _, e := svc.Register(ctx, email, code, "supersecret", "", DeviceMeta{DeviceID: "x", Platform: "windows"}); e != nil {
|
||||
t.Fatalf("Register must succeed despite registrar error: %v", e)
|
||||
}
|
||||
}
|
||||
@@ -80,7 +81,7 @@ func TestService_RegisterDevice_NoMeta(t *testing.T) {
|
||||
t.Fatalf("SendCode: %v", err)
|
||||
}
|
||||
code := codeInRedis(t, svc, email)
|
||||
if _, e := svc.Register(ctx, email, code, "supersecret", DeviceMeta{}); e != nil {
|
||||
if _, e := svc.Register(ctx, email, code, "supersecret", "", DeviceMeta{}); e != nil {
|
||||
t.Fatalf("Register: %v", e)
|
||||
}
|
||||
if len(reg.calls) != 0 {
|
||||
|
||||
@@ -102,7 +102,7 @@ func (h *Handler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
if !decodeJSON(w, r, &req) {
|
||||
return
|
||||
}
|
||||
pair, apiErr := h.svc.Register(r.Context(), req.Email, req.Code, req.Password, req.Device.toMeta())
|
||||
pair, apiErr := h.svc.Register(r.Context(), req.Email, req.Code, req.Password, clientIP(r), req.Device.toMeta())
|
||||
if apiErr != nil {
|
||||
writeAPIErr(w, apiErr, 0)
|
||||
return
|
||||
|
||||
@@ -86,40 +86,61 @@ type DeviceMeta struct {
|
||||
ClientVersion string // app version (stored from P2 onward)
|
||||
}
|
||||
|
||||
// DeviceRegistrar registers the logging-in device. Defined consumer-side to
|
||||
// avoid an import cycle; devices.Service is adapted to it in main wiring.
|
||||
// Registration is best-effort and must never block login (see registerDevice).
|
||||
// DeviceRegistrar registers the logging-in device and returns its internal id
|
||||
// (for session binding). Defined consumer-side to avoid an import cycle;
|
||||
// devices.Service is adapted to it in main wiring. Best-effort (see recordLogin).
|
||||
type DeviceRegistrar interface {
|
||||
RegisterDevice(ctx context.Context, userID int64, meta DeviceMeta) error
|
||||
RegisterDevice(ctx context.Context, userID int64, meta DeviceMeta) (deviceID int64, err error)
|
||||
}
|
||||
|
||||
// SessionStore persists login sessions bound to a refresh JTI. Satisfied by
|
||||
// sessions.Store; injected so auth stays decoupled.
|
||||
type SessionStore interface {
|
||||
Create(ctx context.Context, userID, deviceID int64, jti, ip, clientVersion string) error
|
||||
Rotate(ctx context.Context, oldJTI, newJTI string) error
|
||||
Revoke(ctx context.Context, jti string) error
|
||||
}
|
||||
|
||||
// Service is the auth business layer: code issuance, registration, login, and
|
||||
// token refresh. It is safe for concurrent use.
|
||||
type Service struct {
|
||||
store UserStore
|
||||
rdb *redis.Client
|
||||
rl *RateLimiter
|
||||
tokens *TokenManager
|
||||
mailer Mailer
|
||||
cfg ServiceConfig
|
||||
now func() time.Time
|
||||
devReg DeviceRegistrar // nil until wired; registration is best-effort
|
||||
store UserStore
|
||||
rdb *redis.Client
|
||||
rl *RateLimiter
|
||||
tokens *TokenManager
|
||||
mailer Mailer
|
||||
cfg ServiceConfig
|
||||
now func() time.Time
|
||||
devReg DeviceRegistrar // nil until wired; registration is best-effort
|
||||
sessions SessionStore // nil until wired; session recording is best-effort
|
||||
}
|
||||
|
||||
// SetDeviceRegistrar wires the device registrar after construction (main keeps
|
||||
// auth and devices decoupled). Safe to call once during startup.
|
||||
// SetDeviceRegistrar / SetSessionStore wire collaborators after construction
|
||||
// (main keeps auth, devices and sessions decoupled). Call once during startup.
|
||||
func (s *Service) SetDeviceRegistrar(r DeviceRegistrar) { s.devReg = r }
|
||||
func (s *Service) SetSessionStore(st SessionStore) { s.sessions = st }
|
||||
|
||||
// registerDevice records the logging-in device. Best-effort: a registrar error
|
||||
// (device cap, transient DB) is logged but never fails the login/registration —
|
||||
// the user must always be able to get in (notably: free-plan reinstall churns
|
||||
// the device UUID, so a hard cap here would lock users out).
|
||||
func (s *Service) registerDevice(ctx context.Context, userID int64, meta DeviceMeta) {
|
||||
if s.devReg == nil || meta.DeviceID == "" {
|
||||
// recordLogin registers the device and binds a session to the freshly-issued
|
||||
// refresh JTI. Best-effort: a registrar/session error (device cap, transient DB)
|
||||
// is logged but never fails login — the user must always be able to get in
|
||||
// (notably: free-plan reinstall churns the device UUID, so a hard cap here would
|
||||
// lock users out).
|
||||
func (s *Service) recordLogin(ctx context.Context, userID int64, refreshJTI, ip string, meta DeviceMeta) {
|
||||
if meta.DeviceID == "" {
|
||||
return
|
||||
}
|
||||
if err := s.devReg.RegisterDevice(ctx, userID, meta); err != nil {
|
||||
slog.Warn("auth: device register failed (login proceeds)", "uid", userID, "err", err)
|
||||
var deviceID int64
|
||||
if s.devReg != nil {
|
||||
id, err := s.devReg.RegisterDevice(ctx, userID, meta)
|
||||
if err != nil {
|
||||
slog.Warn("auth: device register failed (login proceeds)", "uid", userID, "err", err)
|
||||
}
|
||||
deviceID = id
|
||||
}
|
||||
if s.sessions != nil && deviceID > 0 && refreshJTI != "" {
|
||||
if err := s.sessions.Create(ctx, userID, deviceID, refreshJTI, ip, meta.ClientVersion); err != nil {
|
||||
slog.Warn("auth: session create failed (login proceeds)", "uid", userID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,7 +239,7 @@ func (s *Service) SendCode(ctx context.Context, rawEmail, ip string) (retryAfter
|
||||
|
||||
// Register verifies the code (one-time), creates the account plus a 7-day PRO
|
||||
// trial in a single transaction, and returns a fresh token pair.
|
||||
func (s *Service) Register(ctx context.Context, rawEmail, code, password string, device DeviceMeta) (*TokenPair, *apierr.Error) {
|
||||
func (s *Service) Register(ctx context.Context, rawEmail, code, password, ip string, device DeviceMeta) (*TokenPair, *apierr.Error) {
|
||||
email := NormalizeEmail(rawEmail)
|
||||
if !ValidEmail(email) || len(password) < 8 || len(code) != 6 {
|
||||
return nil, ErrInvalidRequest
|
||||
@@ -247,11 +268,11 @@ func (s *Service) Register(ctx context.Context, rawEmail, code, password string,
|
||||
return nil, ErrInternal
|
||||
}
|
||||
|
||||
pair, err := s.tokens.Issue(ctx, user.ID, user.UUID)
|
||||
pair, jti, err := s.tokens.IssueWithJTI(ctx, user.ID, user.UUID)
|
||||
if err != nil {
|
||||
return nil, ErrInternal
|
||||
}
|
||||
s.registerDevice(ctx, user.ID, device)
|
||||
s.recordLogin(ctx, user.ID, jti, ip, device)
|
||||
return pair, nil
|
||||
}
|
||||
|
||||
@@ -308,7 +329,6 @@ const (
|
||||
)
|
||||
|
||||
func (s *Service) Login(ctx context.Context, rawEmail, password, ip string, device DeviceMeta) (*LoginOutcome, time.Duration, *apierr.Error) {
|
||||
_ = ip // IP reserved for future per-IP login throttling; not logged.
|
||||
email := NormalizeEmail(rawEmail)
|
||||
if email == "" || password == "" {
|
||||
return nil, 0, ErrInvalidRequest
|
||||
@@ -360,11 +380,11 @@ func (s *Service) Login(ctx context.Context, rawEmail, password, ip string, devi
|
||||
return &LoginOutcome{PendingToken: pending}, 0, nil
|
||||
}
|
||||
|
||||
pair, err := s.tokens.Issue(ctx, user.ID, user.UUID)
|
||||
pair, jti, err := s.tokens.IssueWithJTI(ctx, user.ID, user.UUID)
|
||||
if err != nil {
|
||||
return nil, 0, ErrInternal
|
||||
}
|
||||
s.registerDevice(ctx, user.ID, device)
|
||||
s.recordLogin(ctx, user.ID, jti, ip, device)
|
||||
return &LoginOutcome{Tokens: pair}, 0, nil
|
||||
}
|
||||
|
||||
@@ -374,15 +394,22 @@ func (s *Service) Logout(ctx context.Context, refreshToken string) {
|
||||
if refreshToken == "" {
|
||||
return
|
||||
}
|
||||
// Mark the bound session revoked before dropping the Redis whitelist entry.
|
||||
if s.sessions != nil {
|
||||
if jti, err := s.tokens.ParseRefreshJTI(refreshToken); err == nil {
|
||||
_ = s.sessions.Revoke(ctx, jti)
|
||||
}
|
||||
}
|
||||
_ = s.tokens.RevokeRefresh(ctx, refreshToken)
|
||||
}
|
||||
|
||||
// Refresh validates and rotates a refresh token.
|
||||
// Refresh validates and rotates a refresh token, moving the bound session to the
|
||||
// new JTI.
|
||||
func (s *Service) Refresh(ctx context.Context, refreshToken string) (*TokenPair, *apierr.Error) {
|
||||
if refreshToken == "" {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
pair, err := s.tokens.Refresh(ctx, refreshToken)
|
||||
pair, oldJTI, newJTI, err := s.tokens.RefreshWithJTI(ctx, refreshToken)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrInvalidTokenSentinel) {
|
||||
return nil, ErrInvalidToken
|
||||
@@ -390,6 +417,9 @@ func (s *Service) Refresh(ctx context.Context, refreshToken string) (*TokenPair,
|
||||
// Parse / signature / expiry failures all map to an opaque invalid-token.
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
if s.sessions != nil {
|
||||
_ = s.sessions.Rotate(ctx, oldJTI, newJTI)
|
||||
}
|
||||
return pair, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ func TestService_RegisterFullFlow(t *testing.T) {
|
||||
}
|
||||
code := codeInRedis(t, svc, email)
|
||||
|
||||
pair, apiErr := svc.Register(ctx, email, code, "supersecret", DeviceMeta{})
|
||||
pair, apiErr := svc.Register(ctx, email, code, "supersecret", "", DeviceMeta{})
|
||||
if apiErr != nil {
|
||||
t.Fatalf("Register: %v", apiErr)
|
||||
}
|
||||
@@ -84,7 +84,7 @@ func TestService_DuplicateEmailConflict(t *testing.T) {
|
||||
|
||||
// First registration.
|
||||
_, _ = svc.SendCode(ctx, email, "")
|
||||
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), "password1", DeviceMeta{}); e != nil {
|
||||
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), "password1", "", DeviceMeta{}); e != nil {
|
||||
t.Fatalf("first register: %v", e)
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ func TestService_DuplicateEmailConflict(t *testing.T) {
|
||||
if err := svc.rdb.Set(ctx, codeKey(email), "654321", 10*time.Minute).Err(); err != nil {
|
||||
t.Fatalf("force code: %v", err)
|
||||
}
|
||||
_, apiErr := svc.Register(ctx, email, "654321", "password2", DeviceMeta{})
|
||||
_, apiErr := svc.Register(ctx, email, "654321", "password2", "", DeviceMeta{})
|
||||
if apiErr == nil || apiErr.Code != ErrCodeInvalid.Code {
|
||||
t.Fatalf("want code_invalid (anti-enumeration), got %v", apiErr)
|
||||
}
|
||||
@@ -115,7 +115,7 @@ func TestService_CodeWrong(t *testing.T) {
|
||||
const email = "wrong@example.com"
|
||||
_, _ = svc.SendCode(ctx, email, "")
|
||||
|
||||
_, apiErr := svc.Register(ctx, email, "000000", "password1", DeviceMeta{})
|
||||
_, apiErr := svc.Register(ctx, email, "000000", "password1", "", DeviceMeta{})
|
||||
if apiErr == nil || apiErr.Code != ErrCodeInvalid.Code {
|
||||
t.Fatalf("want code_invalid, got %v", apiErr)
|
||||
}
|
||||
@@ -131,7 +131,7 @@ func TestService_CodeExpired(t *testing.T) {
|
||||
// Expire the code key.
|
||||
svc.rdb.Del(ctx, codeKey(email))
|
||||
|
||||
_, apiErr := svc.Register(ctx, email, code, "password1", DeviceMeta{})
|
||||
_, apiErr := svc.Register(ctx, email, code, "password1", "", DeviceMeta{})
|
||||
if apiErr == nil || apiErr.Code != ErrCodeInvalid.Code {
|
||||
t.Fatalf("want code_invalid after expiry, got %v", apiErr)
|
||||
}
|
||||
@@ -144,11 +144,11 @@ func TestService_CodeReuseRejected(t *testing.T) {
|
||||
_, _ = svc.SendCode(ctx, email, "")
|
||||
code := codeInRedis(t, svc, email)
|
||||
|
||||
if _, e := svc.Register(ctx, email, code, "password1", DeviceMeta{}); e != nil {
|
||||
if _, e := svc.Register(ctx, email, code, "password1", "", DeviceMeta{}); e != nil {
|
||||
t.Fatalf("first register: %v", e)
|
||||
}
|
||||
// Re-using the consumed code must fail.
|
||||
_, apiErr := svc.Register(ctx, "other@example.com", code, "password1", DeviceMeta{})
|
||||
_, apiErr := svc.Register(ctx, "other@example.com", code, "password1", "", DeviceMeta{})
|
||||
if apiErr == nil || apiErr.Code != ErrCodeInvalid.Code {
|
||||
t.Fatalf("want code_invalid on reuse, got %v", apiErr)
|
||||
}
|
||||
@@ -163,12 +163,12 @@ func TestService_CodeBruteForceBurned(t *testing.T) {
|
||||
|
||||
// 3 wrong attempts burn the code.
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, e := svc.Register(ctx, email, "999999", "password1", DeviceMeta{}); e == nil {
|
||||
if _, e := svc.Register(ctx, email, "999999", "password1", "", DeviceMeta{}); e == nil {
|
||||
t.Fatal("wrong code should fail")
|
||||
}
|
||||
}
|
||||
// Even the correct code no longer works.
|
||||
if _, e := svc.Register(ctx, email, good, "password1", DeviceMeta{}); e == nil || e.Code != ErrCodeInvalid.Code {
|
||||
if _, e := svc.Register(ctx, email, good, "password1", "", DeviceMeta{}); e == nil || e.Code != ErrCodeInvalid.Code {
|
||||
t.Fatalf("burned code should reject correct value, got %v", e)
|
||||
}
|
||||
}
|
||||
@@ -205,7 +205,7 @@ func TestService_LoginAndLockout(t *testing.T) {
|
||||
const pw = "rightpassword"
|
||||
|
||||
_, _ = svc.SendCode(ctx, email, "")
|
||||
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), pw, DeviceMeta{}); e != nil {
|
||||
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), pw, "", DeviceMeta{}); e != nil {
|
||||
t.Fatalf("register: %v", e)
|
||||
}
|
||||
|
||||
@@ -247,7 +247,7 @@ func TestService_BannedUserRejected(t *testing.T) {
|
||||
const pw = "password1"
|
||||
|
||||
_, _ = svc.SendCode(ctx, email, "")
|
||||
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), pw, DeviceMeta{}); e != nil {
|
||||
if _, e := svc.Register(ctx, email, codeInRedis(t, svc, email), pw, "", DeviceMeta{}); e != nil {
|
||||
t.Fatalf("register: %v", e)
|
||||
}
|
||||
store.setStatus(email, "banned")
|
||||
@@ -264,7 +264,7 @@ func TestService_RefreshRotation(t *testing.T) {
|
||||
const email = "refresh@example.com"
|
||||
|
||||
_, _ = svc.SendCode(ctx, email, "")
|
||||
pair, e := svc.Register(ctx, email, codeInRedis(t, svc, email), "password1", DeviceMeta{})
|
||||
pair, e := svc.Register(ctx, email, codeInRedis(t, svc, email), "password1", "", DeviceMeta{})
|
||||
if e != nil {
|
||||
t.Fatalf("register: %v", e)
|
||||
}
|
||||
|
||||
@@ -113,27 +113,34 @@ func NewTokenManager(rdb *redis.Client, cfg TokenConfig) (*TokenManager, error)
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Issue mints a fresh access+refresh pair for the user and whitelists the
|
||||
// refresh JTI in Redis with the refresh TTL.
|
||||
func (tm *TokenManager) Issue(ctx context.Context, userID int64, userUUID string) (*TokenPair, error) {
|
||||
// IssueWithJTI mints a fresh access+refresh pair, whitelists the refresh JTI in
|
||||
// Redis, and returns that JTI so the caller can bind a session to the refresh
|
||||
// token. Issue wraps this when the JTI isn't needed.
|
||||
func (tm *TokenManager) IssueWithJTI(ctx context.Context, userID int64, userUUID string) (*TokenPair, string, error) {
|
||||
now := tm.now()
|
||||
|
||||
access, _, err := tm.sign(userID, userUUID, typAccess, tm.accessTTL, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
refresh, refreshJTI, err := tm.sign(userID, userUUID, typRefresh, tm.refreshTTL, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
if err := tm.whitelist(ctx, refreshJTI, userID); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
return &TokenPair{
|
||||
AccessToken: access,
|
||||
RefreshToken: refresh,
|
||||
ExpiresIn: int(tm.accessTTL.Seconds()),
|
||||
}, nil
|
||||
}, refreshJTI, nil
|
||||
}
|
||||
|
||||
// Issue mints a fresh access+refresh pair (refresh JTI discarded).
|
||||
func (tm *TokenManager) Issue(ctx context.Context, userID int64, userUUID string) (*TokenPair, error) {
|
||||
pair, _, err := tm.IssueWithJTI(ctx, userID, userUUID)
|
||||
return pair, err
|
||||
}
|
||||
|
||||
// sign builds and signs one token, returning the compact string and its JTI.
|
||||
@@ -206,13 +213,13 @@ func (tm *TokenManager) ParseAccess(tokenStr string) (*Claims, error) {
|
||||
return tm.parse(tokenStr, typAccess)
|
||||
}
|
||||
|
||||
// Refresh validates a refresh token against the Redis whitelist, then rotates:
|
||||
// the old JTI is deleted and a brand-new access+refresh pair is issued, so the
|
||||
// presented refresh token can never be replayed.
|
||||
func (tm *TokenManager) Refresh(ctx context.Context, refreshToken string) (*TokenPair, error) {
|
||||
// RefreshWithJTI validates+rotates a refresh token (single-use) and returns the
|
||||
// old and new refresh JTIs so the caller can move the bound session. Refresh
|
||||
// wraps this when the JTIs aren't needed.
|
||||
func (tm *TokenManager) RefreshWithJTI(ctx context.Context, refreshToken string) (pair *TokenPair, oldJTI, newJTI string, err error) {
|
||||
claims, err := tm.parse(refreshToken, typRefresh)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, "", "", err
|
||||
}
|
||||
|
||||
// Whitelist check + single-use rotation: DEL returns the number of keys
|
||||
@@ -220,13 +227,23 @@ func (tm *TokenManager) Refresh(ctx context.Context, refreshToken string) (*Toke
|
||||
// banned) → reject.
|
||||
removed, err := tm.rdb.Del(ctx, refreshKeyPrefix+claims.ID).Result()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("auth: refresh whitelist del: %w", err)
|
||||
return nil, "", "", fmt.Errorf("auth: refresh whitelist del: %w", err)
|
||||
}
|
||||
if removed == 0 {
|
||||
return nil, ErrInvalidTokenSentinel
|
||||
return nil, "", "", ErrInvalidTokenSentinel
|
||||
}
|
||||
|
||||
return tm.Issue(ctx, claims.UID, claims.Subject)
|
||||
pair, newJTI, err = tm.IssueWithJTI(ctx, claims.UID, claims.Subject)
|
||||
if err != nil {
|
||||
return nil, "", "", err
|
||||
}
|
||||
return pair, claims.ID, newJTI, nil
|
||||
}
|
||||
|
||||
// Refresh validates+rotates a refresh token (JTIs discarded).
|
||||
func (tm *TokenManager) Refresh(ctx context.Context, refreshToken string) (*TokenPair, error) {
|
||||
pair, _, _, err := tm.RefreshWithJTI(ctx, refreshToken)
|
||||
return pair, err
|
||||
}
|
||||
|
||||
// Revoke removes a single refresh JTI from the whitelist (logout).
|
||||
@@ -234,6 +251,15 @@ func (tm *TokenManager) Revoke(ctx context.Context, jti string) error {
|
||||
return tm.rdb.Del(ctx, refreshKeyPrefix+jti).Err()
|
||||
}
|
||||
|
||||
// ParseRefreshJTI returns a refresh token's JTI (for session lookup on logout).
|
||||
func (tm *TokenManager) ParseRefreshJTI(refreshToken string) (string, error) {
|
||||
claims, err := tm.parse(refreshToken, typRefresh)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return claims.ID, nil
|
||||
}
|
||||
|
||||
// RevokeRefresh parses a refresh token and revokes its JTI. Used by logout.
|
||||
// Returns an error only when the token is structurally invalid; a missing or
|
||||
// already-rotated JTI is a no-op (logout is idempotent).
|
||||
|
||||
Reference in New Issue
Block a user