mirror of
https://github.com/lzh-1625/go_process_manager.git
synced 2025-10-01 06:12:07 +08:00
60 lines
1.1 KiB
Go
60 lines
1.1 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
var jwtKey []byte
|
|
|
|
type MyClaims struct {
|
|
Username string `json:"username"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func SetSecret(secret []byte) {
|
|
jwtKey = []byte(secret)
|
|
}
|
|
|
|
func GenerateToken(username string) (string, error) {
|
|
expirationTime := time.Now().Add(3 * 24 * time.Hour)
|
|
|
|
claims := &MyClaims{
|
|
Username: username,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(expirationTime),
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
NotBefore: jwt.NewNumericDate(time.Now()),
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
tokenString, err := token.SignedString(jwtKey)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return tokenString, nil
|
|
}
|
|
|
|
func VerifyToken(tokenString string) (*MyClaims, error) {
|
|
claims := &MyClaims{}
|
|
|
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
|
return jwtKey, nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if !token.Valid {
|
|
return nil, fmt.Errorf("invalid token")
|
|
}
|
|
|
|
return claims, nil
|
|
}
|