cmd/gitbayd/adminusers.go
91 lines · 2250 bytes
1package main
2
3import (
4 "fmt"
5
6 "github.com/spf13/cobra"
7
8 "gitbay.org/gitbay/internal/config"
9 "gitbay.org/gitbay/internal/store"
10)
11
12func withUser(use, short string, run func(st *store.Store, u store.User) error) *cobra.Command {
13 return &cobra.Command{
14 Use: use + " <username>",
15 Short: short,
16 Args: cobra.ExactArgs(1),
17 RunE: func(cmd *cobra.Command, args []string) error {
18 cfg, err := config.Load(configPath)
19 if err != nil {
20 return err
21 }
22 st, err := openStore(cfg)
23 if err != nil {
24 return err
25 }
26 defer st.Close()
27 u, err := st.UserByUsername(args[0])
28 if err != nil {
29 return fmt.Errorf("no user %q", args[0])
30 }
31 return run(st, u)
32 },
33 }
34}
35
36func adminUserDisableCmd() *cobra.Command {
37 return withUser("disable", "suspend an account: keys and sessions refused until re-enabled",
38 func(st *store.Store, u store.User) error {
39 if err := st.SetUserDisabled(u.ID, true); err != nil {
40 return err
41 }
42 st.Audit(0, "admin user.disabled", map[string]any{"user": u.Username})
43 fmt.Printf("disabled %s: SSH, web sessions, and API tokens are refused; nothing was deleted\n", u.Username)
44 return nil
45 })
46}
47
48func adminUserEnableCmd() *cobra.Command {
49 return withUser("enable", "restore a suspended account",
50 func(st *store.Store, u store.User) error {
51 if err := st.SetUserDisabled(u.ID, false); err != nil {
52 return err
53 }
54 st.Audit(0, "admin user.enabled", map[string]any{"user": u.Username})
55 fmt.Printf("enabled %s\n", u.Username)
56 return nil
57 })
58}
59
60func adminAuditCmd() *cobra.Command {
61 var limit int
62 cmd := &cobra.Command{
63 Use: "audit",
64 Short: "print the security audit log, newest first",
65 RunE: func(cmd *cobra.Command, args []string) error {
66 cfg, err := config.Load(configPath)
67 if err != nil {
68 return err
69 }
70 st, err := openStore(cfg)
71 if err != nil {
72 return err
73 }
74 defer st.Close()
75 entries, err := st.AuditEntries(limit)
76 if err != nil {
77 return err
78 }
79 for _, e := range entries {
80 actor := e.Actor
81 if actor == "" {
82 actor = "-"
83 }
84 fmt.Printf("%s\t%s\t%s\t%s\n", e.CreatedAt, actor, e.Action, e.Data)
85 }
86 return nil
87 },
88 }
89 cmd.Flags().IntVar(&limit, "limit", 100, "entries to print")
90 return cmd
91}