审查视图

pkg/domain/user_auth.go 1.6 KB
庄敏学 authored
1 2 3 4 5
package domain

import (
	"errors"
	"time"
6 7

	"github.com/dgrijalva/jwt-go"
庄敏学 authored
8 9 10 11 12 13
)

type UserAuth struct {
	jwt.StandardClaims `json:"-"`
	UserId             int64  `json:"userId"`
	CompanyId          int64  `json:"companyId"`
14
	CompanyName        string `json:"companyName"`
庄敏学 authored
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	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
tangxvhui authored
53
		user.CompanyName = claim.CompanyName
庄敏学 authored
54 55 56 57
		return user, nil
	}
	return user, errors.New("解析token失败")
}