package auth import ( "context" "golang.org/x/crypto/bcrypt" "git.sr.ht/~gabrielgio/img/pkg/ext" ) type Controller struct { repository Repository key []byte } func NewController(repository Repository, key []byte) *Controller { return &Controller{ repository: repository, 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) } func (c *Controller) Register(ctx context.Context, username, password []byte) error { hash, err := bcrypt.GenerateFromPassword(password, bcrypt.MinCost) if err != nil { return err } _, err = c.repository.Create(ctx, &CreateUser{ Username: string(username), Password: hash, }) return err }