-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
99 lines (78 loc) · 2.67 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
89
90
91
92
93
94
95
96
97
98
99
package aviation
import (
"context"
"github.com/cdr/gimlet"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
)
// TODO: add interceptors to provide "role required" and "group
// member" using gimlet.Authenticator
func MakeAuthenticationRequiredUnaryInterceptor(um gimlet.UserManager, conf gimlet.UserMiddlewareConfiguration) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
meta, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, grpc.Errorf(codes.Unauthenticated, "missing metadata from context")
}
var (
authDataAPIKey string
authDataName string
)
// Grab API auth details from header
if len(meta[conf.HeaderKeyName]) > 0 {
authDataAPIKey = meta[conf.HeaderKeyName][0]
}
if len(meta[conf.HeaderUserName]) > 0 {
authDataName = meta[conf.HeaderUserName][0]
}
if len(authDataAPIKey) == 0 {
return nil, grpc.Errorf(codes.Unauthenticated, "user key not provided")
}
usr, err := um.GetUserByID(authDataName)
if err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "problem finding user: %+v", err)
}
if usr == nil {
return nil, grpc.Errorf(codes.Unauthenticated, "user not found")
}
if usr.GetAPIKey() != authDataAPIKey {
return nil, grpc.Errorf(codes.Unauthenticated, "incorrect credentials")
}
ctx = SetRequestUser(ctx, usr)
return handler(ctx, req)
}
}
func MakeAuthenticationRequiredStreamInterceptor(um gimlet.UserManager, conf gimlet.UserMiddlewareConfiguration) grpc.StreamServerInterceptor {
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
ctx := stream.Context()
meta, ok := metadata.FromIncomingContext(ctx)
if !ok {
return grpc.Errorf(codes.Unauthenticated, "missing metadata from context")
}
var (
authDataAPIKey string
authDataName string
)
// Grab API auth details from header
if len(meta[conf.HeaderKeyName]) > 0 {
authDataAPIKey = meta[conf.HeaderKeyName][0]
}
if len(meta[conf.HeaderUserName]) > 0 {
authDataName = meta[conf.HeaderUserName][0]
}
if len(authDataAPIKey) == 0 {
return grpc.Errorf(codes.Unauthenticated, "user key not provided")
}
usr, err := um.GetUserByID(authDataName)
if err != nil {
return grpc.Errorf(codes.Unauthenticated, "problem finding user: %+v", err)
}
if usr == nil {
return grpc.Errorf(codes.Unauthenticated, "user not found")
}
if usr.GetAPIKey() != authDataAPIKey {
return grpc.Errorf(codes.Unauthenticated, "incorrect credentials")
}
return handler(srv, stream)
}
}