-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
51 lines (47 loc) · 1.27 KB
/
middleware.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
package main
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/context"
)
// JwtToken a session token
type JwtToken struct {
Token string `json:"token"`
}
// ValidateMiddleware middleware to validate session from authorization header
func (s *Service) ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
authorizationHeader := req.Header.Get("authorization")
if authorizationHeader != "" {
bearerToken := strings.Split(authorizationHeader, " ")
if len(bearerToken) == 2 {
token, err := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error with token")
}
return s.TokenSigningKey, nil
})
if err != nil {
fmt.Println(err)
http.Error(w, "", 403)
return
}
if token.Valid {
context.Set(req, "decoded", token.Claims)
next(w, req)
} else {
fmt.Println(errors.New("invalid authorization token"))
http.Error(w, "", 403)
return
}
}
} else {
fmt.Println(errors.New("an authorization header is required"))
http.Error(w, "", 403)
return
}
})
}