package JWT import ( "encoding/json" "errors" "github.com/dgrijalva/jwt-go" "go.mongodb.org/mongo-driver/bson/primitive" "letu/Config" "letu/DB" "time" ) func CreateToken(user *DB.SMember, exp int64) (tokenss string, err error) { //自定义claim auth, _ := json.Marshal(user.Auth) claim := jwt.MapClaims{ "id": user.Id, "username": user.Username, "userType": user.UserType, "scenicId": user.ScenicId, "auth": string(auth), "nbf": time.Now().Unix(), "iat": time.Now().Unix(), "exp": exp, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim) tokenss, err = token.SignedString([]byte(Config.Info.TokenSecret)) return } func secret() jwt.Keyfunc { return func(token *jwt.Token) (interface{}, error) { return []byte(Config.Info.TokenSecret), nil } } func CheckToken(tokenss string) (err error) { _, err = jwt.Parse(tokenss, secret()) return err } func ParseToken(tokenss string) (user *DB.SMember, err error) { user = &DB.SMember{} token, err := jwt.Parse(tokenss, secret()) if err != nil { return } claim, ok := token.Claims.(jwt.MapClaims) if !ok { err = errors.New("cannot convert claim to mapclaim") return } //验证token,如果token被修改过则为false if !token.Valid { err = errors.New("token is invalid") return } id, _ := primitive.ObjectIDFromHex(claim["id"].(string)) user.Id = &id user.Username = claim["username"].(string) user.UserType = claim["userType"].(string) user.ScenicId = claim["scenicId"].(string) var jsons []string json.Unmarshal([]byte(claim["auth"].(string)), &jsons) user.Auth = jsons return }