internal/control/audit.go

c7cebb36f27f7d136074c5392f87231786a06d56
gitbay/internal/control/audit.go history · blame · raw

45 lines · 1039 bytes

 1package control
 2
 3import (
 4	"fmt"
 5	"io"
 6	"strconv"
 7
 8	"gitbay.org/gitbay/internal/protocol"
 9)
10
11func init() {
12	register(Command{Path: []string{"audit"},
13		Summary: "instance audit log (admins)",
14		Usage:   "audit [--limit <n>]", ReadOnly: true, SSHOnly: true, Run: runAudit})
15}
16
17func runAudit(c *Ctx, args []string) int {
18	if !c.User.IsAdmin {
19		return c.fail(protocol.ExitDenied, "the audit log is for instance admins")
20	}
21	limit := 100
22	for i := 0; i < len(args); i++ {
23		if args[i] == "--limit" && i+1 < len(args) {
24			if n, err := strconv.Atoi(args[i+1]); err == nil && n > 0 && n <= 10000 {
25				limit = n
26			}
27			i++
28		} else {
29			return c.fail(protocol.ExitUsage, "usage: audit [--limit <n>]")
30		}
31	}
32	entries, err := c.Store.AuditEntries(limit)
33	if err != nil {
34		return c.fail(protocol.ExitFailure, "%v", err)
35	}
36	return c.emit(entries, func(w io.Writer) {
37		for _, e := range entries {
38			actor := e.Actor
39			if actor == "" {
40				actor = "-"
41			}
42			fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", e.CreatedAt, actor, e.Action, e.Data)
43		}
44	})
45}