-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.go
53 lines (43 loc) · 1.17 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
package minion
import (
"net/http"
"regexp"
jwt "github.com/dgrijalva/jwt-go"
"github.com/go-chi/jwtauth"
)
// CreateJWTToken creates a jwt token with the given secret
func CreateJWTToken(claims jwt.Claims) (string, error) {
_, tokenString, err := tokenAuth.Encode(claims)
return tokenString, err
}
// Authenticator validates the jwt token and return 401 if not
func (c *Context) Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
unauthenticated := false
for _, path := range c.app.options.UnauthenticatedRoutes {
re := regexp.MustCompile(path)
if re.MatchString(req.URL.Path) {
unauthenticated = true
}
}
if !unauthenticated {
errResp := struct {
Code int `json:"status"`
Msg string `json:"message"`
}{
http.StatusUnauthorized,
http.StatusText(http.StatusUnauthorized),
}
token, _, err := jwtauth.FromContext(req.Context())
if err != nil {
c.render.JSON(rw, http.StatusUnauthorized, errResp)
return
}
if token == nil || !token.Valid {
c.render.JSON(rw, http.StatusUnauthorized, errResp)
return
}
}
next.ServeHTTP(rw, req)
})
}