-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmiddleware_auth.go
309 lines (258 loc) · 7.76 KB
/
middleware_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
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package gimlet
import (
"context"
"net/http"
)
// NewAuthenticationHandler produces middleware that attaches
// Authenticator and UserManager instances to the request context,
// enabling the use of GetAuthenticator and GetUserManager accessors.
//
// While your application can have multiple authentication mechanisms,
// a single request can only have one authentication provider
// associated with it.
func NewAuthenticationHandler(a Authenticator, um UserManager) Middleware {
return &authHandler{
auth: a,
um: um,
}
}
type authHandler struct {
auth Authenticator
um UserManager
}
func (a *authHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
ctx := r.Context()
ctx = setAuthenticator(ctx, a.auth)
ctx = setUserManager(ctx, a.um)
r = r.WithContext(ctx)
next(rw, r)
}
func setAuthenticator(ctx context.Context, a Authenticator) context.Context {
return context.WithValue(ctx, authHandlerKey, a)
}
func setUserManager(ctx context.Context, um UserManager) context.Context {
return context.WithValue(ctx, userManagerKey, um)
}
// GetAuthenticator returns an the attached interface to the
// context. If there is no authenticator attached, then
// GetAutenticator returns nil.
func GetAuthenticator(ctx context.Context) Authenticator {
a := ctx.Value(authHandlerKey)
if a == nil {
return nil
}
amgr, ok := a.(Authenticator)
if !ok {
return nil
}
return amgr
}
// GetUserManager returns the attached UserManager to the current
// request, returning nil if no such object is attached.
func GetUserManager(ctx context.Context) UserManager {
m := ctx.Value(userManagerKey)
if m == nil {
return nil
}
umgr, ok := m.(UserManager)
if !ok {
return nil
}
return umgr
}
// NewRoleRequired provides middlesware that requires a specific role
// to access a resource. This access is defined as a property of the
// user objects.
func NewRoleRequired(role string) Middleware { return &requiredRole{role: role} }
type requiredRole struct {
role string
}
func (rr *requiredRole) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
ctx := r.Context()
user := GetUser(ctx)
if user == nil {
rw.WriteHeader(http.StatusUnauthorized)
return
}
if !userHasRole(user, rr.role) {
rw.WriteHeader(http.StatusUnauthorized)
return
}
next(rw, r)
}
// NewGroupMembershipRequired provides middleware that requires that
// users belong to a group to gain access to a resource. This is
// access is defined as a property of the authentication system.
func NewGroupMembershipRequired(name string) Middleware { return &requiredGroup{group: name} }
type requiredGroup struct {
group string
}
func (rg *requiredGroup) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
ctx := r.Context()
authenticator := GetAuthenticator(ctx)
if authenticator == nil {
rw.WriteHeader(http.StatusUnauthorized)
return
}
user := GetUser(ctx)
if user == nil {
rw.WriteHeader(http.StatusUnauthorized)
return
}
if !authenticator.CheckGroupAccess(user, rg.group) {
rw.WriteHeader(http.StatusUnauthorized)
return
}
next(rw, r)
}
// NewRequireAuthHandler provides middlesware that requires that users be
// authenticated generally to access the resource, but does no
// validation of their access.
func NewRequireAuthHandler() Middleware { return &requireAuthHandler{} }
type requireAuthHandler struct{}
func (*requireAuthHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
ctx := r.Context()
authenticator := GetAuthenticator(ctx)
if authenticator == nil {
rw.WriteHeader(http.StatusUnauthorized)
return
}
user := GetUser(ctx)
if user == nil {
rw.WriteHeader(http.StatusUnauthorized)
return
}
if !authenticator.CheckAuthenticated(user) {
rw.WriteHeader(http.StatusUnauthorized)
return
}
next(rw, r)
}
// NewRestrictAccessToUsers allows you to define a list of users that
// may access certain resource. This is similar to "groups," but allows
// you to control access centrally rather than needing to edit or
// change user documents.
//
// This middleware is redundant to the "access required middleware."
func NewRestrictAccessToUsers(userIDs []string) Middleware {
return &restrictedAccessHandler{ids: userIDs}
}
type restrictedAccessHandler struct {
ids []string
}
func (ra *restrictedAccessHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
ctx := r.Context()
user := GetUser(ctx)
if user == nil {
rw.WriteHeader(http.StatusUnauthorized)
return
}
authenticator := GetAuthenticator(ctx)
if authenticator == nil {
rw.WriteHeader(http.StatusUnauthorized)
return
}
if !authenticator.CheckAuthenticated(user) {
rw.WriteHeader(http.StatusUnauthorized)
return
}
id := user.Username()
for _, allowed := range ra.ids {
if id == allowed {
next(rw, r)
return
}
}
rw.WriteHeader(http.StatusUnauthorized)
}
type requiresPermissionHandler struct {
opts RequiresPermissionMiddlewareOpts
}
type FindResourceFunc func(*http.Request) ([]string, int, error)
// RequiresPermissionMiddlewareOpts defines what permissions the middleware shoud check and how. The ResourceFunc parameter
// can be used to specify custom behavior to extract a valid resource name from request variables
type RequiresPermissionMiddlewareOpts struct {
RM RoleManager
PermissionKey string
ResourceType string
RequiredLevel int
ResourceLevels []string
DefaultRoles []Role
ResourceFunc FindResourceFunc
}
// RequiresPermission allows a route to specify that access to a given resource in the route requires a certain permission
// at a certain level. The resource ID must be defined somewhere in the URL as mux.Vars. The specific URL params to check
// need to be sent in the last parameter of this function, in order of most to least specific
func RequiresPermission(opts RequiresPermissionMiddlewareOpts) Middleware {
return &requiresPermissionHandler{
opts: opts,
}
}
func (rp *requiresPermissionHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
vars := GetVars(r)
var resources []string
var status int
var err error
if rp.opts.ResourceFunc != nil {
resources, status, err = rp.opts.ResourceFunc(r)
if err != nil {
http.Error(rw, err.Error(), status)
return
}
} else {
for _, level := range rp.opts.ResourceLevels {
if resourceVal, exists := vars[level]; exists {
resources = []string{resourceVal}
break
}
}
}
if len(resources) == 0 {
http.Error(rw, "no resources found", http.StatusNotFound)
return
}
if ok := rp.checkPermissions(rw, r.Context(), resources); !ok {
return
}
next(rw, r)
}
func (rp *requiresPermissionHandler) checkPermissions(rw http.ResponseWriter, ctx context.Context, resources []string) bool {
user := GetUser(ctx)
opts := PermissionOpts{
ResourceType: rp.opts.ResourceType,
Permission: rp.opts.PermissionKey,
RequiredLevel: rp.opts.RequiredLevel,
}
if user == nil {
for _, item := range resources {
opts.Resource = item
if rp.opts.DefaultRoles != nil {
if !HasPermission(rp.opts.RM, opts, rp.opts.DefaultRoles) {
http.Error(rw, "not authorized for this action", http.StatusUnauthorized)
return false
}
return true
}
http.Error(rw, "no user found", http.StatusUnauthorized)
return false
}
return true
}
authenticator := GetAuthenticator(ctx)
if authenticator == nil {
http.Error(rw, "unable to determine an authenticator", http.StatusInternalServerError)
return false
}
if !authenticator.CheckAuthenticated(user) {
http.Error(rw, "not authenticated", http.StatusUnauthorized)
return false
}
for _, item := range resources {
opts.Resource = item
if !user.HasPermission(opts) {
http.Error(rw, "not authorized for this action", http.StatusUnauthorized)
return false
}
}
return true
}