Ai
3 Star 0 Fork 0

salmon_go/common

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
token.go 1.66 KB
Copy Edit Raw Blame History
MikeJia authored 2021-03-19 15:03 +08:00 . 增加GORM初始化
package jwt
import (
"errors"
"time"
"github.com/dgrijalva/jwt-go"
)
const (
ErrorMessage_ValidationErrorMalformed = "无效token"
ErrorMessage_ValidationErrorExpired = "token已过期"
ErrorMessage_ValidationErrorNotValidYet = "token未激活"
)
//EncryToken 创建jwt-token
func EncryToken(user TokenUserInput, secretKey string) (r string, err error) {
claims := SgcClaims{
ID: user.ID,
Username: user.Username,
Password: user.Password,
StandardClaims: jwt.StandardClaims{
NotBefore: int64(time.Now().Unix()), // 签名生效时间
ExpiresAt: int64(time.Now().Unix() + user.Expire), // 过期时间
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
r, err = token.SignedString([]byte(secretKey))
return
}
//DecrypToken 解析jwt-token
func DecrypToken(token string, secretKey string) (claims *SgcClaims, err error) {
t, err := jwt.ParseWithClaims(token, &SgcClaims{}, func(jt *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
err = errors.New(ErrorMessage_ValidationErrorMalformed)
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
err = errors.New(ErrorMessage_ValidationErrorExpired)
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
err = errors.New(ErrorMessage_ValidationErrorNotValidYet) //还没有到达token开始时间,一般用不到
} else {
err = errors.New(ve.Error()) // 未知错误
}
return
}
}
claims, ok := t.Claims.(*SgcClaims)
if !ok || !t.Valid {
err = errors.New(ErrorMessage_ValidationErrorMalformed)
}
return
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/salmon-go/common.git
git@gitee.com:salmon-go/common.git
salmon-go
common
common
v0.0.6

Search