Debian Codegraph @

rpc/interceptors.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package rpc
5
6 import (
7 "context"
8
9 . "github.com/etix/mirrorbits/config"
10 grpc "google.golang.org/grpc"
11 "google.golang.org/grpc/codes"
12 "google.golang.org/grpc/metadata"
13 "google.golang.org/grpc/status"
14 )
15
16 func StreamInterceptor(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
17 if err := authorize(stream.Context()); err != nil {
18 return err
19 }
20
21 return handler(srv, stream)
22 }
23
24 func UnaryInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
25 if err := authorize(ctx); err != nil {
26 return nil, err
27 }
28
29 return handler(ctx, req)
30 }
31
32 func authorize(ctx context.Context) error {
33 if md, ok := metadata.FromIncomingContext(ctx); ok {
34 if md["password"][0] == GetConfig().RPCPassword {
35 return nil
36 }
37 }
38
39 return status.Error(codes.Unauthenticated, "access denied")
40 }