Вход в систему зарегистрированных пользователей после активации учетной записи без fosuserbundle - PullRequest
2 голосов
/ 03 июня 2019

Я пытаюсь зарегистрироваться (с подтверждением по электронной почте) и войти в систему моих пользователей без использования FOSUserBundle.

Я взял идею из этого видео: https://www.grafikart.fr/tutoriels/confirmation-compte-824

что я сделал на данный момент:

1-а регистрация пользователя

2 - электронное письмо отправлено пользователю для активации

3 - если пользователь нажал на ссылку, активировать подтверждение_отделение = ноль и enabled = true

НО

Я не знаю, как проверить в функции входа в систему и добавить условие подтверждение_login = null, чтобы позволить только активированной учетной записи войти в систему.

this security.yml

encoders:
        AppBundle\Entity\User: bcrypt

    providers:
        db_provider:
            entity:
                class: AppBundle\Entity\User
                property: username

    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            anonymous: ~
            provider: db_provider
            form_login:
                login_path: login
                check_path: login
            logout:
                path:   /logout
                target: /


    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }

это моя регистрация Контроллер:

/**
 * @Route("/register")
 * @param Request $request
 * @Template()
 * @return \Symfony\Component\HttpFoundation\Response
 */
 public function registerAction(Request $request)
 {
    $user = new User();
    $form = $this->createForm(UserType::class, $user);
    $form->handleRequest($request);
    $em = $this->getDoctrine()->getManager();
    if ($form->isSubmitted() && $form->isValid()) {
        $password = $this->get('security.password_encoder')
            ->encodePassword($user, $user->getPlainPassword());
        $user->setPassword($password);


        $em->persist($user);
        $em->flush();

        $confirmationToken = $user->getConfirmationToken();
        $username = $user->getUsername();
        $userId = $user->getId();

        $subject = 'Account activation';
        $email = $user->getEmail();
      /*  $renderedTemplate = $this->render('AppBundle:Register:registrationConfirmed.html.twig', array(
            'username' => $username,
            'confirmationToken' => $confirmationToken
        ));*/
        $message = (new \Swift_Message('Hello Email'))
            ->setSubject($subject)
            ->setFrom($this->container->getParameter('mailer_user'))
            ->setTo($email)
            ->setBody(
            $this->renderView(
                'AppBundle:Register:registrationConfirmed.html.twig', array('id' => $userId,'username' => $username,'confirmationToken' => $confirmationToken)), 'text/html');

        $this->get('mailer')->send($message);


        $this->addFlash('success', 'Genus created!');
       return $this->redirectToRoute('login');
    }

    return $this->render('AppBundle:Register:register.html.twig', array('form' => $form->createView()));
}


 /**
  * @Route("/confirm/{id}/{confirmationToken}", name="confirmation_path")
  */
public function confirmAction(Request $request, $id,$confirmationToken)
 {
    $em = $this->getDoctrine()->getManager();
    $repository = $em->getRepository('AppBundle:User');
    //$confirmationToken = $user->getConfirmationToken();

    $user = $repository->findUserByIdAndConfirmationToken($id,$confirmationToken);

    if (!$user)
    {
        throw $this->createNotFoundException('We couldn\'t find an account for that confirmation token');
    }
      else
      {

     $user= $repository->updateConfirmationTokenAfterValidation($id,$confirmationToken);

    // $user->setEnabled(true);
    // $user->setConfirmationToken(null);
    //$em->persist($user);
    // $em->flush();
      }
    return $this->redirectToRoute('login');
}

и это ссылка в письме для активации учетной записи:

<a href="{{ url('confirmation_path', {'id': id, 'confirmationToken': confirmationToken }  ) }}">Activate</a>

и для входа в систему я использую loginAction, так как я могу проверить здесь, если verifyToken = null, чтобы позволить только зарегистрированным пользователям войти

/**
 * @Route("/login",name="login")
 */


 public function loginAction()
    {
        $helper = $this->get('security.authentication_utils');

        return $this->render('AppBundle:Login:login.html.twig', [
            // last username entered by the user (if any)
            'last_username' => $helper->getLastUsername(),
            // last authentication error (if any)
            'error' => $helper->getLastAuthenticationError(),
        ]);
    }

my login.html.twig

<form action="{{ path('login') }}" method="post">

            <div class="form-group">
                <label for="username">{{ 'label.username'|trans }}</label>
                <input type="text" id="username" name="_username"  class="form-control"/>
            </div>
            <div class="form-group">
                <label for="password">{{ 'label.password'|trans }}</label>
                <input type="password" id="password" name="_password" class="form-control" />
            </div>
            <button type="submit" class="btn btn-primary">
                <i class="fa fa-sign-in" aria-hidden="true"></i> {{ 'action.sign_in'|trans }}
            </button>
        </form>

Обновление

Я реализовал Userchecker, и он работает (я не знаю, лучше это или нет)

 public function checkPostAuth(UserInterface $user)
    {
        if (!$user instanceof AppUser) {
            return;
        }

        if (!$user->getIsActive()) {
            throw new \Exception("ce membre n'est pas actif");
        }

    }
...