package utils

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

type UserTokenClaims struct {
	UserId int64  `json:"userId"`
	Phone  string `json:"phone"`
	jwt.StandardClaims
}

var jwtSecret = []byte("123456")

//解析 UserTokenClaims
func ParseJWTToken(token string) (*UserTokenClaims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &UserTokenClaims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})
	if err != nil {
		return nil, err
	}
	if tokenClaims != nil {
		if claim, ok := tokenClaims.Claims.(*UserTokenClaims); ok && tokenClaims.Valid {
			return claim, nil
		}
	}

	return nil, err
}

//生成token
//@uid 用户变化
//@password 密码
//@expire 过期时长
func GenerateToken(uid int64, phone string, expire time.Duration) (string, error) {
	now := time.Now()
	expireTime := now.Add(expire)
	claims := UserTokenClaims{
		UserId: uid,
		Phone:  phone,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "jwt",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)
	return token, err
}