-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
54 lines (43 loc) · 1.1 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
44
45
46
47
48
49
50
51
52
53
54
package util
import (
"github.com/dgrijalva/jwt-go"
"github.com/ehsaniara/go-crash/config"
"time"
)
var jwtSecret []byte
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
}
// Setup Initialize the util
func Setup() {
jwtSecret = []byte(config.AppConfig.App.JwtSecret)
}
// GenerateToken generate tokens used for auth
func GenerateToken(username string) (string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(3 * time.Hour)
claims := Claims{
username,
//EncodeMD5(username),
jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "go-crash",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
// ParseJwtToken parsing token
func ParseJwtToken(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
}