feat(auth): Optimized device session handling logic

- Introduced middleware to handle device sessions
- Changed `handleSession` to `HandleSession` in multiple places in `auth.go` to maintain consistent naming
- Updated response structure to return `device_key` and `token`
pull/9299/head
okatu-loli 2025-08-29 13:31:44 +08:00
parent 8623da5361
commit 9a7c82a71e
2 changed files with 12 additions and 5 deletions

View File

@ -15,6 +15,7 @@ import (
"github.com/alist-org/alist/v3/internal/session" "github.com/alist-org/alist/v3/internal/session"
"github.com/alist-org/alist/v3/internal/setting" "github.com/alist-org/alist/v3/internal/setting"
"github.com/alist-org/alist/v3/server/common" "github.com/alist-org/alist/v3/server/common"
"github.com/alist-org/alist/v3/server/middlewares"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/pquerna/otp/totp" "github.com/pquerna/otp/totp"
) )
@ -82,13 +83,18 @@ func loginHash(c *gin.Context, req *LoginReq) {
return return
} }
} }
// generate device session
if !middlewares.HandleSession(c, user) {
return
}
// generate token // generate token
token, err := common.GenerateToken(user) token, err := common.GenerateToken(user)
if err != nil { if err != nil {
common.ErrorResp(c, err, 400, true) common.ErrorResp(c, err, 400, true)
return return
} }
common.SuccessResp(c, gin.H{"token": token}) key := c.GetString("device_key")
common.SuccessResp(c, gin.H{"token": token, "device_key": key})
loginCache.Del(ip) loginCache.Del(ip)
} }

View File

@ -26,7 +26,7 @@ func Auth(c *gin.Context) {
c.Abort() c.Abort()
return return
} }
if !handleSession(c, admin) { if !HandleSession(c, admin) {
return return
} }
log.Debugf("use admin token: %+v", admin) log.Debugf("use admin token: %+v", admin)
@ -54,7 +54,7 @@ func Auth(c *gin.Context) {
} }
guest.RolesDetail = roles guest.RolesDetail = roles
} }
if !handleSession(c, guest) { if !HandleSession(c, guest) {
return return
} }
log.Debugf("use empty token: %+v", guest) log.Debugf("use empty token: %+v", guest)
@ -93,14 +93,15 @@ func Auth(c *gin.Context) {
} }
user.RolesDetail = roles user.RolesDetail = roles
} }
if !handleSession(c, user) { if !HandleSession(c, user) {
return return
} }
log.Debugf("use login token: %+v", user) log.Debugf("use login token: %+v", user)
c.Next() c.Next()
} }
func handleSession(c *gin.Context, user *model.User) bool { // HandleSession verifies device sessions and stores context values.
func HandleSession(c *gin.Context, user *model.User) bool {
clientID := c.GetHeader("Client-Id") clientID := c.GetHeader("Client-Id")
if clientID == "" { if clientID == "" {
clientID = c.Query("client_id") clientID = c.Query("client_id")