miaopanel
1package store
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "time"
8)
9
10// Audit appends one audit record.
11func (s *Store) Audit(ctx context.Context, e AuditEntry) error {
12 _, err := s.db.ExecContext(ctx,
13 `INSERT INTO audit_logs(user_id, username, ip, ua, module, action, target,
14 params, result, cost_ms, created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)`,
15 e.UserID, e.Username, e.IP, e.UA, e.Module, e.Action, e.Target,
16 e.Params, e.Result, e.CostMS, time.Now().Unix())
17 return err
18}
19
20// RecentAudit returns the newest audit records.
21func (s *Store) RecentAudit(ctx context.Context, limit int) ([]map[string]any, error) {
22 if limit <= 0 || limit > 500 {
23 limit = 100
24 }
25 rows, err := s.db.QueryContext(ctx,
26 `SELECT id, username, ip, module, action, target, result, cost_ms, created_at
27 FROM audit_logs ORDER BY id DESC LIMIT ?`, limit)
28 if err != nil {
29 return nil, err
30 }
31 defer rows.Close()
32 out := make([]map[string]any, 0, limit)
33 for rows.Next() {
34 var id, cost, at int64
35 var user, ip, module, action, target, result string
36 if err := rows.Scan(&id, &user, &ip, &module, &action, &target, &result, &cost, &at); err != nil {
37 return nil, err
38 }
39 out = append(out, map[string]any{
40 "id": id, "username": user, "ip": ip, "module": module,
41 "action": action, "target": target, "result": result,
42 "cost_ms": cost, "created_at": at,
43 })
44 }
45 return out, rows.Err()
46}
47
48// Setting reads one key, returning def when unset.
49func (s *Store) Setting(ctx context.Context, key, def string) (string, error) {
50 var v string
51 err := s.db.QueryRowContext(ctx, `SELECT value FROM settings WHERE key = ?`, key).Scan(&v)
52 if errors.Is(err, sql.ErrNoRows) {
53 return def, nil
54 }
55 return v, err
56}
57
58// SetSetting writes one key.
59func (s *Store) SetSetting(ctx context.Context, key, value string) error {
60 _, err := s.db.ExecContext(ctx,
61 `INSERT INTO settings(key, value) VALUES(?,?)
62 ON CONFLICT(key) DO UPDATE SET value = excluded.value`, key, value)
63 return err
64}