forked from sensu/uchiwa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
accessToken.go
86 lines (73 loc) · 2.38 KB
/
accessToken.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 authentication
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/ransoni/uchiwa/uchiwa/logger"
)
// TokenLocation represents a function that accepts a request as input and returns
// either a token or an error.
type TokenLocation func(r *http.Request) (string, error)
// accessTokenFromAuthHeader retrieves an access token from the
// authentication header, e.g. token {TOKEN}
func accessTokenFromAuthHeader(r *http.Request) (string, error) {
authorization := r.Header.Get("Authorization")
if authorization == "" {
return "", nil // No token found, do not fail yet
}
authorizationComponents := strings.Split(authorization, " ")
if len(authorizationComponents) != 2 || strings.ToLower(authorizationComponents[0]) != "token" {
logger.Debug("Invalid authorization header. The format must be: token {token}")
return "", errors.New("")
}
return authorizationComponents[1], nil
}
// accessTokenFromParameter retrieves an access token from a
// URL parameter, e.g. ?token={TOKEN}
func accessTokenFromParameter(r *http.Request) (string, error) {
return r.URL.Query().Get("token"), nil
}
// findAccessToken finds the first corresponding token in the provided functions
func findAccessToken(locations ...TokenLocation) TokenLocation {
return func(r *http.Request) (string, error) {
for _, location := range locations {
token, err := location(r)
if err != nil {
return "", err
}
if token != "" {
return token, nil
}
}
return "", errors.New("")
}
}
// findRoleFromAccessToken finds within the Role slice a role with
// the corresponding token
func findRoleFromAccessToken(token string) (*Role, error) {
for _, role := range Roles {
if role.AccessToken == token {
return &role, nil
}
}
return nil, fmt.Errorf("No role found with the access token %s", token)
}
// verifyAccessToken extracts the access token and verifies it, then
// returns a JWT with the associated role
func verifyAccessToken(r *http.Request) (*jwt.Token, error) {
locations := findAccessToken(accessTokenFromAuthHeader, accessTokenFromParameter)
accessToken, err := locations(r)
if err != nil {
return nil, errors.New("")
}
role, err := findRoleFromAccessToken(accessToken)
if err != nil {
return nil, errors.New("")
}
token := jwt.New(jwt.GetSigningMethod("RS256"))
token.Claims["Role"] = role
token.Claims["Username"] = role.Name
return token, nil
}