/
token.go
43 lines (40 loc) · 1.29 KB
/
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
package server
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"pkg"
"pkg/configuration"
)
// ---- CreateToken ----
func CreateToken(userToken root.UserToken, config configuration.Configuration, exp int64) string {
var MySigningKey = []byte(config.Secret)
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["user_id"] = userToken.UserId
claims["username"] = userToken.Username
claims["email"] = userToken.Email
claims["remote_addr"] = userToken.RemoteAddr
claims["exp"] = exp
tokenString, _ := token.SignedString(MySigningKey)
return tokenString
}
// ---- DecodeJWT ----
func DecodeJWT(curToken string, config configuration.Configuration) root.UserToken {
var userToken root.UserToken
var MySigningKey = []byte(config.Secret)
token, err := jwt.Parse(curToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("error")
}
return []byte(MySigningKey), nil
})
if err != nil {
return userToken
}
tokenClaims := token.Claims.(jwt.MapClaims)
userToken.UserId = tokenClaims["user_id"].(string)
userToken.Username = tokenClaims["username"].(string)
userToken.Email = tokenClaims["email"].(string)
userToken.RemoteAddr = tokenClaims["remote_addr"].(string)
return userToken
}