auth.go 946 字节
package domain

import (
	"github.com/dgrijalva/jwt-go"
	eggJwt "github.com/linmadan/egglib-go/utils/jwt"
	"time"
)

const (
	secret = "$^%$Rdefault&*^(*&"
)

const (
	AccessTokenExpire = 3600
)

type UserTokenClaim struct {
	jwt.StandardClaims
	UserId    int64 `json:"userId"`
	CompanyId int64 `json:"companyId"`
}

func NewUserTokenClaim(userId, companyId int64, expire int64) UserTokenClaim {
	return UserTokenClaim{
		UserId:         userId,
		CompanyId:      companyId,
		StandardClaims: jwt.StandardClaims{ExpiresAt: expire},
	}
}

func SignToken(userId int64, companyId int64) string {
	claim := NewUserTokenClaim(int64(userId), companyId, time.Now().Add(time.Second*AccessTokenExpire).Unix())
	token, _ := eggJwt.Sign(claim, secret, "")
	return token
}

func ValidToken(token string, claims *UserTokenClaim) (bool, error) {
	result, c, err := eggJwt.Valid(token, claims, secret)
	claims = c.Claims.(*UserTokenClaim)
	return result, err
}