feat(session): Added session list functionality with usernames

- Added the `SessionWithUser` structure, which includes `Session` and `Username` fields.
- Added the `ListSessionsWithUser` function, which queries and returns a list of sessions with usernames.
- Used a `JOIN` operation to join the session and user tables to retrieve the username associated with each session.
- Changed `ListSessions` to `ListSessionsWithUser` to ensure that the username is retrieved.
pull/9315/head
okatu-loli 2025-09-09 22:26:40 +08:00
parent af2a115547
commit 3fc0859037
2 changed files with 22 additions and 1 deletions

View File

@ -1,11 +1,17 @@
package db
import (
"github.com/alist-org/alist/v3/internal/conf"
"github.com/alist-org/alist/v3/internal/model"
"github.com/pkg/errors"
"gorm.io/gorm/clause"
)
type SessionWithUser struct {
model.Session
Username string
}
func GetSession(userID uint, deviceKey string) (*model.Session, error) {
s := model.Session{UserID: userID, DeviceKey: deviceKey}
if err := db.Select("user_id, device_key, last_active, status, user_agent, ip").Where(&s).First(&s).Error; err != nil {
@ -64,6 +70,19 @@ func ListSessions() ([]model.Session, error) {
return sessions, errors.WithStack(err)
}
func ListSessionsWithUser() ([]SessionWithUser, error) {
var sessions []SessionWithUser
sessionTable := conf.Conf.Database.TablePrefix + "sessions"
userTable := conf.Conf.Database.TablePrefix + "users"
err := db.Table(sessionTable).
Select(sessionTable+".user_id, "+sessionTable+".device_key, "+sessionTable+".last_active, "+
sessionTable+".status, "+sessionTable+".user_agent, "+sessionTable+".ip, "+userTable+".username").
Joins("JOIN "+userTable+" ON "+sessionTable+".user_id = "+userTable+".id").
Where(sessionTable+".status = ?", model.SessionActive).
Scan(&sessions).Error
return sessions, errors.WithStack(err)
}
func MarkInactive(sessionID string) error {
return errors.WithStack(db.Model(&model.Session{}).Where("device_key = ?", sessionID).Update("status", model.SessionInactive).Error)
}

View File

@ -10,6 +10,7 @@ import (
type SessionResp struct {
SessionID string `json:"session_id"`
UserID uint `json:"user_id,omitempty"`
Username string `json:"username,omitempty"`
LastActive int64 `json:"last_active"`
Status int `json:"status"`
UA string `json:"ua"`
@ -64,7 +65,7 @@ func EvictMySession(c *gin.Context) {
}
func ListSessions(c *gin.Context) {
sessions, err := db.ListSessions()
sessions, err := db.ListSessionsWithUser()
if err != nil {
common.ErrorResp(c, err, 500)
return
@ -74,6 +75,7 @@ func ListSessions(c *gin.Context) {
resp[i] = SessionResp{
SessionID: s.DeviceKey,
UserID: s.UserID,
Username: s.Username,
LastActive: s.LastActive,
Status: s.Status,
UA: s.UserAgent,