forked from getfider/fider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
644 lines (553 loc) · 17.7 KB
/
context.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
package web
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
"strings"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/blob"
"github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/pkg/worker"
)
// Map defines a generic map of type `map[string]interface{}`
type Map map[string]interface{}
// StringMap defines a map of type `map[string]string`
type StringMap map[string]string
// Props defines the data required to render rages
type Props struct {
Title string
Description string
ChunkName string
Data Map
}
// HTMLMimeType is the mimetype for HTML responses
var (
PlainContentType = "text/plain"
HTMLContentType = "text/html"
JSONContentType = "application/json"
XMLContentType = "application/xml"
UTF8PlainContentType = PlainContentType + "; charset=utf-8"
UTF8HTMLContentType = HTMLContentType + "; charset=utf-8"
UTF8XMLContentType = XMLContentType + "; charset=utf-8"
UTF8JSONContentType = JSONContentType + "; charset=utf-8"
)
// CookieSessionName is the name of the cookie that holds the session ID
const CookieSessionName = "user_session_id"
// CookieAuthName is the name of the cookie that holds the Authentication Token
const CookieAuthName = "auth"
// CookieSignUpAuthName is the name of the cookie that holds the temporary Authentication Token
const CookieSignUpAuthName = "__signup_auth"
var (
prefixKey = "__CTX_"
tenantContextKey = prefixKey + "TENANT"
userContextKey = prefixKey + "USER"
claimsContextKey = prefixKey + "CLAIMS"
transactionContextKey = prefixKey + "TRANSACTION"
servicesContextKey = prefixKey + "SERVICES"
tasksContextKey = prefixKey + "TASKS"
)
//Context shared between http pipeline
type Context struct {
id string
sessionID string
Response http.ResponseWriter
Request Request
engine *Engine
logger log.Logger
params StringMap
store Map
worker worker.Worker
}
//Engine returns main HTTP engine
func (ctx *Context) Engine() *Engine {
return ctx.engine
}
//SessionID returns the current session ID
func (ctx *Context) SessionID() string {
return ctx.sessionID
}
//SetSessionID sets the session ID on current context
func (ctx *Context) SetSessionID(id string) {
ctx.sessionID = id
ctx.logger.SetProperty(log.PropertyKeySessionID, id)
}
//ContextID returns the unique id for this context
func (ctx *Context) ContextID() string {
return ctx.id
}
//Commit everything that is pending on current context
func (ctx *Context) Commit() error {
if trx := ctx.ActiveTransaction(); trx != nil {
if err := trx.Commit(); err != nil {
return err
}
}
tasks, ok := ctx.Get(tasksContextKey).([]worker.Task)
if ok {
for _, task := range tasks {
ctx.worker.Enqueue(task)
}
}
return nil
}
//Rollback everything that is pending on current context
func (ctx *Context) Rollback() error {
if trx := ctx.ActiveTransaction(); trx != nil {
return trx.Rollback()
}
return nil
}
//Enqueue given task to be processed in background
func (ctx *Context) Enqueue(task worker.Task) {
wrap := func(c *Context) worker.Job {
return func(wc *worker.Context) error {
wc.SetUser(c.User())
wc.SetTenant(c.Tenant())
wc.SetBaseURL(c.BaseURL())
wc.SetLogoURL(c.LogoURL())
wc.SetAssetsBaseURL(c.TenantAssetsURL(""))
return task.Job(wc)
}
}
tasks, ok := ctx.Get(tasksContextKey).([]worker.Task)
if !ok {
tasks = make([]worker.Task, 0)
}
ctx.Set(tasksContextKey, append(tasks, worker.Task{
OriginSessionID: ctx.SessionID(),
Name: task.Name,
Job: wrap(ctx),
}))
}
//Tenant returns current tenant
func (ctx *Context) Tenant() *models.Tenant {
tenant, ok := ctx.Get(tenantContextKey).(*models.Tenant)
if ok {
return tenant
}
return nil
}
//SetTenant update HTTP context with current tenant
func (ctx *Context) SetTenant(tenant *models.Tenant) {
if tenant != nil {
ctx.logger.SetProperty(log.PropertyKeyTenantID, tenant.ID)
}
if ctx.Services() != nil {
ctx.Services().SetCurrentTenant(tenant)
}
ctx.Set(tenantContextKey, tenant)
}
//Bind context values into given model
func (ctx *Context) Bind(i interface{}) error {
err := ctx.engine.binder.Bind(i, ctx)
if err != nil {
return errors.Wrap(err, "failed to bind request to model")
}
return nil
}
//BindTo context values into given model
func (ctx *Context) BindTo(i actions.Actionable) *validate.Result {
err := ctx.engine.binder.Bind(i.Initialize(), ctx)
if err != nil {
if err == ErrContentTypeNotAllowed {
return validate.Failed(err.Error())
}
return validate.Error(errors.Wrap(err, "failed to bind request to action"))
}
if !i.IsAuthorized(ctx.User(), ctx.Services()) {
return validate.Unauthorized()
}
return i.Validate(ctx.User(), ctx.Services())
}
//Logger returns current logger
func (ctx *Context) Logger() log.Logger {
return ctx.logger
}
//IsAuthenticated returns true if user is authenticated
func (ctx *Context) IsAuthenticated() bool {
return ctx.Get(userContextKey) != nil
}
//IsAjax returns true if request is AJAX
func (ctx *Context) IsAjax() bool {
accept := ctx.Request.GetHeader("Accept")
contentType := ctx.Request.GetHeader("Content-Type")
return strings.Contains(accept, JSONContentType) || strings.Contains(contentType, JSONContentType)
}
//Unauthorized returns a 403 response
func (ctx *Context) Unauthorized() error {
return ctx.Render(http.StatusForbidden, "403.html", Props{
Title: "Not Authorized",
Description: "You are not authorized to view this page.",
})
}
//NotFound returns a 404 page
func (ctx *Context) NotFound() error {
return ctx.Render(http.StatusNotFound, "404.html", Props{
Title: "Page not found",
Description: "The link you clicked may be broken or the page may have been removed.",
})
}
//Gone returns a 410 page
func (ctx *Context) Gone() error {
return ctx.Render(http.StatusGone, "410.html", Props{
Title: "Expired",
Description: "The link you clicked has expired.",
})
}
//Failure returns a 500 page
func (ctx *Context) Failure(err error) error {
err = errors.StackN(err, 1)
cause := errors.Cause(err)
if cause == app.ErrNotFound || cause == blob.ErrNotFound {
return ctx.NotFound()
}
ctx.Logger().Errorf(err.Error(), log.Props{
"Body": ctx.Request.Body,
"HttpMethod": ctx.Request.Method,
"URL": ctx.Request.URL.String(),
})
ctx.Render(http.StatusInternalServerError, "500.html", Props{
Title: "Shoot! Well, this is unexpected…",
Description: "An error has occurred and we're working to fix the problem!",
})
return err
}
//HandleValidation handles given validation result property to return 400 or 500
func (ctx *Context) HandleValidation(result *validate.Result) error {
if result.Err != nil {
return ctx.Failure(result.Err)
}
if !result.Authorized {
return ctx.Unauthorized()
}
return ctx.BadRequest(Map{
"errors": result.Errors,
})
}
//Attachment returns an attached file
func (ctx *Context) Attachment(fileName, contentType string, file []byte) error {
ctx.Response.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", fileName))
return ctx.Blob(http.StatusOK, contentType, file)
}
//Ok returns 200 OK with JSON result
func (ctx *Context) Ok(data interface{}) error {
return ctx.JSON(http.StatusOK, data)
}
//BadRequest returns 400 BadRequest with JSON result
func (ctx *Context) BadRequest(dict Map) error {
return ctx.JSON(http.StatusBadRequest, dict)
}
//Page returns a page with given variables
func (ctx *Context) Page(props Props) error {
if len(env.Config.Rendergun.URL) > 0 && ctx.Request.IsCrawler() {
html := new(bytes.Buffer)
ctx.engine.renderer.Render(html, "index.html", props, ctx)
return ctx.prerender(http.StatusOK, html)
}
return ctx.Render(http.StatusOK, "index.html", props)
}
// Render renders a template with data and sends a text/html response with status
func (ctx *Context) Render(code int, template string, props Props) error {
if ctx.IsAjax() {
return ctx.JSON(code, Map{})
}
buf := new(bytes.Buffer)
ctx.engine.renderer.Render(buf, template, props, ctx)
return ctx.Blob(code, UTF8HTMLContentType, buf.Bytes())
}
func (ctx *Context) prerender(code int, html io.Reader) error {
renderURL := fmt.Sprintf("%s/render?url=%s", env.Config.Rendergun.URL, ctx.Request.URL.String())
req, _ := http.NewRequest("POST", renderURL, html)
req.Header.Set("Content-Type", "text/html")
req.Header.Set("x-rendergun-wait-until", "networkidle0")
req.Header.Set("x-rendergun-block-ads", "true")
req.Header.Set("x-rendergun-abort-request", "assets\\/css\\/(common|vendor|main)\\.")
resp, err := http.DefaultClient.Do(req)
if err != nil {
ctx.Logger().Error(errors.Wrap(err, "failed to execute rendergun"))
return ctx.TryAgainLater(24 * time.Hour)
}
defer resp.Body.Close()
prerendered, err := ioutil.ReadAll(resp.Body)
if err != nil {
ctx.Logger().Error(errors.Wrap(err, "failed to copy response from rendergun to output"))
return ctx.TryAgainLater(24 * time.Hour)
}
return ctx.Blob(code, UTF8HTMLContentType, prerendered)
}
//TryAgainLater returns a service unavailable response with Retry-After header
func (ctx *Context) TryAgainLater(d time.Duration) error {
ctx.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
ctx.Response.Header().Set("Retry-After", fmt.Sprintf("%.0f", d.Seconds()))
return ctx.NoContent(http.StatusServiceUnavailable)
}
//AddParam add a single param to route parameters list
func (ctx *Context) AddParam(name, value string) {
ctx.params[name] = value
}
//Claims returns current user claims
func (ctx *Context) Claims() *jwt.FiderClaims {
claims, ok := ctx.Get(claimsContextKey).(*jwt.FiderClaims)
if ok {
return claims
}
return nil
}
//SetClaims update HTTP context with current user claims
func (ctx *Context) SetClaims(claims *jwt.FiderClaims) {
ctx.Set(claimsContextKey, claims)
}
//User returns authenticated user
func (ctx *Context) User() *models.User {
user, ok := ctx.Get(userContextKey).(*models.User)
if ok {
return user
}
return nil
}
//SetUser update HTTP context with current user
func (ctx *Context) SetUser(user *models.User) {
if user != nil {
ctx.logger.SetProperty(log.PropertyKeyUserID, user.ID)
}
if ctx.Services() != nil {
ctx.Services().SetCurrentUser(user)
}
ctx.Set(userContextKey, user)
}
//Services returns current app.Services from context
func (ctx *Context) Services() *app.Services {
svc, ok := ctx.Get(servicesContextKey).(*app.Services)
if ok {
return svc
}
return nil
}
//AddCookie adds a cookie
func (ctx *Context) AddCookie(name, value string, expires time.Time) *http.Cookie {
cookie := &http.Cookie{
Name: name,
Value: value,
HttpOnly: true,
Path: "/",
Expires: expires,
Secure: ctx.Request.IsSecure,
}
http.SetCookie(ctx.Response, cookie)
return cookie
}
//RemoveCookie removes a cookie
func (ctx *Context) RemoveCookie(name string) {
http.SetCookie(ctx.Response, &http.Cookie{
Name: name,
Path: "/",
HttpOnly: true,
MaxAge: -1,
Expires: time.Now().Add(-100 * time.Hour),
Secure: ctx.Request.IsSecure,
})
}
//SetServices update current context with app.Services
func (ctx *Context) SetServices(services *app.Services) {
ctx.Set(servicesContextKey, services)
}
//SetActiveTransaction adds transaction to context
func (ctx *Context) SetActiveTransaction(trx *dbx.Trx) {
ctx.Set(transactionContextKey, trx)
}
//ActiveTransaction returns current active Database transaction
func (ctx *Context) ActiveTransaction() *dbx.Trx {
return ctx.Get(transactionContextKey).(*dbx.Trx)
}
//BaseURL returns base URL
func (ctx *Context) BaseURL() string {
address := ctx.Request.URL.Scheme + "://" + ctx.Request.URL.Hostname()
if ctx.Request.URL.Port() != "" {
address += ":" + ctx.Request.URL.Port()
}
return address
}
//TenantBaseURL returns base URL for a given tenant
func (ctx *Context) TenantBaseURL(tenant *models.Tenant) string {
if env.IsSingleHostMode() {
return ctx.BaseURL()
}
address := ctx.Request.URL.Scheme + "://"
if tenant.CNAME != "" {
address += tenant.CNAME
} else {
address += tenant.Subdomain + env.MultiTenantDomain()
}
if ctx.Request.URL.Port() != "" {
address += ":" + ctx.Request.URL.Port()
}
return address
}
//QueryParam returns querystring parameter for given key
func (ctx *Context) QueryParam(key string) string {
return ctx.Request.URL.Query().Get(key)
}
//QueryParamAsInt returns querystring parameter for given key
func (ctx *Context) QueryParamAsInt(key string) (int, error) {
value := ctx.QueryParam(key)
if value == "" {
return 0, nil
}
intValue, err := strconv.Atoi(value)
if err != nil {
return 0, errors.Wrap(err, "failed to parse %s to integer", value)
}
return intValue, nil
}
//QueryParamAsArray returns querystring parameter for given key as an array
func (ctx *Context) QueryParamAsArray(key string) []string {
param := ctx.QueryParam(key)
if param != "" {
return strings.Split(param, ",")
}
return []string{}
}
//Param returns parameter as string
func (ctx *Context) Param(name string) string {
if ctx.params == nil {
return ""
}
return strings.TrimPrefix(ctx.params[name], "/")
}
//ParamAsInt returns parameter as int
func (ctx *Context) ParamAsInt(name string) (int, error) {
value := ctx.Param(name)
intValue, err := strconv.Atoi(value)
if err != nil {
return 0, errors.Wrap(err, "failed to parse %s to integer", value)
}
return intValue, nil
}
// Get retrieves data from the context.
func (ctx *Context) Get(key string) interface{} {
return ctx.store[key]
}
// Set saves data in the context.
func (ctx *Context) Set(key string, val interface{}) {
if ctx.store == nil {
ctx.store = make(Map)
}
ctx.store[key] = val
}
// String returns a text response with status code.
func (ctx *Context) String(code int, text string) error {
return ctx.Blob(code, UTF8PlainContentType, []byte(text))
}
// XML returns a XML response with status code.
func (ctx *Context) XML(code int, text string) error {
return ctx.Blob(code, UTF8XMLContentType, []byte(text))
}
// JSON returns a JSON response with status code.
func (ctx *Context) JSON(code int, i interface{}) error {
b, err := json.Marshal(i)
if err != nil {
return errors.Wrap(err, "failed to marshal response to JSON")
}
return ctx.Blob(code, UTF8JSONContentType, b)
}
// Image sends an image blob response with status code and content type.
func (ctx *Context) Image(contentType string, b []byte) error {
if !strings.HasPrefix(contentType, "image/") {
return ctx.Failure(errors.New("'%s' is not an image", ctx.Request.URL.String()))
}
return ctx.Blob(http.StatusOK, contentType, b)
}
// Blob sends a blob response with status code and content type.
func (ctx *Context) Blob(code int, contentType string, b []byte) error {
ctx.Response.Header().Set("Content-Type", contentType)
ctx.Response.WriteHeader(code)
_, err := ctx.Response.Write(b)
return err
}
// NoContent sends a response with no body and a status code.
func (ctx *Context) NoContent(code int) error {
ctx.Response.WriteHeader(code)
return nil
}
// Redirect the request to a provided URL
func (ctx *Context) Redirect(url string) error {
ctx.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
ctx.Response.Header().Set("Location", url)
ctx.Response.WriteHeader(http.StatusTemporaryRedirect)
return nil
}
// PermanentRedirect the request to a provided URL
func (ctx *Context) PermanentRedirect(url string) error {
ctx.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
ctx.Response.Header().Set("Location", url)
ctx.Response.WriteHeader(http.StatusMovedPermanently)
return nil
}
// GlobalAssetsURL return the full URL to a globally shared static asset
func (ctx *Context) GlobalAssetsURL(path string, a ...interface{}) string {
path = fmt.Sprintf(path, a...)
if env.Config.CDN.Host != "" {
if env.IsSingleHostMode() {
return ctx.Request.URL.Scheme + "://" + env.Config.CDN.Host + path
}
return ctx.Request.URL.Scheme + "://cdn." + env.Config.CDN.Host + path
}
return ctx.BaseURL() + path
}
// TenantAssetsURL return the full URL to a tenant-specific static asset
func (ctx *Context) TenantAssetsURL(path string, a ...interface{}) string {
path = fmt.Sprintf(path, a...)
if env.Config.CDN.Host != "" && ctx.Tenant() != nil {
if env.IsSingleHostMode() {
return ctx.Request.URL.Scheme + "://" + env.Config.CDN.Host + path
}
return ctx.Request.URL.Scheme + "://" + ctx.Tenant().Subdomain + "." + env.Config.CDN.Host + path
}
return ctx.BaseURL() + path
}
// LogoURL return the full URL to the tenant-specific logo URL
func (ctx *Context) LogoURL() string {
if ctx.Tenant() != nil && ctx.Tenant().LogoBlobKey != "" {
return ctx.TenantAssetsURL("/images/%s?size=200", ctx.Tenant().LogoBlobKey)
}
return "https://getfider.com/images/logo-100x100.png"
}
// FaviconURL return the full URL to the tenant-specific favicon URL
func (ctx *Context) FaviconURL() string {
if ctx.Tenant() != nil && ctx.Tenant().LogoBlobKey != "" {
return ctx.TenantAssetsURL("/favicon/%s", ctx.Tenant().LogoBlobKey)
}
return ctx.GlobalAssetsURL("/favicon")
}
// SetCanonicalURL sets the canonical link on the HTTP Response Headers
func (ctx *Context) SetCanonicalURL(rawurl string) {
u, err := url.Parse(rawurl)
if err == nil {
if u.Host == "" {
baseURL, ok := ctx.Get("Canonical-BaseURL").(string)
if !ok {
baseURL = ctx.BaseURL()
}
if len(rawurl) > 0 && rawurl[0] != '/' {
rawurl = "/" + rawurl
}
rawurl = baseURL + rawurl
} else {
ctx.Set("Canonical-BaseURL", u.Scheme+"://"+u.Host)
}
ctx.Set("Canonical-URL", rawurl)
}
}