This repository has been archived by the owner on Jun 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
88 lines (68 loc) · 2.13 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
76
77
78
79
80
81
82
83
84
85
86
87
88
package middleware
import (
"context"
"net/http"
"github.com/efritz/nacelle"
"github.com/efritz/response"
"github.com/efritz/chevron"
)
type (
AuthMiddleware struct {
authorizer Authorizer
errorFactory ErrorFactory
forbiddenResponseFactory ResponseFactory
unauthorizedResponseFactory ErrorFactory
}
Authorizer interface {
Authorize(context.Context, *http.Request) (AuthResult, interface{}, error)
}
AuthResult int
AuthorizerFunc func(context.Context, *http.Request) (AuthResult, interface{}, error)
tokenAuthPayload string
)
var TokenAuthPayload = tokenAuthPayload("chevron.middleware.auth")
const (
AuthResultInvalid AuthResult = iota
AuthResultOK
AuthResultForbidden
AuthResultUnauthorized
)
func (f AuthorizerFunc) Authorize(ctx context.Context, req *http.Request) (AuthResult, interface{}, error) {
return f(ctx, req)
}
func NewAuthMiddleware(authorizer Authorizer, configs ...AuthMiddlewareConfigFunc) chevron.Middleware {
m := &AuthMiddleware{
authorizer: authorizer,
errorFactory: defaultErrorFactory,
forbiddenResponseFactory: defaultForbiddenResponseFactory,
unauthorizedResponseFactory: defaultUnauthorizedResponseFactory,
}
for _, f := range configs {
f(m)
}
return m
}
func (m *AuthMiddleware) Convert(f chevron.Handler) (chevron.Handler, error) {
handler := func(ctx context.Context, req *http.Request, logger nacelle.Logger) response.Response {
result, payload, err := m.authorizer.Authorize(ctx, req)
switch result {
case AuthResultForbidden:
return m.forbiddenResponseFactory()
case AuthResultUnauthorized:
return m.unauthorizedResponseFactory(err)
default:
}
if err != nil {
logger.Error("failed to invoke authorizer (%s)", err.Error())
return m.errorFactory(err)
}
return f(context.WithValue(ctx, TokenAuthPayload, payload), req, logger)
}
return handler, nil
}
func defaultForbiddenResponseFactory() response.Response {
return response.Empty(http.StatusForbidden)
}
func defaultUnauthorizedResponseFactory(err error) response.Response {
return response.Empty(http.StatusUnauthorized)
}