-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
256 lines (216 loc) · 6.96 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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package main
import (
"bytes"
"context"
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"github.com/bjorge/friendlyreservations/cookies"
"github.com/bjorge/friendlyreservations/frapi"
"github.com/bjorge/friendlyreservations/utilities"
"github.com/rs/cors"
graphqlupload "github.com/smithaitufe/go-graphql-upload"
"github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/relay"
)
func main() {
if redirectURL != "" {
redirectHTML := mustGetRedirectHTML("redirect.html", redirectURL, redirectLabel)
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(redirectHTML)
}))
startServer()
return
}
if utilities.SystemEmail == "" {
panic("DEFAULT_SYSTEM_EMAIL environment variable must be set, example set to [email protected] in app.yaml")
}
// handle the gql playground pages
for uri, query := range map[string]string{
"/adminschema": "adminquery",
"/memberschema": "memberquery",
"/homeschema": "homequery"} {
gqlSchemaHTML := mustGetSchemaHTML("gqlschema.html", query)
http.Handle(uri, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(gqlSchemaHTML)
}))
}
// handle the daily cron job
http.Handle("/dailycron", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
log.LogInfof("Run daily cron")
err := frapi.DailyCron(ctx)
if err != nil {
log.LogErrorf("Daily cron error: %+v", err)
}
}))
// handle the graphql requests
for uri, schema := range map[string]*graphql.Schema{
"/homequery": homeSchema,
"/adminquery": adminSchema,
"/memberquery": memberSchema} {
// the gql handler
gqlRelayHandler := &relay.Handler{Schema: schema}
// chain in the upload handler
gqlHandler := graphqlupload.Handler(gqlRelayHandler)
// chain in the cors handler
if corsOriginURI != "" {
log.LogInfof("cors handler added for graphql for uri: %v with origin: %v", uri, corsOriginURI)
corsHandler := cors.New(cors.Options{
AllowedOrigins: []string{corsOriginURI},
AllowedMethods: []string{
http.MethodPost,
},
AllowedHeaders: []string{"*"},
AllowCredentials: true,
})
gqlHandler = corsHandler.Handler(gqlHandler)
}
// chain in the gql context handler
http.Handle(uri, gqlMiddleware(gqlHandler))
}
// handle the test auth
http.Handle("/auth", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.LogDebugf("auth handler for localhost testing")
if r.Method != "POST" {
fmt.Fprintf(w, "hmm... not a post, try again")
return
}
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm err: %v", err)
return
}
email := r.FormValue("email")
if email == "" {
fmt.Fprintf(w, "hmm... empty email, try again")
return
}
// ok, this is just for testing, so assume a valid email
// (although any identifier ok for testing...)
// save auth credentials into cookies
frapi.FrapiCookies.SetCookies(w, email)
// go back to home
redirectURL := "/"
if corsOriginURI != "" {
redirectURL = corsOriginURI + redirectURL
log.LogDebugf("redirect to cors origin")
}
log.LogDebugf("redirect to: %v", redirectURL)
http.Redirect(w, r, redirectURL, http.StatusFound)
}))
// the login handler
http.Handle("/login", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.LogDebugf("login handler for localhost testing")
frapi.FrapiCookies.ClearCookies(w)
noCache(w)
var htmlContent = `
<html>
Local test login<br/>
<form action="/auth" method="post">
Email:<br/>
<input type="text" name="email" value=""><br/>
<input type="submit" value="Submit">
</form>
</html>`
fmt.Fprintf(w, htmlContent)
}))
// for production the spa is built and deployed to the spa directory
spa := SpaHandler{StaticPath: "spa", IndexPath: "index.html"}
http.Handle("/", spa)
startServer()
}
func startServer() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.LogDebugf("Defaulting to port %s", port)
}
log.LogDebugf("Listening on port %s", port)
if err := http.ListenAndServe("localhost:"+port, nil); err != nil {
log.LogErrorf("error listening on port %v", err)
}
}
func gqlMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctxWithValues := context.WithValue(r.Context(), cookies.WriterKey("writer"), w)
ctxWithValues = frapi.FrapiCookies.ContextWithCookies(ctxWithValues, r)
next.ServeHTTP(w, r.WithContext(ctxWithValues))
}
return http.HandlerFunc(fn)
}
func mustGetSchemaHTML(fileName string, gqlPath string) []byte {
t := template.New(fileName)
t, err := t.ParseFiles(fileName)
if err != nil {
panic(err)
}
// refer to the gql handler above
var buffer bytes.Buffer
err = t.Execute(&buffer, struct{ Path string }{Path: gqlPath})
if err != nil {
panic(err)
}
return buffer.Bytes()
}
func mustGetRedirectHTML(fileName string, url string, label string) []byte {
t := template.New(fileName)
t, err := t.ParseFiles(fileName)
if err != nil {
panic(err)
}
// refer to the gql handler above
var buffer bytes.Buffer
err = t.Execute(&buffer, struct {
Path string
Label string
}{Path: url, Label: label})
if err != nil {
panic(err)
}
return buffer.Bytes()
}
func noCache(w http.ResponseWriter) {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
}
// SpaHandler implements the http.Handler interface, so we can use it
// to respond to HTTP requests. The path to the static directory and
// path to the index file within that static directory are used to
// serve the SPA in the given static directory.
type SpaHandler struct {
StaticPath string
IndexPath string
}
// ServeHTTP inspects the URL path to locate a file within the static dir
// on the SPA handler. If a file is found, it will be served. If not, the
// file located at the index path on the SPA handler will be served. This
// is suitable behavior for serving an SPA (single page application).
func (h SpaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the absolute path to prevent directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// prepend the path with the path to the static directory
path = filepath.Join(h.StaticPath, path)
// check whether a file exists at the given path
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.StaticPath, h.IndexPath))
return
} else if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// otherwise, use http.FileServer to serve the static dir
http.FileServer(http.Dir(h.StaticPath)).ServeHTTP(w, r)
}