feat(session): Added session cleanup functionality

- Added the `/clean` route to the route for session cleanup
- Added the `DeleteInactiveSessions` method to support deleting inactive sessions by user ID
- Added the `DeleteSessionByID` method to delete a specific session by session ID
- Defined the `CleanSessionsReq` request structure to support passing a user ID or session ID
- Implemented the `CleanSessions` interface logic to perform corresponding session cleanup operations based on the request parameters
pull/9315/head
okatu-loli 2025-09-09 22:06:17 +08:00
parent 2d5b8a9a61
commit af2a115547
3 changed files with 47 additions and 0 deletions

View File

@ -67,3 +67,15 @@ func ListSessions() ([]model.Session, error) {
func MarkInactive(sessionID string) error {
return errors.WithStack(db.Model(&model.Session{}).Where("device_key = ?", sessionID).Update("status", model.SessionInactive).Error)
}
func DeleteInactiveSessions(userID *uint) error {
query := db.Where("status = ?", model.SessionInactive)
if userID != nil {
query = query.Where("user_id = ?", *userID)
}
return errors.WithStack(query.Delete(&model.Session{}).Error)
}
func DeleteSessionByID(sessionID string) error {
return errors.WithStack(db.Where("device_key = ?", sessionID).Delete(&model.Session{}).Error)
}

View File

@ -40,6 +40,11 @@ type EvictSessionReq struct {
SessionID string `json:"session_id"`
}
type CleanSessionsReq struct {
UserID *uint `json:"user_id"`
SessionID string `json:"session_id"`
}
func EvictMySession(c *gin.Context) {
var req EvictSessionReq
if err := c.ShouldBindJSON(&req); err != nil {
@ -90,3 +95,32 @@ func EvictSession(c *gin.Context) {
}
common.SuccessResp(c)
}
func CleanSessions(c *gin.Context) {
var req CleanSessionsReq
if err := c.ShouldBindJSON(&req); err != nil {
common.ErrorResp(c, err, 400)
return
}
if req.SessionID != "" {
if err := db.DeleteSessionByID(req.SessionID); err != nil {
common.ErrorResp(c, err, 500)
return
}
common.SuccessResp(c)
return
}
if req.UserID != nil {
if err := db.DeleteInactiveSessions(req.UserID); err != nil {
common.ErrorResp(c, err, 500)
return
}
common.SuccessResp(c)
return
}
if err := db.DeleteInactiveSessions(nil); err != nil {
common.ErrorResp(c, err, 500)
return
}
common.SuccessResp(c)
}

View File

@ -190,6 +190,7 @@ func admin(g *gin.RouterGroup) {
session := g.Group("/session")
session.GET("/list", handles.ListSessions)
session.POST("/evict", handles.EvictSession)
session.POST("/clean", handles.CleanSessions)
}