-
Notifications
You must be signed in to change notification settings - Fork 0
/
interceptor.go
66 lines (54 loc) · 1.43 KB
/
interceptor.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
package main
import (
"context"
"database/sql"
"github.com/kofoworola/passbasetest/storage"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
var ignorePaths = []string{
"/project.ProjectService/CreateProject",
}
type serverInterceptor struct {
storage projectStorage
}
type projectStorage interface {
GetProjectByApiKey(context.Context, string) (*storage.Project, error)
}
func (i *serverInterceptor) Interceptor() grpc.UnaryServerInterceptor {
return grpc.UnaryServerInterceptor(func(ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
// ignore the ignorables
found := false
for _, p := range ignorePaths {
if info.FullMethod == p {
found = true
break
}
}
if found {
return handler(ctx, req)
}
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Error(codes.Internal, "error completing request")
}
authHeader, ok := md["authorization"]
if !ok {
return nil, status.Error(codes.Unauthenticated, "invalid auth data")
}
apiKey := authHeader[0]
_, err := i.storage.GetProjectByApiKey(ctx, apiKey)
if err != nil {
if err == sql.ErrNoRows {
return nil, status.Error(codes.PermissionDenied, "unauthorized")
}
return nil, status.Error(codes.Internal, "error completing request")
}
return handler(ctx, req)
})
}