~sircmpwn/meta.sr.ht

ref: 0.56.17 meta.sr.ht/api/graph/model/auditlog.go -rw-r--r-- 2.1 KiB
b1deacf0Nicolas Schodet Fix field name when validating the PGP key in RegisterAccount 11 months ago
                                                                                
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
102
103
package model

import (
	"context"
	"database/sql"
	"strconv"
	"time"

	sq "github.com/Masterminds/squirrel"

	"git.sr.ht/~sircmpwn/core-go/database"
	"git.sr.ht/~sircmpwn/core-go/model"
)

type AuditLogEntry struct {
	ID        int       `json:"id"`
	Created   time.Time `json:"created"`
	IPAddress string    `json:"ipAddress"`
	EventType string    `json:"eventType"`
	Details   *string   `json:"details"`

	UserID int

	alias  string
	fields *database.ModelFields
}

func (e *AuditLogEntry) As(alias string) *AuditLogEntry {
	e.alias = alias
	return e
}

func (e *AuditLogEntry) Alias() string {
	return e.alias
}

func (e *AuditLogEntry) Table() string {
	return "audit_log_entry"
}

func (e *AuditLogEntry) Fields() *database.ModelFields {
	if e.fields != nil {
		return e.fields
	}
	e.fields = &database.ModelFields{
		Fields: []*database.FieldMap{
			{ "id", "id", &e.ID },
			{ "created", "created", &e.Created },
			{ "ip_address", "ipAddress", &e.IPAddress },
			{ "event_type", "eventType", &e.EventType },
			{ "details", "details", &e.Details },

			// Always fetch:
			{ "id", "", &e.ID },
			{ "user_id", "", &e.UserID },
		},
	}
	return e.fields
}

func (e *AuditLogEntry) QueryWithCursor(ctx context.Context,
	runner sq.BaseRunner, q sq.SelectBuilder,
	cur *model.Cursor) ([]*AuditLogEntry, *model.Cursor) {
	var (
		err  error
		rows *sql.Rows
	)

	if cur.Next != "" {
		next, _ := strconv.ParseInt(cur.Next, 10, 64)
		q = q.Where(database.WithAlias(e.alias, "id")+"<= ?", next)
	}
	q = q.
		OrderBy(database.WithAlias(e.alias, "id") + " DESC").
		Limit(uint64(cur.Count + 1))

	if rows, err = q.RunWith(runner).QueryContext(ctx); err != nil {
		panic(err)
	}
	defer rows.Close()

	var ents []*AuditLogEntry
	for rows.Next() {
		var ent AuditLogEntry
		if err := rows.Scan(database.Scan(ctx, &ent)...); err != nil {
			panic(err)
		}
		ents = append(ents, &ent)
	}

	if len(ents) > cur.Count {
		cur = &model.Cursor{
			Count:  cur.Count,
			Next:   strconv.Itoa(ents[len(ents)-1].ID),
			Search: cur.Search,
		}
		ents = ents[:cur.Count]
	} else {
		cur = nil
	}

	return ents, cur
}