refactor(session): Filter for the user's oldest active session

- Renamed `GetOldestSession` to `GetOldestActiveSession` to more accurately reflect its functionality
- Updated the SQL query to add the `status = SessionActive` condition to retrieve only active sessions
- Replaced all callpoints and unified the new function name to ensure logical consistency
pull/9301/head
okatu-loli 2025-08-29 18:30:47 +08:00
parent 74c963dc47
commit 09147f09b5
2 changed files with 8 additions and 6 deletions

View File

@ -38,10 +38,12 @@ func DeleteSessionsBefore(ts int64) error {
return errors.WithStack(db.Where("last_active < ?", ts).Delete(&model.Session{}).Error)
}
func GetOldestSession(userID uint) (*model.Session, error) {
// GetOldestActiveSession returns the oldest active session for the specified user.
func GetOldestActiveSession(userID uint) (*model.Session, error) {
var s model.Session
if err := db.Where("user_id = ?", userID).Order("last_active ASC").First(&s).Error; err != nil {
return nil, errors.Wrap(err, "failed get oldest session")
if err := db.Where("user_id = ? AND status = ?", userID, model.SessionActive).
Order("last_active ASC").First(&s).Error; err != nil {
return nil, errors.Wrap(err, "failed get oldest active session")
}
return &s, nil
}

View File

@ -47,7 +47,7 @@ func Handle(userID uint, deviceKey, ua, ip string) error {
if count >= int64(max) {
policy := setting.GetStr(conf.DeviceEvictPolicy, "deny")
if policy == "evict_oldest" {
if oldest, err := db.GetOldestSession(userID); err == nil {
if oldest, err := db.GetOldestActiveSession(userID); err == nil {
if err := db.MarkInactive(oldest.DeviceKey); err != nil {
return err
}
@ -81,7 +81,7 @@ func EnsureActiveOnLogin(userID uint, deviceKey, ua, ip string) error {
if count >= int64(max) {
policy := setting.GetStr(conf.DeviceEvictPolicy, "deny")
if policy == "evict_oldest" {
if oldest, gerr := db.GetOldestSession(userID); gerr == nil {
if oldest, gerr := db.GetOldestActiveSession(userID); gerr == nil {
if err := db.MarkInactive(oldest.DeviceKey); err != nil {
return err
}
@ -111,7 +111,7 @@ func EnsureActiveOnLogin(userID uint, deviceKey, ua, ip string) error {
if count >= int64(max) {
policy := setting.GetStr(conf.DeviceEvictPolicy, "deny")
if policy == "evict_oldest" {
if oldest, gerr := db.GetOldestSession(userID); gerr == nil {
if oldest, gerr := db.GetOldestActiveSession(userID); gerr == nil {
if err := db.MarkInactive(oldest.DeviceKey); err != nil {
return err
}