~sircmpwn/meta.sr.ht

ref: 0.56.17 meta.sr.ht/api/graph/model/sshkey.go -rw-r--r-- 2.0 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
104
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 SSHKey struct {
	ID          int        `json:"id"`
	Created     time.Time  `json:"created"`
	LastUsed    *time.Time `json:"lastUsed"`
	Key         string     `json:"key"`
	Fingerprint string     `json:"fingerprint"`
	Comment     *string    `json:"comment"`

	UserID int

	alias  string
	fields *database.ModelFields
}

func (k *SSHKey) As(alias string) *SSHKey {
	k.alias = alias
	return k
}

func (k *SSHKey) Alias() string {
	return k.alias
}

func (k *SSHKey) Table() string {
	return "sshkey"
}

func (k *SSHKey) Fields() *database.ModelFields {
	if k.fields != nil {
		return k.fields
	}
	k.fields = &database.ModelFields{
		Fields: []*database.FieldMap{
			{ "id", "id", &k.ID },
			{ "created", "created", &k.Created },
			{ "last_used", "lastUsed", &k.LastUsed },
			{ "key", "key", &k.Key },
			{ "fingerprint", "fingerprint", &k.Fingerprint },
			{ "comment", "comment", &k.Comment },

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

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

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

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

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

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

	return keys, cur
}