Repository navigation
Expand file tree
/
Copy pathaudit.go
More file actions
65 lines (60 loc) · 1.66 KB
/
Copy pathaudit.go
File metadata and controls
65 lines (60 loc) · 1.66 KB
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
package access
import (
"webtyp.com/time"
)
// Actions recorded by this module. An app records its own actions with
// Record and its own constants.
const (
AuditRoleSave = "role.save"
AuditRoleDelete = "role.delete"
AuditAssign = "role.assign"
AuditRevoke = "role.revoke"
)
// AuditListLimit is how many rows list_audit returns, newest first.
const AuditListLimit = 200
// Record writes one audit row. actorUserID is the user who acted ("" for the
// system); the row stores that user's e-mail so it stays readable after the
// user is gone.
//
// Example: err := m.Record(ctx.UserID(), "project.create", "proj_x", "Mi proyecto")
func (m *Module) Record(actorUserID, action, target, detail string) error {
actor := ""
if actorUserID != "" {
if u, err := m.users.UserByID(actorUserID); err == nil {
actor = u.Email
}
}
now := time.NowNano()
if now <= m.lastAuditNano {
now = m.lastAuditNano + 1
}
m.lastAuditNano = now
return m.db.Create(&AuditEntry{
Id: m.ids.NewID(),
ActorEmail: actor,
Action: action,
Target: target,
Detail: detail,
CreatedAt: now,
})
}
// ListAudit returns the newest AuditListLimit rows, newest first.
func (m *Module) ListAudit(search, after string, limit int64) ([]AuditEntry, error) {
qb := m.db.Query(&AuditEntry{})
if search != "" {
qb = qb.Where(AuditEntry_.ActorEmail).Like("%" + search + "%")
}
if after != "" {
qb = qb.Where(AuditEntry_.Id).Gt(after)
}
qb = qb.OrderBy(AuditEntry_.Id).Asc().Limit(int(limit))
ptrs, err := ReadAllAuditEntry(qb)
if err != nil {
return nil, err
}
out := make([]AuditEntry, len(ptrs))
for i, p := range ptrs {
out[i] = *p
}
return out, nil
}