/
auth.go
75 lines (68 loc) · 2.17 KB
/
auth.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
package middlewares
import (
"context"
"errors"
"net/http"
"strings"
"github.com/AdhityaRamadhanus/chronicle/server/internal/contextkey"
"github.com/AdhityaRamadhanus/chronicle/server/render"
jwt "github.com/dgrijalva/jwt-go"
"github.com/spf13/viper"
)
func parseAuthorizationHeader(authHeader, scheme string) (cred string, err error) {
splittedHeader := strings.Split(authHeader, " ")
if len(splittedHeader) != 2 {
return "", errors.New("Cannot parse authorization header")
}
parsedScheme := splittedHeader[0]
if scheme != parsedScheme {
return "", errors.New("Unexpected Scheme, expected " + scheme)
}
return splittedHeader[1], nil
}
//Authenticate request
func Authenticate(nextHandler http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
authHeader, ok := req.Header["Authorization"]
if !ok || len(authHeader) == 0 {
render.JSON(res, http.StatusUnauthorized, map[string]interface{}{
"status": http.StatusUnauthorized,
"error": map[string]interface{}{
"code": "ErrInvalidAuthorizationHeader",
"message": "Authorization Header is not present",
},
})
return
}
cred, err := parseAuthorizationHeader(authHeader[0], "Bearer")
if err != nil {
render.JSON(res, http.StatusUnauthorized, map[string]interface{}{
"status": http.StatusUnauthorized,
"error": map[string]interface{}{
"code": "ErrInvalidAuthorizationHeader",
"message": err.Error(),
},
})
return
}
token, err := jwt.Parse(cred, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("Unexpected signing method")
}
return []byte(viper.GetString("jwt_secret")), nil
})
if err != nil {
render.JSON(res, http.StatusUnauthorized, map[string]interface{}{
"status": http.StatusUnauthorized,
"error": map[string]interface{}{
"code": "ErrInvalidAccessToken",
"message": err.Error(),
},
})
return
}
claims, _ := token.Claims.(jwt.MapClaims)
req = req.WithContext(context.WithValue(req.Context(), contextkey.ClientID, claims["client"].(string)))
nextHandler(res, req)
})
}