lens @ 249ee195ce52ee4a4defeb67a33ef353919d3a11

 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}