-
Notifications
You must be signed in to change notification settings - Fork 16
/
routes.go
364 lines (331 loc) · 9.87 KB
/
routes.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
/*
*
* Gosora Route Handlers
* Copyright Azareal 2016 - 2020
*
*/
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"strconv"
"strings"
"sync"
"time"
"unicode"
c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/common/phrases"
)
// A blank list to fill out that parameter in Page for routes which don't use it
var tList []interface{}
var successJSONBytes = []byte(`{"success":1}`)
// TODO: Refactor this
// TODO: Use the phrase system
var phraseLoginAlerts = []byte(`{"msgs":[{"msg":"Login to see your alerts","path":"/accounts/login"}],"count":0}`)
var alertStrPool = sync.Pool{}
// TODO: Refactor this endpoint
// TODO: Move this into the routes package
func routeAPI(w http.ResponseWriter, r *http.Request, user *c.User) c.RouteError {
// TODO: Don't make this too JSON dependent so that we can swap in newer more efficient formats
w.Header().Set("Content-Type", "application/json")
err := r.ParseForm()
if err != nil {
return c.PreErrorJS("Bad Form", w, r)
}
action := r.FormValue("a")
if action == "" {
action = "get"
}
if action != "get" && action != "set" {
return c.PreErrorJS("Invalid Action", w, r)
}
switch r.FormValue("m") {
// TODO: Split this into it's own function
case "dismiss-alert":
id, err := strconv.Atoi(r.FormValue("id"))
if err != nil {
return c.PreErrorJS("Invalid id", w, r)
}
res, err := stmts.deleteActivityStreamMatch.Exec(user.ID, id)
if err != nil {
return c.InternalError(err, w, r)
}
count, err := res.RowsAffected()
if err != nil {
return c.InternalError(err, w, r)
}
// Don't want to throw an internal error due to a socket closing
if c.EnableWebsockets && count > 0 {
c.DismissAlert(user.ID, id)
}
w.Write(successJSONBytes)
// TODO: Split this into it's own function
case "alerts": // A feed of events tailored for a specific user
if !user.Loggedin {
h := w.Header()
if gzw, ok := w.(c.GzipResponseWriter); ok {
w = gzw.ResponseWriter
h.Del("Content-Encoding")
}
etag := "\"1583653869-n\""
//etag = c.StartEtag
h.Set("ETag", etag)
if match := r.Header.Get("If-None-Match"); match != "" {
if strings.Contains(match, etag) {
w.WriteHeader(http.StatusNotModified)
return nil
}
}
w.Write(phraseLoginAlerts)
return nil
}
var count int
err = stmts.getActivityCountByWatcher.QueryRow(user.ID).Scan(&count)
if err == ErrNoRows {
return c.PreErrorJS("Unable to get the activity count", w, r)
} else if err != nil {
return c.InternalErrorJS(err, w, r)
}
if count == 0 {
if gzw, ok := w.(c.GzipResponseWriter); ok {
w = gzw.ResponseWriter
w.Header().Del("Content-Encoding")
}
_, _ = io.WriteString(w, `{}`)
return nil
}
rCreatedAt, _ := strconv.ParseInt(r.FormValue("t"), 10, 64)
rCount, _ := strconv.Atoi(r.FormValue("c"))
//log.Print("rCreatedAt:", rCreatedAt)
//log.Print("rCount:", rCount)
var actors []int
var alerts []*c.Alert
var createdAt time.Time
var topCreatedAt int64
if count != 0 {
rows, err := stmts.getActivityFeedByWatcher.Query(user.ID, 12)
if err != nil {
return c.InternalErrorJS(err, w, r)
}
defer rows.Close()
for rows.Next() {
al := &c.Alert{}
err = rows.Scan(&al.ASID, &al.ActorID, &al.TargetUserID, &al.Event, &al.ElementType, &al.ElementID, &createdAt)
if err != nil {
return c.InternalErrorJS(err, w, r)
}
uCreatedAt := createdAt.Unix()
//log.Print("uCreatedAt", uCreatedAt)
//if rCreatedAt == 0 || rCreatedAt < uCreatedAt {
alerts = append(alerts, al)
actors = append(actors, al.ActorID)
//}
if uCreatedAt > topCreatedAt {
topCreatedAt = uCreatedAt
}
}
if err = rows.Err(); err != nil {
return c.InternalErrorJS(err, w, r)
}
}
if len(alerts) == 0 || (rCreatedAt != 0 && rCreatedAt >= topCreatedAt && count == rCount) {
if gzw, ok := w.(c.GzipResponseWriter); ok {
w = gzw.ResponseWriter
w.Header().Del("Content-Encoding")
}
_, _ = io.WriteString(w, `{}`)
return nil
}
// Might not want to error here, if the account was deleted properly, we might want to figure out how we should handle deletions in general
list, err := c.Users.BulkGetMap(actors)
if err != nil {
log.Print("actors:", actors)
return c.InternalErrorJS(err, w, r)
}
var sb *strings.Builder
ii := alertStrPool.Get()
if ii == nil {
sb = &strings.Builder{}
} else {
sb = ii.(*strings.Builder)
sb.Reset()
}
sb.Grow(c.AlertsGrowHint + (len(alerts) * (c.AlertsGrowHint2 + 1)) - 1)
sb.WriteString(`{"msgs":[`)
var ok bool
for i, alert := range alerts {
if i != 0 {
sb.WriteRune(',')
}
alert.Actor, ok = list[alert.ActorID]
if !ok {
return c.InternalErrorJS(errors.New("No such actor"), w, r)
}
err := c.BuildAlertSb(sb, alert, user)
if err != nil {
return c.LocalErrorJS(err.Error(), w, r)
}
}
sb.WriteString(`],"count":`)
sb.WriteString(strconv.Itoa(count))
sb.WriteString(`,"tc":`)
//rCreatedAt
sb.WriteString(strconv.Itoa(int(topCreatedAt)))
sb.WriteRune('}')
_, _ = io.WriteString(w, sb.String())
alertStrPool.Put(sb)
default:
return c.PreErrorJS("Invalid Module", w, r)
}
return nil
}
// TODO: Remove this line after we move routeAPIPhrases to the routes package
var cacheControlMaxAge = "max-age=" + strconv.Itoa(int(c.Day))
// TODO: Be careful with exposing the panel phrases here, maybe move them into a different namespace? We also need to educate the admin that phrases aren't necessarily secret
// TODO: Move to the routes package
var phraseWhitelist = []string{
"topic",
"status",
"alerts",
"paginator",
"analytics",
"panel", // We're going to handle this specially below as this is a security boundary
}
func routeAPIPhrases(w http.ResponseWriter, r *http.Request, user *c.User) c.RouteError {
// TODO: Don't make this too JSON dependent so that we can swap in newer more efficient formats
h := w.Header()
h.Set("Content-Type", "application/json")
err := r.ParseForm()
if err != nil {
return c.PreErrorJS("Bad Form", w, r)
}
query := r.FormValue("q")
if query == "" {
return c.PreErrorJS("No query provided", w, r)
}
var negations, positives []string
for _, queryBit := range strings.Split(query, ",") {
queryBit = strings.TrimSpace(queryBit)
if queryBit[0] == '!' && len(queryBit) > 1 {
queryBit = strings.TrimPrefix(queryBit, "!")
for _, ch := range queryBit {
if !unicode.IsLetter(ch) && ch != '-' && ch != '_' {
return c.PreErrorJS("No symbols allowed, only - and _", w, r)
}
}
negations = append(negations, queryBit)
} else {
for _, ch := range queryBit {
if !unicode.IsLetter(ch) && ch != '-' && ch != '_' {
return c.PreErrorJS("No symbols allowed, only - and _", w, r)
}
}
positives = append(positives, queryBit)
}
}
if len(positives) == 0 {
return c.PreErrorJS("You haven't requested any phrases", w, r)
}
h.Set("Cache-Control", cacheControlMaxAge) //Cache-Control: max-age=31536000
var etag string
_, ok := w.(c.GzipResponseWriter)
if ok {
etag = "\"" + strconv.FormatInt(phrases.GetCurrentLangPack().ModTime.Unix(), 10) + "-ng\""
} else {
etag = "\"" + strconv.FormatInt(phrases.GetCurrentLangPack().ModTime.Unix(), 10) + "-n\""
}
var plist map[string]string
var notModified, private bool
posLoop := func(positive string) c.RouteError {
// ! Constrain it to a subset of phrases for now
for _, item := range phraseWhitelist {
if strings.HasPrefix(positive, item) {
// TODO: Break this down into smaller security boundaries based on control panel sections?
// TODO: Do we have to be so strict with panel phrases?
if strings.HasPrefix(positive, "panel") {
private = true
ok = user.IsSuperMod
} else {
ok = true
if notModified {
return nil
}
w.Header().Set("ETag", etag)
match := r.Header.Get("If-None-Match")
if match != "" && strings.Contains(match, etag) {
notModified = true
return nil
}
}
break
}
}
if !ok {
return c.PreErrorJS("Outside of phrase prefix whitelist", w, r)
}
return nil
}
// A little optimisation to avoid copying entries from one map to the other, if we don't have to mutate it
if len(positives) > 1 {
plist = make(map[string]string)
for _, positive := range positives {
rerr := posLoop(positive)
if rerr != nil {
return rerr
}
pPhrases, ok := phrases.GetTmplPhrasesByPrefix(positive)
if !ok {
return c.PreErrorJS("No such prefix", w, r)
}
for name, phrase := range pPhrases {
plist[name] = phrase
}
}
} else {
rerr := posLoop(positives[0])
if rerr != nil {
return rerr
}
pPhrases, ok := phrases.GetTmplPhrasesByPrefix(positives[0])
if !ok {
return c.PreErrorJS("No such prefix", w, r)
}
plist = pPhrases
}
if private {
w.Header().Set("Cache-Control", "private")
} else if notModified {
w.WriteHeader(http.StatusNotModified)
return nil
}
for _, negation := range negations {
for name, _ := range plist {
if strings.HasPrefix(name, negation) {
delete(plist, name)
}
}
}
// TODO: Cache the output of this, especially for things like topic, so we don't have to waste more time than we need on this
jsonBytes, err := json.Marshal(plist)
if err != nil {
return c.InternalError(err, w, r)
}
w.Write(jsonBytes)
return nil
}
// A dedicated function so we can shake things up every now and then to make the token harder to parse
// TODO: Are we sure we want to do this by ID, just in case we reuse this and have multiple antispams on the page?
func routeJSAntispam(w http.ResponseWriter, r *http.Request, user *c.User) c.RouteError {
h := sha256.New()
h.Write([]byte(c.JSTokenBox.Load().(string)))
h.Write([]byte(user.GetIP()))
jsToken := hex.EncodeToString(h.Sum(nil))
innerCode := "`document.getElementByld('golden-watch').value='" + jsToken + "';`"
io.WriteString(w, `let hihi=`+innerCode+`;hihi=hihi.replace('ld','Id');eval(hihi);`)
return nil
}