-
Notifications
You must be signed in to change notification settings - Fork 16
/
sec_token.go
60 lines (55 loc) · 1.23 KB
/
sec_token.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
55
56
57
58
59
60
package main
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
// Create Token
// Example:
/*
newToken, _ := createToken("Hide", "[email protected]")
log.Print("Token: ", newToken)
*/
func createToken(user string, email string) (string, error) {
exp, err := time.ParseDuration(config.tokenExp)
if err != nil {
return "", err
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user,
"email": email,
"iat": time.Now().Unix(),
"exp": time.Now().Add(exp).Unix(),
})
s, err := token.SignedString([]byte(config.tokenSecret))
if err != nil {
return "", err
}
return s, nil
}
// Verify Token
// Example:
/*
info, err := verifyToken(newToken)
if err != nil {
log.Print("Token invalid")
} else {
log.Print(info)
}
*/
func verifyToken(tokenString string) (jwt.MapClaims, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return false, fmt.Errorf("There was an error")
}
return []byte(config.tokenSecret), nil
})
if err != nil {
return nil, err
}
if token.Valid == true {
return token.Claims.(jwt.MapClaims), err
} else {
return nil, fmt.Errorf("Token invalid.")
}
}