对接
This commit is contained in:
@@ -43,6 +43,33 @@ func AuthenticateWebSocket(c *gin.Context, auth TokenAuthenticator) bool {
|
||||
return authenticate(c, auth, true)
|
||||
}
|
||||
|
||||
// AuthenticateWebSocketOptional enriches a public WebSocket connection when
|
||||
// a valid token is available. Missing, expired, malformed, or revoked tokens
|
||||
// fall back to an anonymous session; invalid cookie state is cleared so a
|
||||
// stale login cannot prevent public live viewing.
|
||||
func AuthenticateWebSocketOptional(c *gin.Context, auth TokenAuthenticator) bool {
|
||||
token := RequestToken(c, true)
|
||||
if token == "" || auth == nil {
|
||||
return false
|
||||
}
|
||||
value, err, _ := refreshTokens.Do(token, func() (any, error) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(c.Request.Context()), tokenAuthTimeout)
|
||||
defer cancel()
|
||||
return auth.AuthenticateToken(ctx, token)
|
||||
})
|
||||
if err != nil {
|
||||
httpx.SetCookie(c, "x-token", "", -1)
|
||||
return false
|
||||
}
|
||||
authentication, ok := value.(*system.TokenAuthentication)
|
||||
if !ok || authentication == nil || authentication.Claims == nil {
|
||||
httpx.SetCookie(c, "x-token", "", -1)
|
||||
return false
|
||||
}
|
||||
applyTokenAuthentication(c, authentication)
|
||||
return true
|
||||
}
|
||||
|
||||
func authenticate(c *gin.Context, auth TokenAuthenticator, allowQueryToken bool) bool {
|
||||
token := RequestToken(c, allowQueryToken)
|
||||
if token == "" {
|
||||
@@ -74,13 +101,17 @@ func authenticate(c *gin.Context, auth TokenAuthenticator, allowQueryToken bool)
|
||||
httpx.NoAuth(c, "无法处理此token")
|
||||
return false
|
||||
}
|
||||
applyTokenAuthentication(c, authentication)
|
||||
return true
|
||||
}
|
||||
|
||||
func applyTokenAuthentication(c *gin.Context, authentication *system.TokenAuthentication) {
|
||||
if authentication.Refreshed != nil {
|
||||
c.Header("new-token", authentication.Refreshed.Value)
|
||||
c.Header("new-expires-at", strconv.FormatInt(authentication.Refreshed.ExpiresAt.Unix(), 10))
|
||||
httpx.SetCookie(c, "x-token", authentication.Refreshed.Value, int(authentication.Refreshed.TTL.Seconds()))
|
||||
}
|
||||
c.Set(claimsKey, authentication.Claims)
|
||||
return true
|
||||
}
|
||||
|
||||
// RequestToken extracts the authentication token accepted by HTTP handlers.
|
||||
|
||||
Reference in New Issue
Block a user