This repository has been archived by the owner on Oct 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
mod.go
336 lines (314 loc) · 10.5 KB
/
mod.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/jackc/pgx/v4"
)
func modSendWebhook(content string) error {
return sendWebhook(cfg.GetDSString("", "webhooks", "actions"), content)
}
func isSuperadmin(context context.Context, username string) bool {
ret := false
derr := dbpool.QueryRow(context, "SELECT superadmin FROM accounts WHERE username = $1", username).Scan(&ret)
if derr != nil {
if errors.Is(derr, pgx.ErrNoRows) {
return false
}
log.Printf("Error checking superadmin: %v", derr)
}
return ret
}
func basicSuperadminHandler(page string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if !isSuperadmin(r.Context(), sessionGetUsername(r)) {
respondWithForbidden(w, r)
return
}
basicLayoutLookupRespond(page, w, r, nil)
}
}
func SuperadminCheck(next func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if !isSuperadmin(r.Context(), sessionGetUsername(r)) {
respondWithForbidden(w, r)
return
}
next(w, r)
}
}
func APISuperadminCheck(next func(w http.ResponseWriter, r *http.Request) (int, any)) func(w http.ResponseWriter, r *http.Request) (int, any) {
return func(w http.ResponseWriter, r *http.Request) (int, any) {
if !isSuperadmin(r.Context(), sessionGetUsername(r)) {
return http.StatusForbidden, nil
}
return next(w, r)
}
}
func APIgetAccounts2(_ http.ResponseWriter, r *http.Request) (int, any) {
return genericViewRequest[struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
AccountCreated time.Time `json:"account_created"`
LastSeen *time.Time `json:"last_seen"`
EmailConfirmed *time.Time `json:"email_confirmed"`
Terminated bool `json:"terminated"`
AllowHostRequest bool `json:"allow_host_request"`
DisplayName *string `json:"display_name"`
LastReport *time.Time `json:"last_report"`
LastRequest *time.Time `json:"last_request"`
Identities string `json:"identities"`
}](r, genericRequestParams{
tableName: "accounts_view",
limitClamp: 1500,
sortDefaultOrder: "desc",
sortDefaultColumn: "id",
sortColumns: []string{"id", "account_created"},
filterColumnsFull: []string{"id"},
filterColumnsStartsWith: []string{"username", "email", "display_name"},
searchColumn: "username || email || display_name",
searchSimilarity: 0.3,
columnMappings: map[string]string{
"id": "id",
"username": "username",
"email": "email",
"account_created": "account_created",
"last_seen": "last_seen",
"email_confirmed": "email_confirmed",
"terminated": "terminated",
"last_report": "last_report",
"last_request": "last_request",
},
})
}
func APIresendEmailConfirm(_ http.ResponseWriter, r *http.Request) (int, any) {
params := mux.Vars(r)
id, err := strconv.Atoi(params["id"])
if err != nil {
return 400, nil
}
modSendWebhook(fmt.Sprintf("Administrator `%s` resent activation email for account `%v`", sessionGetUsername(r), id))
return 200, modResendEmailConfirm(id)
}
func modAccountsPOST(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(4096)
if err != nil {
respondWithCodeAndPlaintext(w, 400, "Failed to parse form")
return
}
if !stringOneOf(r.FormValue("param"), "bypass_ispban", "allow_host_request", "terminated", "no_request_reason") {
respondWithCodeAndPlaintext(w, 400, "Param is bad ("+r.FormValue("param")+")")
return
}
if stringOneOf(r.FormValue("param"), "bypass_ispban", "allow_host_request", "terminated") {
if !stringOneOf(r.FormValue("val"), "true", "false") {
respondWithCodeAndPlaintext(w, 400, "Val is bad")
return
}
}
if r.FormValue("name") == "" {
respondWithCodeAndPlaintext(w, 400, "Name is missing")
return
}
tag, derr := dbpool.Exec(context.Background(), "UPDATE accounts SET "+r.FormValue("param")+" = $1 WHERE username = $2", r.FormValue("val"), r.FormValue("name"))
if derr != nil {
logRespondWithCodeAndPlaintext(w, 500, "Database query error: "+derr.Error())
return
}
if !tag.Update() || tag.RowsAffected() != 1 {
logRespondWithCodeAndPlaintext(w, 500, "Sus result "+tag.String())
return
}
w.WriteHeader(200)
err = modSendWebhook(fmt.Sprintf("Administrator `%s` changed `%s` to `%s` for user `%s`.", sessionGetUsername(r), r.FormValue("param"), r.FormValue("val"), r.FormValue("name")))
if err != nil {
log.Println(err)
}
if r.FormValue("param") == "norequest_reason" {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msggreen": true, "msg": "Success"})
w.Header().Set("Refresh", "1; /moderation/accounts")
}
}
func modNewsPOST(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
respondWithCodeAndPlaintext(w, 400, "Failed to parse form: "+err.Error())
return
}
tag, err := dbpool.Exec(r.Context(), `insert into announcements (title, content, color, when_posted) values ($1, $2, $3, $4)`, r.FormValue("title"), r.FormValue("content"), r.FormValue("color"), r.FormValue("date"))
result := ""
if err != nil {
result = err.Error()
} else {
result = tag.String()
}
msg := template.HTML(result + `<br><a href="/moderation/news">back</a>`)
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"nocenter": true, "plaintext": true, "msg": msg})
}
func modBansPOST(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
respondWithCodeAndPlaintext(w, 400, "Failed to parse form: "+err.Error())
return
}
dur := parseFormInt(r, "duration")
var inExpires *time.Time
if dur != nil && *dur != 0 {
d := time.Now().Add(time.Duration(*dur) * time.Second)
inExpires = &d
}
inAccount := parseFormInt(r, "account")
inIdentity := parseFormInt(r, "identity")
if inAccount == nil && inIdentity == nil {
respondWithCodeAndPlaintext(w, 400, "Both identity and account are nil")
return
}
inForbidsJoining := parseFormBool(r, "forbids-joining")
inForbidsChatting := parseFormBool(r, "forbids-chatting")
inForbidsPlaying := parseFormBool(r, "forbids-playing")
tag, err := dbpool.Exec(r.Context(),
`insert into bans
(account, identity, time_expires, reason, forbids_joining, forbids_chatting, forbids_playing) values
($1, $2, $3, $4, $5, $6, $7)`, inAccount, inIdentity, inExpires, r.FormValue("reason"),
inForbidsJoining, inForbidsChatting, inForbidsPlaying)
result := ""
if err != nil {
result = err.Error()
} else {
result = tag.String()
}
msg := template.HTML(result + `<br><a href="/moderation/bans">back</a>`)
modSendWebhook(fmt.Sprintf("Administrator `%s` banned"+
"\naccount `%+#v` identity `%+#v`"+
"\nfor `%+#v` (ends at `%+#v`)"+
"\nduration `%+#v`"+
"\njoining `%+#v` `%+#v`"+
"\nchatting `%+#v` `%+#v`"+
"\nplaying `%+#v` `%+#v`",
sessionGetUsername(r),
r.FormValue("account"), r.FormValue("identity"),
r.FormValue("reason"), dur, inExpires,
r.FormValue("forbids-joining"), inForbidsJoining,
r.FormValue("forbids-chatting"), inForbidsChatting,
r.FormValue("forbids-playing"), inForbidsPlaying))
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"nocenter": true, "plaintext": true, "msg": msg})
}
func APIgetBans(_ http.ResponseWriter, r *http.Request) (int, any) {
var ret []byte
derr := dbpool.QueryRow(r.Context(), `SELECT array_to_json(array_agg(to_json(bans))) FROM bans;`).Scan(&ret)
if derr != nil {
return 500, derr
}
return 200, ret
}
func APIgetLogs2(_ http.ResponseWriter, r *http.Request) (int, any) {
return genericViewRequest[struct {
ID int `json:"id"`
Whensent time.Time `json:"whensent"`
Pkey string `json:"pkey"`
Name string `json:"name"`
Msgtype *string `json:"msgtype"`
Msg string `json:"msg"`
}](r, genericRequestParams{
tableName: "composelog",
limitClamp: 1500,
sortDefaultOrder: "desc",
sortDefaultColumn: "whensent",
sortColumns: []string{"id", "whensent"},
filterColumnsFull: []string{"id", "msg"},
filterColumnsStartsWith: []string{"name", "pkey", "msgtype"},
searchColumn: "name || msg",
searchSimilarity: 0.3,
columnMappings: map[string]string{
"id": "id",
"whensent": "whensent",
"pkey": "pkey",
"name": "name",
"msgtype": "msgtype",
"msg": "msg",
},
})
}
func APIgetIdentities(_ http.ResponseWriter, r *http.Request) (int, any) {
return genericViewRequest[struct {
ID int
Name string
Pkey []byte
Hash string
Account *int
}](r, genericRequestParams{
tableName: "identities_view",
limitClamp: 500,
sortDefaultOrder: "desc",
sortDefaultColumn: "id",
sortColumns: []string{"id", "name", "account"},
filterColumnsFull: []string{"id", "account"},
filterColumnsStartsWith: []string{"name", "pkey", "hash"},
searchColumn: "name",
searchSimilarity: 0.3,
columnMappings: map[string]string{
"ID": "id",
"Name": "name",
"Pkey": "pkey",
"Hash": "hash",
"Account": "account",
},
})
}
func modResendEmailConfirm(accountID int) error {
var email, emailcode string
err := dbpool.QueryRow(context.Background(), `SELECT email, email_confirm_code FROM accounts WHERE id = $1`, accountID).Scan(&email, &emailcode)
if err != nil {
if err == pgx.ErrNoRows {
return errors.New("no account")
}
return err
}
return sendgridConfirmcode(email, emailcode)
}
func modIdentitiesHandler(w http.ResponseWriter, r *http.Request) {
}
func modReloadConfig(w http.ResponseWriter, r *http.Request) {
if !isSuperadmin(r.Context(), sessionGetUsername(r)) {
w.WriteHeader(200)
w.Write([]byte("no auth\n\n"))
}
err := cfg.SetFromFileJSON("config.json")
w.WriteHeader(200)
w.Write([]byte(fmt.Sprintf("%v\n\n", err)))
}
func APImodInstances(w http.ResponseWriter, r *http.Request) (int, any) {
cl := http.Client{Timeout: 2 * time.Second}
h, ok := cfg.GetString("backend", "urlBase")
if !ok {
return 500, "backend url base not set"
}
rsp, err := cl.Get(h + "instances")
if err != nil {
return 500, err
}
rspbb, err := io.ReadAll(rsp.Body)
if err != nil {
return 500, err
}
i := map[string]map[string]any{}
err = json.Unmarshal(rspbb, &i)
if err != nil {
return 500, err
}
ii := []map[string]any{}
for k, v := range i {
v["ID"] = k
ii = append(ii, v)
}
return 200, ii
}