aboutsummaryrefslogblamecommitdiff
path: root/pkg/service/user/login.go
blob: d1f5c65134a49850c9f20da0f2ca9442516d0b32 (plain) (tree)






























                                                                                                        
package user

import (
	"context"
	"errors"

	normalizer "github.com/dimuska139/go-email-normalizer/v3"
	"golang.org/x/crypto/bcrypt"

	"go.neonxp.ru/framework/pkg/model"
	"go.neonxp.ru/framework/pkg/tpl"
)

var ErrInvalidUserOrPassword = errors.New("invalid_user_or_password")

func (s *Service) Login(ctx context.Context, form *tpl.LoginForm) (*model.User, error) {
	n := normalizer.NewNormalizer()
	u := &model.User{
		Email: n.Normalize(form.Email),
	}

	if err := s.db.NewSelect().Model(u).Where("email = ?", u.Email).Scan(ctx, u); err != nil {
		return nil, errors.Join(err, ErrInvalidUserOrPassword)
	}

	if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(form.Password)); err != nil {
		return nil, errors.Join(err, ErrInvalidUserOrPassword)
	}

	return u, nil
}