|
@@ -0,0 +1,59 @@
|
|
|
+package utils
|
|
|
+
|
|
|
+import (
|
|
|
+ "Ic_ouath/app/e"
|
|
|
+ "Ic_ouath/configs"
|
|
|
+ "errors"
|
|
|
+ "github.com/golang-jwt/jwt/v4"
|
|
|
+ "time"
|
|
|
+)
|
|
|
+
|
|
|
+type MyClaims struct {
|
|
|
+ UserId uint `json:"user_id"`
|
|
|
+ UserName string `json:"user_name"`
|
|
|
+ Role string `json:"role"`
|
|
|
+ jwt.RegisteredClaims
|
|
|
+}
|
|
|
+
|
|
|
+const TokenExpireDuration = time.Hour * 72
|
|
|
+
|
|
|
+func CreateToken(userId uint, userName, role string) (string, error) {
|
|
|
+ claims := MyClaims{
|
|
|
+ UserId: userId,
|
|
|
+ UserName: userName,
|
|
|
+ Role: role,
|
|
|
+ RegisteredClaims: jwt.RegisteredClaims{
|
|
|
+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(TokenExpireDuration)),
|
|
|
+ Issuer: configs.Config.GetString("jwt.Issuer"),
|
|
|
+ },
|
|
|
+ }
|
|
|
+ var mySerect = []byte(configs.Config.GetString("jwt.secret"))
|
|
|
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
+ return token.SignedString(mySerect)
|
|
|
+}
|
|
|
+func ParseToken(tokenStr string) (*MyClaims, e.Rescode) {
|
|
|
+ // 使用全局配置中的密钥对token进行解析。
|
|
|
+ var mySecret = []byte(configs.Config.GetString("jwt.secret"))
|
|
|
+ // 尝试解析并验证JWT令牌。
|
|
|
+ claims := new(MyClaims)
|
|
|
+ token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
|
|
|
+ return mySecret, nil
|
|
|
+ })
|
|
|
+
|
|
|
+ if err != nil {
|
|
|
+ if errors.Is(err, jwt.ErrSignatureInvalid) || errors.Is(err, jwt.ErrInvalidKey) {
|
|
|
+ return nil, e.TokenIsInvalid
|
|
|
+ } else if ve, ok := err.(*jwt.ValidationError); ok && ve.Errors&jwt.ValidationErrorExpired != 0 {
|
|
|
+ return nil, e.TokenIsExpired
|
|
|
+ }
|
|
|
+ return nil, e.TokenIsInvalid
|
|
|
+ }
|
|
|
+
|
|
|
+ // 验证令牌是否有效。
|
|
|
+ if !token.Valid {
|
|
|
+ return nil, e.TokenIsInvalid
|
|
|
+ }
|
|
|
+
|
|
|
+ // 如果令牌有效,则返回解析出的声明信息。
|
|
|
+ return claims, e.SUCCESS
|
|
|
+}
|