-
Notifications
You must be signed in to change notification settings - Fork 13
/
auth.go
71 lines (62 loc) · 1.7 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
package interceptor
import (
"context"
"fmt"
"github.com/tdex-network/tdex-daemon/internal/interfaces/grpc/permissions"
"github.com/tdex-network/tdex-daemon/pkg/macaroons"
"google.golang.org/grpc"
)
func unaryMacaroonAuthHandler(
macaroonSvc *macaroons.Service,
) grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
if err := checkMacaroon(ctx, info.FullMethod, macaroonSvc); err != nil {
return nil, err
}
return handler(ctx, req)
}
}
func streamMacaroonAuthHandler(
macaroonSvc *macaroons.Service,
) grpc.StreamServerInterceptor {
return func(
srv interface{},
ss grpc.ServerStream,
info *grpc.StreamServerInfo,
handler grpc.StreamHandler,
) error {
if err := checkMacaroon(ss.Context(), info.FullMethod, macaroonSvc); err != nil {
return err
}
return handler(srv, ss)
}
}
func checkMacaroon(
ctx context.Context, fullMethod string, svc *macaroons.Service,
) error {
if svc == nil {
return nil
}
// Check whether the method is whitelisted, if so we'll allow it regardless
// of macaroons.
if _, ok := permissions.Whitelist()[fullMethod]; ok {
return nil
}
uriPermissions, ok := permissions.AllPermissionsByMethod()[fullMethod]
if !ok {
return fmt.Errorf("%s: unknown permissions required for method", fullMethod)
}
// Find out if there is an external validator registered for
// this method. Fall back to the internal one if there isn't.
validator, ok := svc.ExternalValidators[fullMethod]
if !ok {
validator = svc
}
// Now that we know what validator to use, let it do its work.
return validator.ValidateMacaroon(ctx, uriPermissions, fullMethod)
}