framework/pkg/service/user/login.go

32 lines
787 B
Go
Raw Permalink Normal View History

2024-10-12 02:52:22 +03:00
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
}