Skip to content

Commit

Permalink
feat: invalidate token on logout (#6923 close #6792)
Browse files Browse the repository at this point in the history
  • Loading branch information
itsHenry35 authored Aug 4, 2024
1 parent a6bead9 commit 81258d3
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
23 changes: 23 additions & 0 deletions server/common/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package common
import (
"time"

"github.com/Xhofe/go-cache"
"github.com/alist-org/alist/v3/internal/conf"
"github.com/alist-org/alist/v3/internal/model"
"github.com/golang-jwt/jwt/v4"
Expand All @@ -17,6 +18,8 @@ type UserClaims struct {
jwt.RegisteredClaims
}

var validTokenCache = cache.NewMemCache[bool]()

func GenerateToken(user *model.User) (tokenString string, err error) {
claim := UserClaims{
Username: user.Username,
Expand All @@ -28,13 +31,20 @@ func GenerateToken(user *model.User) (tokenString string, err error) {
}}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
tokenString, err = token.SignedString(SecretKey)
if err != nil {
return "", err
}
validTokenCache.Set(tokenString, true)
return tokenString, err
}

func ParseToken(tokenString string) (*UserClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
return SecretKey, nil
})
if IsTokenInvalidated(tokenString) {
return nil, errors.New("token is invalidated")
}
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
Expand All @@ -53,3 +63,16 @@ func ParseToken(tokenString string) (*UserClaims, error) {
}
return nil, errors.New("couldn't handle this token")
}

func InvalidateToken(tokenString string) error {
if tokenString == "" {
return nil // don't invalidate empty guest token
}
validTokenCache.Del(tokenString)
return nil
}

func IsTokenInvalidated(tokenString string) bool {
_, ok := validTokenCache.Get(tokenString)
return !ok
}
9 changes: 9 additions & 0 deletions server/handles/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,12 @@ func Verify2FA(c *gin.Context) {
common.SuccessResp(c)
}
}

func LogOut(c *gin.Context) {
err := common.InvalidateToken(c.GetHeader("Authorization"))
if err != nil {
common.ErrorResp(c, err, 500)
} else {
common.SuccessResp(c)
}
}
1 change: 1 addition & 0 deletions server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func Init(e *gin.Engine) {
auth.POST("/me/update", handles.UpdateCurrent)
auth.POST("/auth/2fa/generate", handles.Generate2FA)
auth.POST("/auth/2fa/verify", handles.Verify2FA)
auth.GET("/auth/logout", handles.LogOut)

// auth
api.GET("/auth/sso", handles.SSOLoginRedirect)
Expand Down

0 comments on commit 81258d3

Please sign in to comment.