/
controllers.go
217 lines (181 loc) · 5.41 KB
/
controllers.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
package controllers
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"runtime"
"strings"
"time"
"github.com/coduno/api/util/passenger"
"github.com/gorilla/mux"
"golang.org/x/net/context"
"google.golang.org/appengine"
)
// Holds routes to all controllers' handlers.
var router = mux.NewRouter()
func Handler() http.Handler {
return router
}
// ContextHandlerFunc is similar to a http.HandlerFunc, but also gets passed
// the current context.
// To ease error handling, a ContextHandleFunc must return a HTTP status
// code and an error. Still, the handler is allowed to write a response.
type ContextHandlerFunc func(context.Context, http.ResponseWriter, *http.Request) (int, error)
func (h ContextHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if p := recover(); p != nil {
deal(nil, w, r, http.StatusInternalServerError, errors.New(fmt.Sprint(p)))
}
}()
ctx := appengine.NewContext(r)
hsts(w)
if !cors(w, r) {
return
}
// Add authentication metadata.
ctx, err := passenger.NewContextFromRequest(ctx, r)
buf := bufferedResponseWriter{
b: new(bytes.Buffer),
w: w,
s: 0,
}
status, err := h(ctx, buf, r)
if status == 0 {
status = buf.s
}
// No error and a low status code means
// everything went well.
if err == nil && status < 400 {
if status == 0 {
status = http.StatusOK
}
buf.flush(status)
return
}
deal(ctx, w, r, status, err)
}
func hsts(w http.ResponseWriter) {
if !appengine.IsDevAppServer() {
// Protect against HTTP downgrade attacks by explicitly telling
// clients to use HTTPS.
// max-age is computed to match the expiration date of our TLS
// certificate.
// https://developer.mozilla.org/docs/Web/Security/HTTP_strict_transport_security
// This is only set on production.
invalidity := time.Date(2017, time.July, 15, 8, 30, 21, 0, time.UTC)
maxAge := invalidity.Sub(time.Now()).Seconds()
w.Header().Set("Strict-Transport-Security", fmt.Sprintf("max-age=%d", int(maxAge)))
}
}
// Rudimentary CORS checking. See
// https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS
func cors(w http.ResponseWriter, r *http.Request) bool {
origin := r.Header.Get("Origin")
// If the client has not provided it's origin, the
// request will be answered in any case.
if origin == "" {
return true
}
// Only allow our own origin if not on development server.
if !appengine.IsDevAppServer() && origin != "https://app.cod.uno" {
http.Error(w, "Invalid Origin", http.StatusUnauthorized)
return false
}
// We have a nice CORS established, so set appropriate headers.
// TODO(flowlo): Figure out how to send correct methods.
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Origin", origin)
// If this is an OPTIONS request, we answer it
// immediately and do not bother higher level handlers.
if r.Method == "OPTIONS" {
w.Write([]byte("OK"))
return false
}
return true
}
type bufferedResponseWriter struct {
b *bytes.Buffer
w http.ResponseWriter
s int
}
func (w bufferedResponseWriter) flush(status int) {
w.w.WriteHeader(status)
io.Copy(w.w, w.b)
}
func (w bufferedResponseWriter) WriteHeader(status int) {
w.s = status
}
func (w bufferedResponseWriter) Write(p []byte) (n int, err error) {
return w.b.Write(p)
}
func (w bufferedResponseWriter) Header() http.Header {
return w.w.Header()
}
type trace struct {
e error
t []byte
}
func (t trace) Error() string {
return fmt.Sprintf("%s\n%s", t.e, t.t)
}
// tracable wraps the passed error and generates a new error that will
// expand into a full stack trace. Be aware that this is expensive,
// as it will stop the world to collect the trace, and should be
// used with caution!
func tracable(err error) error {
r := trace{
e: err,
t: make([]byte, 4096),
}
runtime.Stack(r.t, false)
return r
}
// deal makes the response in error cases somewhat nicer. It will try
// to figure out what actually went wrong and inform the user.
// It should not be called if the request went fine. If status is below
// 400, and err is not nil, it will assume an internal server error.
// Generally, if you pass a nil error, don't expect deal to do anything
// useful.
func deal(ctx context.Context, w http.ResponseWriter, r *http.Request, status int, err error) {
// Getting an error and a status code blow 400 is somewhat paradox.
// Also, if the status is the zero value, assume that we're dealing
// with an internal server error.
if err != nil && status < 400 || status == 0 {
status = http.StatusInternalServerError
}
codunoError := struct {
Message,
Reason,
RequestID,
StatusText,
Trace string
Status int
}{}
codunoError.Status = status
codunoError.StatusText = http.StatusText(status)
if ctx != nil {
codunoError.RequestID = appengine.RequestID(ctx)
}
w.WriteHeader(status)
// If we don't have an error it's really hard to make sense.
if err == nil {
json.NewEncoder(w).Encode(codunoError)
return
}
if appengine.IsOverQuota(err) {
codunoError.Reason = "Over Quota"
} else if appengine.IsTimeoutError(err) {
codunoError.Reason = "Timeout Error"
} else {
codunoError.Reason = err.Error()
}
if t, ok := err.(trace); ok {
codunoError.Trace = strings.Replace(string(t.t), "\n", "\n\t", -1)
}
json.NewEncoder(w).Encode(codunoError)
}