lens @ d5261d7f121985f13f9d19e9efd5c2ae3d4b5609

 1package auth
 2
 3import (
 4	"context"
 5
 6	"golang.org/x/crypto/bcrypt"
 7
 8	"git.sr.ht/~gabrielgio/img/pkg/ext"
 9)
10
11type Controller struct {
12	repository Repository
13	key        []byte
14}
15
16func NewController(repository Repository, key []byte) *Controller {
17	return &Controller{
18		repository: repository,
19		key:        key,
20	}
21}
22
23func (c *Controller) Login(ctx context.Context, username, password []byte) ([]byte, error) {
24	id, err := c.repository.GetIDByUsername(ctx, string(username))
25	if err != nil {
26		return nil, err
27	}
28
29	hashedPassword, err := c.repository.GetPassword(ctx, id)
30	if err != nil {
31		return nil, err
32	}
33
34	if err := bcrypt.CompareHashAndPassword(hashedPassword, password); err != nil {
35		return nil, err
36	}
37
38	token := &ext.Token{
39		UserID:   id,
40		Username: string(username),
41	}
42	return ext.WriteToken(token, c.key)
43}
44
45func (c *Controller) Register(ctx context.Context, username, password []byte) error {
46	hash, err := bcrypt.GenerateFromPassword(password, bcrypt.MinCost)
47	if err != nil {
48		return err
49	}
50
51	_, err = c.repository.Create(ctx, &CreateUser{
52		Username: string(username),
53		Password: hash,
54	})
55
56	return err
57}