Files
open-im-server/src/utils/jwt_token.go
T

160 lines
4.4 KiB
Go
Raw Normal View History

2021-05-26 19:35:56 +08:00
package utils
import (
"Open_IM/src/common/config"
"Open_IM/src/common/db"
"errors"
2021-10-22 21:20:31 +08:00
"github.com/golang-jwt/jwt/v4"
2021-05-26 19:35:56 +08:00
"time"
)
var (
TokenExpired = errors.New("token is timed out, please log in again")
TokenInvalid = errors.New("token has been invalidated")
TokenNotValidYet = errors.New("token not active yet")
TokenMalformed = errors.New("that's not even a token")
TokenUnknown = errors.New("couldn't handle this token")
)
type Claims struct {
UID string
Platform string //login platform
jwt.StandardClaims
}
2021-10-22 21:20:31 +08:00
func BuildClaims(uid, platform string, ttl int64) Claims {
2021-05-26 19:35:56 +08:00
now := time.Now().Unix()
//if ttl=-1 Permanent token
2021-10-22 18:49:44 +08:00
expiresAt := int64(-1)
if ttl != -1 {
expiresAt = now + ttl
2021-05-26 19:35:56 +08:00
}
2021-10-22 18:49:44 +08:00
2021-05-26 19:35:56 +08:00
return Claims{
UID: uid,
Platform: platform,
StandardClaims: jwt.StandardClaims{
2021-10-22 18:49:44 +08:00
ExpiresAt: expiresAt, //Expiration time
2021-05-26 19:35:56 +08:00
IssuedAt: now, //Issuing time
NotBefore: now, //Begin Effective time
}}
}
2021-10-22 21:20:31 +08:00
func CreateToken(userID string, platform int32) (string, int64, error) {
claims := BuildClaims(userID, PlatformIDToName(platform), config.Config.TokenPolicy.AccessExpire)
2021-05-26 19:35:56 +08:00
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(config.Config.TokenPolicy.AccessSecret))
return tokenString, claims.ExpiresAt, err
}
func secret() jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
return []byte(config.Config.TokenPolicy.AccessSecret), nil
}
}
2021-10-22 18:49:44 +08:00
func getClaimFromToken(tokensString string) (*Claims, error) {
2021-05-26 19:35:56 +08:00
token, err := jwt.ParseWithClaims(tokensString, &Claims{}, secret())
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, TokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
return nil, TokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, TokenNotValidYet
} else {
return nil, TokenUnknown
}
}
}
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
2021-10-22 18:49:44 +08:00
return claims, nil
}
return nil, err
}
func ParseToken(tokensString string) (claims *Claims, err error) {
claims, err = getClaimFromToken(tokensString)
if err != nil {
return nil, err
}
// 1.check userid and platform class 0 not exists and 1 exists
existsInterface, err := db.DB.ExistsUserIDAndPlatform(claims.UID, Platform2class[claims.Platform])
if err != nil {
return nil, err
}
exists := existsInterface.(int64)
//get config multi login policy
if config.Config.MultiLoginPolicy.OnlyOneTerminalAccess {
//OnlyOneTerminalAccess policy need to check all terminal
//When only one end is allowed to log in, there is a situation that needs to be paid attention to. After PC login,
//mobile login should check two platform times. One of them is less than the redis storage time, which is the invalid token.
platform := "PC"
if Platform2class[claims.Platform] == "PC" {
platform = "Mobile"
}
existsInterface, err = db.DB.ExistsUserIDAndPlatform(claims.UID, platform)
2021-05-26 19:35:56 +08:00
if err != nil {
return nil, err
}
2021-10-22 18:49:44 +08:00
exists = existsInterface.(int64)
if exists == 1 {
res, err := MakeTheTokenInvalid(*claims, platform)
if err != nil {
return nil, err
2021-05-26 19:35:56 +08:00
}
2021-10-22 18:49:44 +08:00
if res {
return nil, TokenInvalid
2021-05-26 19:35:56 +08:00
}
}
}
2021-10-22 18:49:44 +08:00
// config.Config.MultiLoginPolicy.MobileAndPCTerminalAccessButOtherTerminalKickEachOther == true
// or PC/Mobile validate success
// final check
if exists == 1 {
res, err := MakeTheTokenInvalid(*claims, Platform2class[claims.Platform])
if err != nil {
return nil, err
}
if res {
return nil, TokenInvalid
}
}
return claims, nil
2021-05-26 19:35:56 +08:00
}
func MakeTheTokenInvalid(currentClaims Claims, platformClass string) (bool, error) {
storedRedisTokenInterface, err := db.DB.GetPlatformToken(currentClaims.UID, platformClass)
if err != nil {
return false, err
}
storedRedisPlatformClaims, err := ParseRedisInterfaceToken(storedRedisTokenInterface)
if err != nil {
return false, err
}
//if issue time less than redis token then make this token invalid
if currentClaims.IssuedAt < storedRedisPlatformClaims.IssuedAt {
return true, TokenInvalid
}
return false, nil
}
2021-10-22 18:49:44 +08:00
2021-05-26 19:35:56 +08:00
func ParseRedisInterfaceToken(redisToken interface{}) (*Claims, error) {
2021-10-22 18:49:44 +08:00
return getClaimFromToken(string(redisToken.([]uint8)))
2021-05-26 19:35:56 +08:00
}
//Validation token, false means failure, true means successful verification
func VerifyToken(token, uid string) bool {
claims, err := ParseToken(token)
2021-10-22 18:49:44 +08:00
if err != nil || claims.UID != uid {
2021-05-26 19:35:56 +08:00
return false
}
2021-10-22 18:49:44 +08:00
return true
2021-05-26 19:35:56 +08:00
}