aboutsummaryrefslogtreecommitdiff
path: root/src/user/hooks.go
blob: 0ab5ab0443b9e35c5bc52441eca211e446f14877 (plain)
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
package user

import (
	"context"
	"crypto/rand"
	"encoding/base64"
	"fmt"

	validation "github.com/go-ozzo/ozzo-validation/v4"
	"github.com/go-ozzo/ozzo-validation/v4/is"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"gitlab.com/alexkavon/newsstand/src/models"
	"golang.org/x/crypto/argon2"
)

func init() {
	models.AddUserHook(boil.BeforeInsertHook, validate)
	// should always be last
	models.AddUserHook(boil.BeforeInsertHook, hashSecret)
}

func validate(ctx context.Context, exec boil.ContextExecutor, u *models.User) error {
	// validate user
	err := validation.ValidateStruct(u,
		validation.Field(&u.Username, validation.Required, validation.Length(3, 50)),
		validation.Field(&u.Secret, validation.Required, validation.Length(8, 128)),
		validation.Field(&u.Email, validation.Required, is.Email),
	)
	if err != nil {
		return err
	}

	return nil
}

func hashSecret(ctx context.Context, exec boil.ContextExecutor, u *models.User) error {
	hashconf := &struct {
		memory      uint32
		iterations  uint32
		parallelism uint8
		keyLength   uint32
		saltLength  uint32
	}{64 * 1024, 3, 2, 12, 16}
	salt := make([]byte, hashconf.saltLength)
	_, err := rand.Read(salt)
	if err != nil {
		return err
	}

	hash := argon2.IDKey(
		[]byte(u.Secret),
		salt,
		hashconf.iterations,
		hashconf.memory,
		hashconf.parallelism,
		hashconf.keyLength,
	)
	b64Salt := base64.RawStdEncoding.EncodeToString(salt)
	b64Hash := base64.RawStdEncoding.EncodeToString(hash)
	encodedHash := fmt.Sprintf(
		"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
		argon2.Version,
		hashconf.memory,
		hashconf.iterations,
		hashconf.parallelism,
		b64Salt,
		b64Hash,
	)

	u.Secret = encodedHash
	return nil
}