-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
216 lines (190 loc) · 6.35 KB
/
server.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package main
import (
"context"
"net/http"
"os"
"strings"
"time"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"github.com/gorilla/websocket"
"github.com/kelseyhightower/envconfig"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/urfave/cli"
"github.com/wwwillw/pixelland-chat/graph"
"github.com/wwwillw/pixelland-chat/graph/generated"
"github.com/wwwillw/pixelland-chat/interfaces"
)
type Specification struct {
Port string `default:"8081"`
Debug bool `default:"true"`
SqlHost string `default:"localhost" split_words:"true"`
SqlPort int `default:"5432" split_words:"true"`
SqlUser string `default:"postgres" split_words:"true"`
SqlPassword string `default:"123" split_words:"true"`
SqlDbName string `default:"pixellandchat" split_words:"true"`
SqlSslMode string `default:"disable" split_words:"true"`
SeedDb bool `default:"false" split_words:"true"`
PubsubActive bool `default:"true" split_words:"true"`
ServiceAccountPath string `default:"/etc/credentials/pixelland-admin-service-account.json" split_words:"true"`
EnforceAuth bool `default:"false" split_words:"true"`
AuthorEventsTopic string `default:"author_events" split_words:"true"`
InstanceEventsTopic string `default:"instance_events" split_words:"true"`
UserEventsTopic string `default:"user_events" split_words:"true"`
PubsubProjectId string `default:"" split_words:"true"`
}
func init() {
if os.Getenv("CHAT_DEBUG") == "false" {
zerolog.LevelFieldName = "severity"
zerolog.TimestampFieldName = "timestamp"
zerolog.TimeFieldFormat = time.RFC3339Nano
} else {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
}
func main() {
app := cli.NewApp()
app.Name = "pixelland-chat"
app.Action = run
app.Run(os.Args)
}
func run(args *cli.Context) error {
var s Specification
err := envconfig.Process("chat", &s)
if err != nil {
log.Fatal().Err(err).Msg("Failed to read environment variables")
}
dbConfig := interfaces.DatabaseConfig{
Host: s.SqlHost,
Port: s.SqlPort,
User: s.SqlUser,
Password: s.SqlPassword,
DbName: s.SqlDbName,
SslMode: s.SqlSslMode,
}
db, err := interfaces.InitDatabase(dbConfig, 5)
if err != nil {
log.Fatal().Err(err).Msg("Failed to initialize db")
}
if s.SeedDb {
if err = db.DropAll(); err != nil {
log.Fatal().Err(err).Msg("Failed to drop all tables")
}
}
if err = db.RunMigrations(); err != nil {
log.Fatal().Err(err).Msg("Failed to run db migrations")
}
if s.SeedDb {
if err = db.Seed(); err != nil {
log.Fatal().Err(err).Msg("Failed to seed db")
}
}
ctx := context.Background()
if s.EnforceAuth {
if err := interfaces.InitFirebaseClient(ctx, s.ServiceAccountPath); err != nil {
log.Fatal().Err(err).Msg("Failed to initialize firebase client")
}
}
pubsubConfig := interfaces.PubsubConfig{
ServiceAccountPath: s.ServiceAccountPath,
AuthorEventsTopic: s.AuthorEventsTopic,
InstanceEventsTopic: s.InstanceEventsTopic,
UserEventsTopic: s.UserEventsTopic,
Active: s.PubsubActive,
PubsubProjectId: s.PubsubProjectId,
IsProd: !s.Debug,
}
if err := interfaces.InitPubSubClient(ctx, pubsubConfig); err != nil {
log.Fatal().Err(err).Msg("Failed to initialize pubsub client")
}
router := chi.NewRouter()
router.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://*", "http://*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token", "X-PINGOTHER"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
}))
srv := handler.New(generated.NewExecutableSchema(graph.New()))
srv.AddTransport(transport.POST{})
srv.AddTransport(transport.Options{})
srv.AddTransport(transport.Websocket{
KeepAlivePingInterval: 10 * time.Second,
Upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
},
InitFunc: func(ctx context.Context, initPayload transport.InitPayload) (context.Context, *transport.InitPayload, error) {
val := initPayload["Authorization"]
authHeader, ok := val.(string)
if !ok {
authHeader = ""
}
return updateAuthContext(ctx, authHeader, s.EnforceAuth), &initPayload, nil
},
})
if s.Debug {
log.Info().Msg("GraphQL introspection enabled")
srv.Use(extension.Introspection{})
router.Handle("/", playground.Handler("PixelLand Chat", "/graphql"))
}
router.Handle("/", http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
},
))
router.Handle("/healthz", http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
},
))
router.Handle("/graphql", http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("authorization")
ctx := updateAuthContext(r.Context(), authHeader, s.EnforceAuth)
srv.ServeHTTP(w, r.WithContext(ctx))
},
))
log.Info().Msg("Server started on port " + s.Port)
if err := http.ListenAndServe(":"+s.Port, router); err != nil {
log.Fatal().Err(err).Msg("Failed to start server")
}
return nil
}
func updateAuthContext(ctx context.Context, authHeader string, enforceAuth bool) context.Context {
authHeaderParts := strings.Split(authHeader, "Bearer ")
if len(authHeaderParts) <= 1 {
return context.WithValue(ctx, "uid", "")
}
tokenStr := authHeaderParts[1]
auth := interfaces.GetAuthClient()
uid := ""
claims := map[string]interface{}{}
if enforceAuth {
token, err := auth.VerifyIDToken(ctx, tokenStr)
if err != nil {
log.Warn().Err(err).Msg("error verifying ID token")
return ctx
}
uid = token.UID
claims = token.Claims
} else {
uid = tokenStr
claims = map[string]interface{}{}
claims["admin"] = true
}
ctx = context.WithValue(ctx, "claims", claims)
ctx = context.WithValue(ctx, "token", tokenStr)
ctx = context.WithValue(ctx, "uid", uid)
return ctx
}