user_auth.go 1.5 KB
package domain

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type UserAuth struct {
	jwt.StandardClaims `json:"-"`
	UserId             int64  `json:"userId"`
	CompanyId          int64  `json:"companyId"`
	Phone              string `json:"phone"`
	PlatformId         int    `json:"platformId"`
	Name               string `json:"name"`
	AdminType          int    `json:"adminType"`
}

var issuer = "performance"

var secretKey = "Ma9HXITeliSYS43Z"

var JWTExpiresSecond = 3600 * 24

// CreateAccessToken 生成token
func (userAuth *UserAuth) CreateAccessToken() (string, error) {
	userAuth.StandardClaims = jwt.StandardClaims{
		ExpiresAt: time.Now().Add(time.Duration(JWTExpiresSecond) * time.Second).Unix(),
		Issuer:    issuer,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, userAuth)
	return token.SignedString([]byte(secretKey))
}

// ParseAccessToken 解析token
func (userAuth *UserAuth) ParseAccessToken(token string) (*UserAuth, error) {
	user := &UserAuth{}
	tokenClaims, err := jwt.ParseWithClaims(token, user, func(token *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})
	if err != nil || tokenClaims == nil {
		return nil, errors.New("解析token失败")
	}
	if claim, ok := tokenClaims.Claims.(*UserAuth); ok && tokenClaims.Valid {
		user.UserId = claim.UserId
		user.CompanyId = claim.CompanyId
		user.Phone = claim.Phone
		user.PlatformId = claim.PlatformId
		user.Name = claim.Name
		user.AdminType = claim.AdminType
		return user, nil
	}
	return user, errors.New("解析token失败")
}