-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·187 lines (166 loc) · 4.46 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package main
import (
"context"
"fmt"
"log"
"net"
"os"
"os/signal"
"github.com/dgraph-io/dgo"
"github.com/dgraph-io/dgo/protos/api"
jwt "github.com/dgrijalva/jwt-go"
pb "github.com/mucyomiller/hahiye/hahiye"
"github.com/mucyomiller/hahiye/server"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const (
port = ":9090"
srvCertFile = "./certs/server.crt"
srvKeyFile = "./certs/ca-key.pem"
)
func main() {
//spin up dgraph db connection
conn, err := grpc.Dial("127.0.0.1:9080", grpc.WithInsecure())
if err != nil {
log.Fatal("Error Occurred While trying to dial gRPC")
return
}
fmt.Println("Now Connected to DgraphDB")
defer conn.Close()
dc := api.NewDgraphClient(conn)
dg := dgo.NewDgraphClient(dc)
op := &api.Operation{}
// Adding Our Defined Database SCHEMA
op.Schema = `
location: geo @index(geo) .
name: string @index(term) .
lastname: string @index(term) .
email: string @index(exact) @upsert .
password: password .
follows: uid @reverse .
interested: uid @reverse .
verified: bool .
`
ctx := context.Background()
err = dg.Alter(ctx, op)
if err != nil {
log.Fatal(err)
}
// creating a listener on specified port
listener, err := net.Listen("tcp", port)
if err != nil {
log.Fatal("failed to start server:", err)
}
fmt.Println("starting gprc server...")
// creating tls credentials from cert file
tlsCreds, err := credentials.NewServerTLSFromFile(srvCertFile, srvKeyFile)
if err != nil {
log.Fatal(err)
}
// setup and register our available services
authService := server.NewAuthService(dg)
accountService := server.NewAccountServiceServer(dg)
placeService := server.NewPlaceServiceServer(dg)
interestService := server.NewInterestServiceServer(dg)
grpcServer := grpc.NewServer(
grpc.Creds(tlsCreds),
grpc.UnaryInterceptor(authUnaryIntercept),
grpc.StreamInterceptor(streamAuthIntercept),
)
pb.RegisterAuthServiceServer(grpcServer, authService)
pb.RegisterAccountServiceServer(grpcServer, accountService)
pb.RegisterPlaceServiceServer(grpcServer, placeService)
pb.RegisterInterestServiceServer(grpcServer, interestService)
// graceful shutdown
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
// sig is a ^C, handle it
log.Println("shutting down gRPC server...")
grpcServer.GracefulStop()
<-ctx.Done()
}
}()
// start services server
log.Println("starting secure rpc services on", port)
if err := grpcServer.Serve(listener); err != nil {
log.Fatal(err)
}
}
// authUnaryIntercept intercepts incoming requests to validate
// jwt token from metadata header "authorization"
func authUnaryIntercept(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
//bypass auth if method is /hahiye.AuthService/Login
if info.FullMethod == "/hahiye.AuthService/Login" {
fmt.Println("bypassing auth cz it's login action")
return handler(ctx, req)
}
if err := auth(ctx); err != nil {
return nil, err
}
log.Println("authorization OK")
return handler(ctx, req)
}
// streamAuthIntercept intercepts to validate authorization
func streamAuthIntercept(
server interface{},
stream grpc.ServerStream,
info *grpc.StreamServerInfo,
handler grpc.StreamHandler,
) error {
//bypass auth if method is /hahiye.AuthService/Login
if info.FullMethod == "/hahiye.AuthService/Login" {
fmt.Println("bypassing auth cz it's login action")
return handler(server, stream)
}
if err := auth(stream.Context()); err != nil {
return err
}
log.Println("authorization OK")
return handler(server, stream)
}
func auth(ctx context.Context) error {
meta, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Errorf(
codes.InvalidArgument,
"missing context",
)
}
authString, ok := meta["authorization"]
if !ok {
return status.Errorf(
codes.Unauthenticated,
"missing authorization",
)
}
// validate token algo
log.Println("found jwt token")
jwtToken, err := jwt.Parse(
authString[0],
func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("bad signing method")
}
// additional validation goes here.
return []byte("s3cr3t"), nil
},
)
if jwtToken.Valid {
return nil
}
if err != nil {
return status.Error(codes.Internal, err.Error())
}
return status.Error(codes.Internal, "bad token")
}