user_token.go 1.2 KB
package domain

import (
	"errors"
	jwt "github.com/dgrijalva/jwt-go"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
	"time"
)

type UserToken struct {
	UserId      int64 `json:"userId"`
	CompanyId   int64 `json:"companyId"`
	CompanyType int   `json:"companyType"`
	jwt.StandardClaims
}

func (tk UserToken) GenerateToken() (string, error) {
	tk.StandardClaims = jwt.StandardClaims{
		ExpiresAt: time.Now().Add(time.Duration(constant.JWTExpiresIn) * time.Second).Unix(),
		Issuer:    "digital-platform",
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, tk)
	return token.SignedString([]byte(constant.JWTSecretKey))
}

func (tk *UserToken) ParseToken(str string) error {
	tokenClaims, err := jwt.ParseWithClaims(
		str,
		tk,
		func(token *jwt.Token) (interface{}, error) {
			return []byte(constant.JWTSecretKey), nil
		})
	if err != nil {
		return err
	}
	if claim, ok := tokenClaims.Claims.(*UserToken); ok && tokenClaims.Valid {
		*tk = *claim
		return nil
	}
	return errors.New("token 解析失败")
}

// CheckUserInfo 如果UserToken有效 返回:true 否则返回false
func (tk *UserToken) CheckUserInfo() bool {
	return !(tk.UserId > 100000000 || tk.UserId <= 0)
}