-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
86 lines (72 loc) · 1.8 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package middlewares
import (
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"inscriptio/database/models"
"inscriptio/libraries/common"
)
var secretKey []byte
func init() {
// get path from root dir
pwd, _ := os.Getwd()
keyPath := pwd + "/jwtsecret.key"
key, readErr := ioutil.ReadFile(keyPath)
if readErr != nil {
panic("failed to load secret key file")
}
secretKey = key
}
func validateToken(tokenString string) (common.JSON, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return secretKey, nil
})
if err != nil {
return common.JSON{}, err
}
if !token.Valid {
return common.JSON{}, errors.New("invalid token")
}
return token.Claims.(jwt.MapClaims), nil
}
// JWTMiddleware parses JWT token from cookie and stores data and expires date to the context
// JWT Token can be passed as cookie, or Authorization header
func JWTMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
tokenString, err := c.Cookie("token")
// failed to read cookie
if err != nil {
// try reading HTTP Header
authorization := c.Request.Header.Get("Authorization")
if authorization == "" {
c.Next()
return
}
sp := strings.Split(authorization, "Bearer ")
// invalid token
if len(sp) < 1 {
c.Next()
return
}
tokenString = sp[1]
}
tokenData, err := validateToken(tokenString)
if err != nil {
c.Next()
return
}
var user models.User
user.Read(tokenData["user"].(common.JSON))
c.Set("user", user)
c.Set("token_expire", tokenData["exp"])
c.Next()
}
}