-
Notifications
You must be signed in to change notification settings - Fork 2
/
authMiddleware.go
164 lines (140 loc) · 4.08 KB
/
authMiddleware.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package server
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
//User represents logged-in user
type User struct {
User string
Authorities []string
}
//UserInfoErr represents error response from ReportPortal's UAT endpoint
type UserInfoErr struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
//authError represents error (response and status code) from ReportPortal's UAT endpoint
type authError struct {
errorDesc *UserInfoErr
statusCode int
}
//Error represents implementation of default golang's Error interface
func (e *authError) Error() string {
r, err := json.Marshal(e.errorDesc)
if nil != e {
return err.Error()
}
return string(r)
}
const (
authorizationHeader = "Authorization"
jsonContentType = "application/json"
bearerToken = "bearer"
unknownAuthorityWeight = 0
)
//Authorities represents available ReportPortal roles
var Authorities = map[string]int{
"ROLE_USER": 1,
"ROLE_ADMINISTRATOR": 2,
}
//RequireRole checks whether request auth represented by ReportPortal user with provided or higher role
func RequireRole(role string, authServerURL string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
authority := "ROLE_" + strings.ToUpper(role)
fn := func(w http.ResponseWriter, rq *http.Request) {
token, err := parseBearer(rq)
if err != nil || token == "" {
notAuthorized(w)
return
}
info, err := getTokenInfo(token, authServerURL)
if err != nil {
authErr, ok := err.(*authError)
if !ok {
notAuthorized(w)
} else {
respondWithError(w, authErr.statusCode, authErr.errorDesc)
}
return
}
if !hasAuthority(authority, info.Authorities) {
notAuthorized(w)
return
}
rq = rq.WithContext(setUser(rq.Context(), info))
next.ServeHTTP(w, rq)
}
return http.HandlerFunc(fn)
}
}
//notAuthorized sends 401 error to the client
func notAuthorized(w http.ResponseWriter) {
respondWithErrorString(w, http.StatusUnauthorized, "Not Authorized")
}
//respondWithErrorString wraps error with JSON ans sends 401 to the client
func respondWithErrorString(w http.ResponseWriter, code int, message string) {
respondWithError(w, code, map[string]string{"error": message})
}
//respondWithErrorString converts message JSON ans sends 401 to the client
func respondWithError(w http.ResponseWriter, code int, message interface{}) {
WriteJSON(code, message, w)
}
//parseBearer parses authorization header
func parseBearer(r *http.Request) (string, error) {
authHeader := r.Header.Get(authorizationHeader)
if "" != authHeader {
authHeaderParts := strings.Split(authHeader, " ")
if len(authHeaderParts) != 2 || bearerToken != strings.ToLower(authHeaderParts[0]) {
return "", fmt.Errorf("Authorization header format must be '%s: token'", bearerToken)
}
return authHeaderParts[1], nil
}
return r.URL.Query().Get("access_token"), nil
}
//getTokenInfo - obtains token info from ReportPortal's UAT service
func getTokenInfo(token string, authServerURL string) (*User, error) {
var netClient = &http.Client{
Timeout: time.Second * 10,
}
rq, _ := http.NewRequest("GET", authServerURL, nil)
rq.Header.Add(authorizationHeader, fmt.Sprintf("%s %s", bearerToken, token))
rq.Header.Add(contentTypeHeader, jsonContentType)
rs, e := netClient.Do(rq)
if nil != e {
return nil, e
}
defer rs.Body.Close()
if rs.StatusCode/100 > 2 {
uatErr := new(UserInfoErr)
decodeJSON(rs, uatErr)
e = &authError{
errorDesc: uatErr,
statusCode: rs.StatusCode,
}
return nil, e
}
user := new(User)
decodeJSON(rs, user)
return user, nil
}
func decodeJSON(rs *http.Response, v interface{}) error {
return json.NewDecoder(rs.Body).Decode(v)
}
//hasAuthority checks whether user authorities has at least one which has equal or higher weight than expected authority
func hasAuthority(ea string, ua []string) bool {
weight := Authorities[ea]
//Role is unknown
if unknownAuthorityWeight == weight {
return false
}
//go through
for _, r := range ua {
if Authorities[r] >= weight {
return true
}
}
return false
}