2019-08-07 20:56:20 +08:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
2019-08-12 21:05:20 +08:00
|
|
|
"fmt"
|
2019-08-07 20:56:20 +08:00
|
|
|
"github.com/dgrijalva/jwt-go"
|
2019-08-12 21:05:20 +08:00
|
|
|
"github.com/google/uuid"
|
2019-08-07 20:56:20 +08:00
|
|
|
"github.com/viletyy/potato/pkg/setting"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var jwtSecret = []byte(setting.JwtSecret)
|
|
|
|
|
|
|
|
type Claims struct {
|
|
|
|
Username string `json:"username"`
|
|
|
|
Password string `json:"password"`
|
|
|
|
jwt.StandardClaims
|
|
|
|
}
|
|
|
|
|
|
|
|
func GenerateToken(username, password string) (string, error) {
|
|
|
|
nowTime := time.Now()
|
2019-08-12 21:05:20 +08:00
|
|
|
expireTime := nowTime.Add(time.Minute * 30)
|
|
|
|
loginUUID := uuid.New().String()
|
2019-08-07 20:56:20 +08:00
|
|
|
|
|
|
|
claims := Claims{
|
|
|
|
Username: username,
|
|
|
|
Password: password,
|
|
|
|
StandardClaims: jwt.StandardClaims{
|
|
|
|
ExpiresAt: expireTime.Unix(),
|
2019-08-12 21:05:20 +08:00
|
|
|
Issuer : "data_govern",
|
|
|
|
Id : loginUUID,
|
2019-08-07 20:56:20 +08:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
token, err := tokenClaims.SignedString(jwtSecret)
|
2019-08-12 21:05:20 +08:00
|
|
|
result, err := Redis.Set("login:" + loginUUID, username, 1*time.Hour).Result()
|
|
|
|
fmt.Println(result, err)
|
2019-08-07 20:56:20 +08:00
|
|
|
|
|
|
|
return token, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func ParseToken(token string) (*Claims, error) {
|
|
|
|
tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
|
|
|
return jwtSecret, nil
|
|
|
|
})
|
|
|
|
|
|
|
|
if tokenClaims != nil {
|
|
|
|
if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
|
|
|
|
return claims, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
}
|