framework/pkg/service/user/login.go

31 lines
787 B
Go

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
}