login_token.go 2.3 KB
package domain

import (
	"time"

	jwt "github.com/dgrijalva/jwt-go"
)

const (
	loginTokenSecret      string = "bbe35ad433dd8e67"
	accessTokenExpiresAt  int64  = 60 * 60 * 2        //两个小时过期
	refreshTokenExpiresAt int64  = 3600 * 24 * 30 * 1 //刷新token 一个月过期
	authCodeExpire        int64  = 60 * 15            //15分钟过期
)

type LoginToken struct {
	jwt.StandardClaims
	UserId     int64 `json:"userId"`
	UserBaseId int64 `json:"userBaseId"`
	// 账号
	Account string `json:"account"`
	// 对应平台
	Platform string `json:"platform"`
	// 公司id
	CompanyId int64 `json:"companyId"`
	// 组织id
	OrgId int64 `json:"orgId"`
	// 用户关联的组织列表
	OrgIds []int64 `json:"orgIds"`
	// 会话模式 1: 短时效模式 2: 长时效模式(默认)
	SessionMode int `json:"sessionMode"`
}

func (t *LoginToken) GenerateAccessToken() (string, error) {
	nowTime := time.Now().Unix()
	t.StandardClaims = jwt.StandardClaims{
		NotBefore: nowTime,
		IssuedAt:  nowTime,
		ExpiresAt: nowTime + accessTokenExpiresAt,
		Issuer:    "allied_creation_gateway",
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, *t)
	return token.SignedString([]byte(loginTokenSecret))
}

func (t *LoginToken) GenerateRefreshToken() (string, error) {
	nowTime := time.Now().Unix()
	expire := refreshTokenExpiresAt
	if t.SessionMode == 1 {
		expire = accessTokenExpiresAt
	}
	t.StandardClaims = jwt.StandardClaims{
		NotBefore: nowTime,
		IssuedAt:  nowTime,
		ExpiresAt: nowTime + expire,
		Issuer:    "allied_creation_gateway",
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, *t)
	return token.SignedString([]byte(loginTokenSecret))
}

func (t *LoginToken) GenerateAuthCode() (string, error) {
	nowTime := time.Now().Unix()
	t.StandardClaims = jwt.StandardClaims{
		NotBefore: nowTime,
		IssuedAt:  nowTime,
		ExpiresAt: nowTime + authCodeExpire,
		Issuer:    "allied_creation_gateway",
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, *t)
	return token.SignedString([]byte(loginTokenSecret))
}

func (t *LoginToken) ParseToken(str string) error {
	tokenClaims, err := jwt.ParseWithClaims(
		str,
		t,
		func(token *jwt.Token) (interface{}, error) {
			return []byte(loginTokenSecret), nil
		})
	if err != nil {
		return err
	}
	if claim, ok := tokenClaims.Claims.(*LoginToken); ok && tokenClaims.Valid {
		*t = *claim
	}
	return nil
}