package utils

import (
	"errors"

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

var tokenSignedKey = []byte(`Yansen is so handsome!`)

// CreateToken 获取token
func CreateToken(info map[string]interface{}) (string, error) {
	claims := jwt.MapClaims(info)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(tokenSignedKey)
}

// PareseToken 解析 token
func PareseToken(token string) (map[string]interface{}, error) {
	tk, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
		return tokenSignedKey, nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := tk.Claims.(jwt.MapClaims); ok && tk.Valid {
		info := map[string]interface{}(claims)
		return info, nil
	}

	return nil, errors.New("Token 解析 未知错误")
}
