-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
audit_log.go
101 lines (81 loc) · 1.88 KB
/
audit_log.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
package servermanager
import (
"net/http"
"sort"
"time"
"github.com/sirupsen/logrus"
)
type AuditEntry struct {
UserGroup Group
Method string
URL string
User string
Time time.Time
}
var ignoredURLs = [5]string{
"/audit-logs",
"/quick",
"/logs",
"/custom",
"/api/logs",
}
type AuditLogHandler struct {
*BaseHandler
store Store
}
func NewAuditLogHandler(baseHandler *BaseHandler, store Store) *AuditLogHandler {
return &AuditLogHandler{
BaseHandler: baseHandler,
store: store,
}
}
func (alh *AuditLogHandler) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, url := range ignoredURLs {
if url == r.URL.String() {
next.ServeHTTP(w, r)
return
}
}
account := AccountFromRequest(r)
if account == nil {
next.ServeHTTP(w, r)
return
}
entry := &AuditEntry{
UserGroup: account.Group(),
Method: r.Method,
URL: r.URL.String(),
User: account.Name,
Time: time.Now(),
}
err := alh.store.AddAuditEntry(entry)
if err != nil {
logrus.WithError(err).Error("Couldn't add audit entry for request")
}
next.ServeHTTP(w, r)
})
}
type auditLogTemplateVars struct {
BaseTemplateVars
AuditLogs []*AuditEntry
}
func (alh *AuditLogHandler) viewLogs(w http.ResponseWriter, r *http.Request) {
// load server audits
auditLogs, err := alh.store.GetAuditEntries()
if err != nil {
logrus.WithError(err).Error("couldn't find audit logs")
AddErrorFlash(w, r, "Couldn't open audit logs")
}
// sort to newest first
sort.Slice(auditLogs, func(i, j int) bool {
return auditLogs[i].Time.After(auditLogs[j].Time)
})
// render audit log page
alh.viewRenderer.MustLoadTemplate(w, r, "server/audit-logs.html", &auditLogTemplateVars{
BaseTemplateVars: BaseTemplateVars{
WideContainer: true,
},
AuditLogs: auditLogs,
})
}