package xtoken import ( "context" "encoding/json" "errors" "git.diulo.com/mogfee/protoc-gen-kit/pkg/jwts" "git.diulo.com/mogfee/protoc-gen-kit/pkg/xaes" "git.diulo.com/mogfee/protoc-gen-kit/pkg/xbase64" "github.com/dgrijalva/jwt-go" "time" ) const ( // expiredTime 授权结束时间 expiredTime = 7200 tokenKey = "68Tz&xWUW5U$Id45" ) type TokenInfo struct { Id int64 Permission []string } var tokenExpired = errors.New("token expired") type tokenStoreInfo struct { Created int64 `json:"created"` ExpiredAt int64 `json:"expired_at"` Id int64 `json:"id"` Permission []string `json:"permission"` } func GetTokenStr(ctx context.Context, info TokenInfo) (string, error) { ctime := time.Now().Unix() tokenString, err := jwts.JWTGetMapString(jwt.MapClaims{ "id": info.Id, "permission": info.Permission, "created": ctime, "expired_at": ctime + expiredTime, }) if err != nil { return "", err } aesString, err := xaes.Encrypt([]byte(tokenString), []byte(tokenKey)) if err != nil { return "", err } return xbase64.Encode(string(aesString)), nil } func ParseToken(tokenStr string) (*TokenInfo, error) { tokenStr, err := xbase64.Decode(tokenStr) if err != nil { return nil, err } body, err := xaes.Decrypt([]byte(tokenStr), []byte(tokenKey)) if err != nil { return nil, err } mps, err := jwts.JWTGetStringMap(string(body)) if err != nil { return nil, errors.New("token parse error") } b, _ := json.Marshal(mps) row := tokenStoreInfo{} if err = json.Unmarshal(b, &row); err != nil { return nil, err } if row.ExpiredAt < time.Now().Unix() || row.Id <= 0 { return nil, tokenExpired } return &TokenInfo{ Id: row.Id, Permission: row.Permission, }, nil } func IsExpired(err error) bool { return err == tokenExpired }