-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
executable file
·43 lines (37 loc) · 1.01 KB
/
jwt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package utility
import (
"home-server/config"
"log"
"time"
"github.com/golang-jwt/jwt"
)
type JwtData struct {
ID string `json:"id"`
jwt.StandardClaims
}
func GenerateStandardJwt(jwtData *JwtData) string {
claims := jwtData
claims.StandardClaims = jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Duration(time.Duration(config.Config.Jwt.Expires) * time.Hour)).Unix(),
Issuer: config.Config.Jwt.Issuer,
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString([]byte(config.Config.Jwt.Secret))
if err != nil {
log.Fatalln("Jwt Error", err)
panic(err)
}
return token
}
func ParseToken(token string) (string, error) {
jwtSecret := []byte(config.Config.Jwt.Secret)
tokenClaims, err := jwt.ParseWithClaims(token, &JwtData{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if tokenClaims != nil {
if claims, ok := tokenClaims.Claims.(*JwtData); ok && tokenClaims.Valid {
return claims.ID, err
}
}
return "", err
}