/
account.go
390 lines (323 loc) · 8.97 KB
/
account.go
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package eventline
import (
"context"
"crypto/sha256"
"crypto/subtle"
"errors"
"fmt"
"time"
"github.com/exograd/eventline/pkg/cryptoutils"
"github.com/exograd/eventline/pkg/utils"
"github.com/galdor/go-ejson"
"github.com/galdor/go-service/pkg/pg"
"github.com/jackc/pgx/v5"
"golang.org/x/crypto/pbkdf2"
)
var AccountSorts Sorts = Sorts{
Sorts: map[string]string{
"id": "id",
"username": "username",
},
Default: "username",
}
type AccountRole string
const (
AccountRoleUser AccountRole = "user"
AccountRoleAdmin AccountRole = "admin"
)
var AccountRoleValues = []AccountRole{
AccountRoleUser,
AccountRoleAdmin,
}
const (
MinUsernameLength = 3
MaxUsernameLength = 100
MinPasswordLength = 8
MaxPasswordLength = 100
SaltSize = 32 // bytes
// Current OWASP recommendations are 310'000+
// (https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2).
//
// Note that changing it requires re-hashing all password hashes in the
// database. Do not change it.
NbPBKDF2Iterations = 350_000
)
type UnknownAccountError struct {
Id Id
}
func (err UnknownAccountError) Error() string {
return fmt.Sprintf("unknown account %q", err.Id)
}
type UnknownUsernameError struct {
Username string
}
func (err UnknownUsernameError) Error() string {
return fmt.Sprintf("unknown username %q", err.Username)
}
type NewAccount struct {
Username string `json:"username"`
Password string `json:"password"`
PasswordConfirmation string `json:"password_confirmation"`
Role AccountRole `json:"role"`
}
type AccountUpdate struct {
Username string `json:"username"`
Role AccountRole `json:"role"`
}
type AccountPasswordUpdate struct {
Password string `json:"password"`
PasswordConfirmation string `json:"password_confirmation"`
}
type AccountSelfUpdate struct {
Settings *AccountSettings `json:"settings"`
}
type Account struct {
Id Id `json:"id"`
CreationTime time.Time `json:"creation_time"`
Username string `json:"username"`
Salt []byte `json:"-"`
PasswordHash []byte `json:"-"`
Role AccountRole `json:"role"`
LastLoginTime *time.Time `json:"last_login_time,omitempty"`
LastProjectId *Id `json:"last_project_id,omitempty"`
Settings *AccountSettings `json:"settings"`
}
type Accounts []*Account
type AccountSettings struct {
DateFormat DateFormat `json:"date_format,omitempty"`
PageSize int `json:"page_size,omitempty"`
}
func DefaultAccountSettings() *AccountSettings {
return &AccountSettings{
DateFormat: "relative",
PageSize: 20,
}
}
func (as *AccountSettings) ValidateJSON(v *ejson.Validator) {
v.CheckStringValue("date_format", as.DateFormat, DateFormatValues)
v.CheckIntMinMax("page_size", as.PageSize, MinPageSize, MaxPageSize)
}
func (na *NewAccount) ValidateJSON(v *ejson.Validator) {
v.CheckStringLengthMinMax("username", na.Username,
MinUsernameLength, MaxUsernameLength)
v.CheckStringLengthMinMax("password", na.Password,
MinPasswordLength, MaxPasswordLength)
v.Check("password_confirmation", na.PasswordConfirmation == na.Password,
"password_mismatch", "password confirmation and password do not match")
v.CheckStringValue("role", na.Role, AccountRoleValues)
}
func (au *AccountUpdate) ValidateJSON(v *ejson.Validator) {
v.CheckStringLengthMinMax("username", au.Username,
MinUsernameLength, MaxUsernameLength)
v.CheckStringValue("role", au.Role, AccountRoleValues)
}
func (au *AccountPasswordUpdate) ValidateJSON(v *ejson.Validator) {
v.CheckStringLengthMinMax("password", au.Password,
MinPasswordLength, MaxPasswordLength)
v.Check("password_confirmation", au.PasswordConfirmation == au.Password,
"password_mismatch", "password confirmation and password do not match")
}
func (au *AccountSelfUpdate) ValidateJSON(v *ejson.Validator) {
v.CheckOptionalObject("settings", au.Settings)
}
func (a *Account) CheckPassword(password string) bool {
attempt := HashPassword(password, a.Salt)
return subtle.ConstantTimeCompare(attempt, a.PasswordHash) == 1
}
func GenerateSalt() []byte {
return cryptoutils.RandomBytes(SaltSize)
}
func HashPassword(password string, salt []byte) []byte {
return pbkdf2.Key([]byte(password), salt, NbPBKDF2Iterations, 32,
sha256.New)
}
func (a *Account) SortKey(sort string) (key string) {
switch sort {
case "id":
key = a.Id.String()
case "username":
key = a.Username
default:
utils.Panicf("unknown account sort %q", sort)
}
return
}
func UsernameExists(conn pg.Conn, username string) (bool, error) {
ctx := context.Background()
query := `
SELECT COUNT(*)
FROM accounts
WHERE username = $1
`
var count int64
err := conn.QueryRow(ctx, query, username).Scan(&count)
if err != nil {
return false, err
}
return count > 0, nil
}
func (as *Accounts) LoadAll(conn pg.Conn) error {
query := `
SELECT id, creation_time, username, salt,
password_hash, role, last_login_time, last_project_id,
settings
FROM accounts
ORDER BY username
`
return pg.QueryObjects(conn, as, query)
}
func (a *Account) Load(conn pg.Conn, id Id) error {
query := `
SELECT id, creation_time, username, salt,
password_hash, role, last_login_time, last_project_id,
settings
FROM accounts
WHERE id = $1
`
err := pg.QueryObject(conn, a, query, id)
if errors.Is(err, pgx.ErrNoRows) {
return &UnknownAccountError{Id: id}
}
return err
}
func (a *Account) LoadForUpdate(conn pg.Conn, id Id) error {
query := `
SELECT id, creation_time, username, salt,
password_hash, role, last_login_time, last_project_id,
settings
FROM accounts
WHERE id = $1
FOR UPDATE
`
err := pg.QueryObject(conn, a, query, id)
if errors.Is(err, pgx.ErrNoRows) {
return &UnknownAccountError{Id: id}
}
return err
}
func (a *Account) LoadByUsernameForUpdate(conn pg.Conn, username string) error {
query := `
SELECT id, creation_time, username, salt,
password_hash, role, last_login_time, last_project_id,
settings
FROM accounts
WHERE username = $1
FOR UPDATE;
`
err := pg.QueryObject(conn, a, query, username)
if errors.Is(err, pgx.ErrNoRows) {
return &UnknownUsernameError{Username: username}
}
return err
}
func LoadAccountPage(conn pg.Conn, cursor *Cursor) (*Page, error) {
query := fmt.Sprintf(`
SELECT id, creation_time, username, salt,
password_hash, role, last_login_time, last_project_id,
settings
FROM accounts
WHERE %s
`, cursor.SQLConditionOrderLimit(AccountSorts))
var accounts Accounts
if err := pg.QueryObjects(conn, &accounts, query); err != nil {
return nil, err
}
return accounts.Page(cursor), nil
}
func (a *Account) Insert(conn pg.Conn) error {
query := `
INSERT INTO accounts
(id, creation_time, username, salt, password_hash,
role, last_login_time, last_project_id, settings)
VALUES
($1, $2, $3, $4, $5,
$6, $7, $8, $9);
`
return pg.Exec(conn, query,
a.Id, a.CreationTime, a.Username, a.Salt, a.PasswordHash,
a.Role, a.LastLoginTime, a.LastProjectId, a.Settings)
}
func (a *Account) UpdateForLogin(conn pg.Conn) error {
query := `
UPDATE accounts SET
last_login_time = $2,
last_project_id = $3
WHERE id = $1;
`
return pg.Exec(conn, query, a.Id, a.LastLoginTime, a.LastProjectId)
}
func (a *Account) SelfUpdate(conn pg.Conn) error {
query := `
UPDATE accounts SET
settings = $2,
salt = $3,
password_hash = $4
WHERE id = $1;
`
return pg.Exec(conn, query, a.Id, a.Settings, a.Salt, a.PasswordHash)
}
func UpdateAccountLastProjectId(conn pg.Conn, accountId Id, projectId *Id) error {
query := `
UPDATE accounts SET
last_project_id = $2
WHERE id = $1;
`
return pg.Exec(conn, query, accountId, projectId)
}
func UpdateAccountsForProjectDeletion(conn pg.Conn, projectId Id) error {
query := `
UPDATE accounts SET
last_project_id = NULL
WHERE last_project_id = $1
`
return pg.Exec(conn, query, projectId)
}
func (a *Account) Update(conn pg.Conn) error {
query := `
UPDATE accounts SET
username = $2,
salt = $3,
password_hash = $4,
role = $5
WHERE id = $1
`
return pg.Exec(conn, query,
a.Id, a.Username, a.Salt, a.PasswordHash, a.Role)
}
func DeleteAccount(conn pg.Conn, accountId Id) error {
query := `
DELETE FROM accounts
WHERE id = $1;
`
return pg.Exec(conn, query, accountId)
}
func (as Accounts) Page(cursor *Cursor) *Page {
elements := make([]PageElement, len(as))
for i, a := range as {
elements[i] = a
}
return NewPage(cursor, elements, AccountSorts)
}
func (a *Account) FromRow(row pgx.Row) error {
var lastProjectId Id
var settings AccountSettings
err := row.Scan(&a.Id, &a.CreationTime, &a.Username, &a.Salt,
&a.PasswordHash, &a.Role, &a.LastLoginTime, &lastProjectId,
&settings)
if err != nil {
return err
}
if !lastProjectId.IsZero() {
a.LastProjectId = &lastProjectId
}
a.Settings = &settings
return nil
}
func (as *Accounts) AddFromRow(row pgx.Row) error {
var a Account
if err := a.FromRow(row); err != nil {
return err
}
*as = append(*as, &a)
return nil
}