feat(session): Added device limits and eviction policies

- Added a device limit, controlling the maximum number of devices using the `MaxDevices` configuration option.
- If the number of devices exceeds the limit, the configured eviction policy is used.
- If the policy is `evict_oldest`, the oldest device is evicted.
- Otherwise, an error message indicating too many devices is returned.
pull/9301/head
okatu-loli 2025-08-29 18:19:31 +08:00
parent e940f10ebc
commit 74c963dc47
1 changed files with 21 additions and 0 deletions

View File

@ -71,6 +71,27 @@ func EnsureActiveOnLogin(userID uint, deviceKey, ua, ip string) error {
sess, err := db.GetSession(userID, deviceKey)
if err == nil {
if sess.Status == model.SessionInactive {
max := setting.GetInt(conf.MaxDevices, 0)
if max > 0 {
count, err := db.CountActiveSessionsByUser(userID)
if err != nil {
return err
}
if count >= int64(max) {
policy := setting.GetStr(conf.DeviceEvictPolicy, "deny")
if policy == "evict_oldest" {
if oldest, gerr := db.GetOldestSession(userID); gerr == nil {
if err := db.MarkInactive(oldest.DeviceKey); err != nil {
return err
}
}
} else {
return errors.WithStack(errs.TooManyDevices)
}
}
}
}
sess.Status = model.SessionActive
sess.LastActive = now
sess.UserAgent = ua