forked from cperfect/hydra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
warden_http.go
77 lines (65 loc) · 2.22 KB
/
warden_http.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
package warden
import (
"net/http"
"net/url"
"context"
"github.com/ory/fosite"
"github.com/ory/hydra/firewall"
"github.com/ory/hydra/pkg"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
type HTTPWarden struct {
Client *http.Client
Dry bool
Endpoint *url.URL
}
func (w *HTTPWarden) TokenFromRequest(r *http.Request) string {
return fosite.AccessTokenFromRequest(r)
}
func (w *HTTPWarden) SetClient(c *clientcredentials.Config) {
w.Client = c.Client(oauth2.NoContext)
}
// TokenAllowed checks if a token is valid and if the token owner is allowed to perform an action on a resource.
// This endpoint requires a token, a scope, a resource name, an action name and a context.
//
// The HTTP API is documented at http://docs.hydra13.apiary.io/#reference/warden:-access-control-for-resource-providers/check-if-an-access-tokens-subject-is-allowed-to-do-something
func (w *HTTPWarden) TokenAllowed(ctx context.Context, token string, a *firewall.TokenAccessRequest, scopes ...string) (*firewall.Context, error) {
var resp = struct {
*firewall.Context
Allowed bool `json:"allowed"`
}{}
var ep = *w.Endpoint
ep.Path = TokenAllowedHandlerPath
agent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client}
if err := agent.POST(&wardenAccessRequest{
wardenAuthorizedRequest: &wardenAuthorizedRequest{
Token: token,
Scopes: scopes,
},
TokenAccessRequest: a,
}, &resp); err != nil {
return nil, err
} else if !resp.Allowed {
return nil, errors.New("Token is not valid")
}
return resp.Context, nil
}
// IsAllowed checks if an arbitrary subject is allowed to perform an action on a resource.
//
// The HTTP API is documented at http://docs.hydra13.apiary.io/#reference/warden:-access-control-for-resource-providers/check-if-a-subject-is-allowed-to-do-something
func (w *HTTPWarden) IsAllowed(ctx context.Context, a *firewall.AccessRequest) error {
var allowed = struct {
Allowed bool `json:"allowed"`
}{}
var ep = *w.Endpoint
ep.Path = AllowedHandlerPath
agent := &pkg.SuperAgent{URL: ep.String(), Client: w.Client}
if err := agent.POST(a, &allowed); err != nil {
return err
} else if !allowed.Allowed {
return errors.Wrap(fosite.ErrRequestForbidden, "")
}
return nil
}