aboutsummaryrefslogtreecommitdiff
path: root/pkg/components/auth/controller.go
blob: 2f30fb5d1027286fc809f6a683bc42416ed86db3 (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
73
74
75
76
77
package auth

import (
	"context"

	"golang.org/x/crypto/bcrypt"

	"git.sr.ht/~gabrielgio/img/pkg/components"
	"git.sr.ht/~gabrielgio/img/pkg/components/user"
	"git.sr.ht/~gabrielgio/img/pkg/ext"
)

type Controller struct {
	repository     Repository
	userRepository user.Repository
	key            []byte
}

func NewController(
	repository Repository,
	userRepository user.Repository,
	key []byte,
) *Controller {
	return &Controller{
		repository:     repository,
		userRepository: userRepository,
		key:            key,
	}
}

func (c *Controller) Login(ctx context.Context, username, password []byte) ([]byte, error) {
	id, err := c.repository.GetIDByUsername(ctx, string(username))
	if err != nil {
		return nil, err
	}

	hashedPassword, err := c.repository.GetPassword(ctx, id)
	if err != nil {
		return nil, err
	}

	if err := bcrypt.CompareHashAndPassword(hashedPassword, password); err != nil {
		return nil, err
	}

	token := &ext.Token{
		UserID:   id,
		Username: string(username),
	}
	return ext.WriteToken(token, c.key)
}

// InitialRegister register a initial user, it will validate if there is another
// user stored already. If so an error `InvlidaInput` will be returned
func (c *Controller) InitialRegister(ctx context.Context, username, password []byte, path []byte) error {
	exist, err := c.userRepository.Any(ctx)
	if err != nil {
		return err
	}

	if exist {
		return components.InvlidaInput
	}

	hash, err := bcrypt.GenerateFromPassword(password, bcrypt.MinCost)
	if err != nil {
		return err
	}

	err = c.userRepository.Create(ctx, &user.CreateUser{
		Username: string(username),
		Password: hash,
		Path:     string(path),
	})

	return err
}