-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathannouncement.go
492 lines (443 loc) · 14 KB
/
announcement.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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020,2021,2022 Marcus Soll
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Top-Ranger/announcementgo/counter"
"github.com/Top-Ranger/announcementgo/helper"
"github.com/Top-Ranger/announcementgo/registry"
"github.com/Top-Ranger/announcementgo/server"
"github.com/Top-Ranger/announcementgo/templates"
"github.com/Top-Ranger/announcementgo/translation"
)
var knownKeys = make(map[string]bool)
type announcement struct {
Key string
ShortDescription string
Plugins []string
UsersSeeErrors bool
UsersCanDeleteMessages bool
PasswordMethod string
PasswordAdmin []string
PasswordUser []string
plugins []registry.Plugin
messages []templates.AnnouncementMessage
l *sync.Mutex
}
// LoadAnnouncements loads all announcements in a path.
// The announcements are loaded in memory and registered to the server. You can not access them directly.
// This function is not save to be used in parallel.
// It should be used at the beginning of the lifetime of the application (before the server is started).
func LoadAnnouncements(path string) error {
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if filepath.Ext(path) != ".json" {
return nil
}
b, err := os.ReadFile(path)
if err != nil {
return err
}
a := new(announcement)
err = json.Unmarshal(b, a)
if err != nil {
return err
}
err = a.Initialise()
if err != nil {
return fmt.Errorf("%s: %w", path, err)
}
return nil
})
if err != nil {
return fmt.Errorf("announcement: %w", err)
}
return nil
}
func (a *announcement) Initialise() error {
a.l = new(sync.Mutex)
a.l.Lock()
defer a.l.Unlock()
errorChannel := make(chan string, 100)
if a.Key == "" {
return fmt.Errorf("invalid key")
}
if strings.ContainsAny(a.Key, "#") {
return fmt.Errorf("invalid character in key key")
}
a.Key = url.PathEscape(a.Key)
ok := knownKeys[a.Key]
if ok {
return fmt.Errorf("key already in use")
}
knownKeys[a.Key] = true
a.loadErrors()
if !a.UsersSeeErrors && a.UsersCanDeleteMessages {
return fmt.Errorf("users can only delete messages when they can see errors (%s)", a.Key)
}
plugins := make(map[string]bool, len(a.Plugins))
ok = registry.PasswordMethodExists(a.PasswordMethod)
if !ok {
return fmt.Errorf("password method '%s' not known", a.PasswordMethod)
}
for i := range a.Plugins {
if plugins[a.Plugins[i]] {
return fmt.Errorf("announcement: plugin %s found twice", a.Plugins[i])
}
pf, ok := registry.GetPlugin(a.Plugins[i])
if !ok {
return fmt.Errorf("announcement: unknown plugin %s", a.Plugins[i])
}
p, err := pf(a.Key, a.ShortDescription, errorChannel)
if err != nil {
return fmt.Errorf("announcement: plugin %s has error %w", a.Plugins[i], err)
}
a.plugins = append(a.plugins, p)
}
err := server.AddHandle(a.Key, "", func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
// Test login
loggedin, admin := server.GetLogin(a.Key, r)
if !loggedin {
td := templates.LoginTemplateStruct{
Key: a.Key,
ShortDescription: a.ShortDescription,
Translation: translation.GetDefaultTranslation(),
}
err := templates.LoginTemplate.Execute(rw, td)
if err != nil {
log.Printf("login template: %s", err.Error())
}
return
}
// Process Request
switch r.Method {
case http.MethodGet:
a.l.Lock()
td := templates.AnnouncementTemplateStruct{
Key: a.Key,
Admin: admin,
ShortDescription: a.ShortDescription,
Translation: translation.GetDefaultTranslation(),
Messages: a.messages,
}
if admin || a.UsersSeeErrors {
td.ShowErrors = true
}
if admin || (a.UsersSeeErrors && a.UsersCanDeleteMessages) {
td.EnableDeleteMessages = true
}
a.l.Unlock()
if admin {
for i := range a.plugins {
td.PluginConfig = append(td.PluginConfig, a.plugins[i].GetConfig())
}
}
err := r.ParseForm()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
t := templates.TextTemplateStruct{Text: "500 Internal Server Error", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
}
err = templates.AnnouncementTemplate.Execute(rw, td)
if err != nil {
log.Println("announcement get:", err.Error())
}
return
case http.MethodPost:
err := r.ParseForm()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
t := templates.TextTemplateStruct{Text: "500 Internal Server Error", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
switch r.Form.Get("target") {
case "publish":
if r.Form.Get("dsgvo") == "" {
rw.WriteHeader(http.StatusPreconditionFailed)
td := templates.TextTemplateStruct{Text: "412 Precondition Failed", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, td)
return
}
subject := r.Form.Get("subject")
message := r.Form.Get("message")
if message == "" || subject == "" {
rw.WriteHeader(http.StatusBadRequest)
td := templates.TextTemplateStruct{Text: "400 Bad Request", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, td)
return
}
an := registry.Announcement{
Header: subject,
Message: message,
Time: time.Now(),
}
id, err := registry.CurrentDataSafe.SaveAnnouncement(a.Key, an)
if err != nil {
log.Println("announcement save:", err.Error())
}
for i := range a.plugins {
go a.plugins[i].NewAnnouncement(an, id)
}
a.l.Lock()
counter.StartProcess()
a.addMessage(translation.GetDefaultTranslation().AnnouncementPublished, false)
counter.EndProcess()
a.l.Unlock()
http.Redirect(rw, r, fmt.Sprintf("/%s", a.Key), http.StatusSeeOther)
return
default:
t := r.Form.Get("target")
for i := range a.Plugins {
if t == a.Plugins[i] {
err = a.plugins[i].ProcessConfigChange(r)
if err != nil {
log.Printf("announcement plugin config (%s): %s", a.Plugins[i], err.Error())
a.l.Lock()
counter.StartProcess()
a.addMessage(err.Error(), true)
counter.EndProcess()
a.l.Unlock()
http.Redirect(rw, r, fmt.Sprintf("/%s", a.Key), http.StatusSeeOther)
return
}
http.Redirect(rw, r, fmt.Sprintf("/%s", a.Key), http.StatusSeeOther)
return
}
}
rw.WriteHeader(http.StatusBadRequest)
td := templates.TextTemplateStruct{Text: "400 Bad Request", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, td)
return
}
default:
rw.WriteHeader(http.StatusBadRequest)
t := templates.TextTemplateStruct{Text: "400 Bad Request", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
})
if err != nil {
return err
}
err = server.AddHandle(a.Key, "login", func(rw http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
rw.WriteHeader(http.StatusBadRequest)
t := templates.TextTemplateStruct{Text: "400 Bad Request", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
err := r.ParseForm()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
t := templates.TextTemplateStruct{Text: "500 Internal Server Error", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
password := r.Form.Get("password")
if password == "" {
rw.WriteHeader(http.StatusForbidden)
t := templates.TextTemplateStruct{Text: "403 Forbidden", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
for i := range a.PasswordUser {
ok, err := registry.ComparePasswords(a.PasswordMethod, password, a.PasswordUser[i])
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
t := templates.TextTemplateStruct{Text: "500 Internal Server Error", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
if ok {
err := server.SetLoginCookie(a.Key, false, rw, r)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
t := templates.TextTemplateStruct{Text: "500 Internal Server Error", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
http.Redirect(rw, r, fmt.Sprintf("/%s", a.Key), http.StatusSeeOther)
return
}
}
for i := range a.PasswordAdmin {
ok, err := registry.ComparePasswords(a.PasswordMethod, password, a.PasswordAdmin[i])
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
t := templates.TextTemplateStruct{Text: "500 Internal Server Error", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
if ok {
err := server.SetLoginCookie(a.Key, true, rw, r)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
t := templates.TextTemplateStruct{Text: "500 Internal Server Error", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
http.Redirect(rw, r, fmt.Sprintf("/%s", a.Key), http.StatusSeeOther)
return
}
}
if config.LogFailedLogin {
log.Printf("Failed login from %s", helper.GetRealIP(r))
}
rw.WriteHeader(http.StatusForbidden)
t := templates.TextTemplateStruct{Text: "403 Forbidden", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
})
if err != nil {
return err
}
err = server.AddHandle(a.Key, "logout", func(rw http.ResponseWriter, r *http.Request) {
server.RemoveLoginCookie(a.Key, rw, r)
http.Redirect(rw, r, fmt.Sprintf("/%s", a.Key), http.StatusSeeOther)
})
if err != nil {
return err
}
err = server.AddHandle(a.Key, "history.html", func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
loggedin, _ := server.GetLogin(a.Key, r)
if !loggedin {
rw.WriteHeader(http.StatusForbidden)
t := templates.TextTemplateStruct{Text: "403 Forbidden", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
h, err := registry.CurrentDataSafe.GetAllAnnouncements(a.Key)
if err != nil {
log.Printf("announcement history (%s): %s", a.Key, err.Error())
rw.WriteHeader(http.StatusInternalServerError)
t := templates.TextTemplateStruct{Text: "500 Internal Server Error", Translation: translation.GetDefaultTranslation()}
templates.TextTemplate.Execute(rw, t)
return
}
for i := 0; i < len(h)/2; i++ {
h[i], h[len(h)-1-i] = h[len(h)-1-i], h[i]
}
td := templates.HistoryTemplateStruct{
Key: a.Key,
ShortDescription: a.ShortDescription,
History: h,
Translation: translation.GetDefaultTranslation(),
}
err = templates.HistoryTemplate.Execute(rw, td)
if err != nil {
log.Printf("announcement history template (%s): %s", a.Key, err.Error())
}
})
if err != nil {
return err
}
err = server.AddHandle(a.Key, "deleteErrors", func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
loggedin, admin := server.GetLogin(a.Key, r)
if !loggedin {
rw.WriteHeader(http.StatusForbidden)
return
}
if !(admin || (a.UsersSeeErrors && a.UsersCanDeleteMessages)) {
rw.WriteHeader(http.StatusForbidden)
return
}
counter.StartProcess()
a.l.Lock()
a.messages = nil
a.saveMessages()
a.l.Unlock()
counter.EndProcess()
rw.WriteHeader(http.StatusOK)
})
if err != nil {
return err
}
go announcemetWorker(a, errorChannel)
log.Println("announcement: sucessfully loaded", a.Key)
return nil
}
func announcemetWorker(a *announcement, errorChannel chan string) {
for {
e := <-errorChannel
counter.StartProcess()
a.l.Lock()
a.addMessage(e, true)
a.l.Unlock()
counter.EndProcess()
}
}
func (a *announcement) loadErrors() {
// Caller needs to lock
counter.StartProcess()
defer counter.EndProcess()
b, err := registry.CurrentDataSafe.GetConfig(a.Key, "internal##messages")
if err != nil {
log.Printf("loading errors (%s): %s", a.Key, err.Error())
return
}
if len(b) == 0 {
a.messages = nil
return
}
buf := bytes.NewBuffer(b)
dec := gob.NewDecoder(buf)
err = dec.Decode(&a.messages)
if err != nil {
log.Printf("decoding errors (%s): %s", a.Key, err.Error())
return
}
}
func (a *announcement) saveMessages() {
// Caller needs to lock
if a.messages == nil {
err := registry.CurrentDataSafe.SetConfig(a.Key, "internal##messages", nil)
if err != nil {
log.Printf("saving nil errors (%s): %s", a.Key, err.Error())
return
}
}
var config bytes.Buffer
enc := gob.NewEncoder(&config)
err := enc.Encode(&a.messages)
if err != nil {
log.Printf("encoding errors (%s): %s", a.Key, err.Error())
return
}
err = registry.CurrentDataSafe.SetConfig(a.Key, "internal##messages", config.Bytes())
if err != nil {
log.Printf("saving errors (%s): %s", a.Key, err.Error())
return
}
}
func (a *announcement) addMessage(text string, error bool) {
a.messages = append(a.messages, templates.AnnouncementMessage{Text: fmt.Sprintf("%s: %s", time.Now().Format(time.RFC3339), text), Error: error})
a.saveMessages()
}