启用FOS用户捆绑包电子邮件注册

时间:2018-08-25 16:46:33

标签: php symfony email fosuserbundle registration

我购买了第三方php脚本,并尝试为其启用电子邮件确认。它是别人做的。我已经与他们联系并没有得到任何答复,我只是在寻求建议,而不是在寻找明确的答案,但我发现package.json要求中包含FOS用户捆绑包,脚本中还包含“ RegistrationController.php”。用户注册时,在确保输入字段是正确的数据类型之后,它将直接转到“注册成功”页面。

在config yml中,我启用了注册确认功能,并在parameters.yml中,我使用gmail作为主机,然后执行了composer install,但是在输入电子邮件之后,它仍然直接指向注册成功页面,而没有输入。我希望,如果我在php.php中的config.yml中启用了注册,这将被识别,但也许并非如此,还有更多的代码需要做,听起来正确吗?

RegistrationController.php     

/*
 * This file is part of the FOSUserBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FOS\UserBundle\Controller;

use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Form\Factory\FactoryInterface;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * Controller managing the registration.
 *
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 * @author Christophe Coevoet <stof@notk.org>
 */
class RegistrationController extends Controller
{
    private $eventDispatcher;
    private $formFactory;
    private $userManager;
    private $tokenStorage;

    public function __construct(EventDispatcherInterface $eventDispatcher, FactoryInterface $formFactory, UserManagerInterface $userManager, TokenStorageInterface $tokenStorage)
    {
        $this->eventDispatcher = $eventDispatcher;
        $this->formFactory = $formFactory;
        $this->userManager = $userManager;
        $this->tokenStorage = $tokenStorage;
    }

    /**
     * @param Request $request
     *
     * @return Response
     */
    public function registerAction(Request $request)
    {
        $user = $this->userManager->createUser();
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $form = $this->formFactory->createForm();
        $form->setData($user);

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $event = new FormEvent($form, $request);
                $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

                $this->userManager->updateUser($user);

                if (null === $response = $event->getResponse()) {
                    $url = $this->generateUrl('fos_user_registration_confirmed');
                    $response = new RedirectResponse($url);
                }

                $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

                return $response;
            }

            $event = new FormEvent($form, $request);
            $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);

            if (null !== $response = $event->getResponse()) {
                return $response;
            }
        }

        return $this->render('@FOSUser/Registration/register.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    /**
     * Tell the user to check their email provider.
     */
    public function checkEmailAction(Request $request)
    {
        $email = $request->getSession()->get('fos_user_send_confirmation_email/email');

        if (empty($email)) {
            return new RedirectResponse($this->generateUrl('fos_user_registration_register'));
        }

        $request->getSession()->remove('fos_user_send_confirmation_email/email');
        $user = $this->userManager->findUserByEmail($email);

        if (null === $user) {
            return new RedirectResponse($this->container->get('router')->generate('fos_user_security_login'));
        }

        return $this->render('@FOSUser/Registration/check_email.html.twig', array(
            'user' => $user,
        ));
    }

    /**
     * Receive the confirmation token from user email provider, login the user.
     *
     * @param Request $request
     * @param string  $token
     *
     * @return Response
     */
    public function confirmAction(Request $request, $token)
    {
        $userManager = $this->userManager;

        $user = $userManager->findUserByConfirmationToken($token);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
        }

        $user->setConfirmationToken(null);
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('fos_user_registration_confirmed');
            $response = new RedirectResponse($url);
        }

        $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    /**
     * Tell the user his account is now confirmed.
     */
    public function confirmedAction(Request $request)
    {
        $user = $this->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this->render('@FOSUser/Registration/confirmed.html.twig', array(
            'user' => $user,
            'targetUrl' => $this->getTargetUrlFromSession($request->getSession()),
        ));
    }

    /**
     * @return string|null
     */
    private function getTargetUrlFromSession(SessionInterface $session)
    {
        $key = sprintf('_security.%s.target_path', $this->tokenStorage->getToken()->getProviderKey());

        if ($session->has($key)) {
            return $session->get($key);
        }

        return null;
    }
}

我发现,直接进入成功页面的问题是因为它处于生产模式,切换到开发人员模式并启用确认后,它会定向到登录页面,不幸的是,它没有发送电子邮件,当然,登录页面不是所需的重定向,但我在日志中发现了一些我认为可能与之相关的错误

[2018-08-27 09:29:51] doctrine.DEBUG: "START TRANSACTION" [] []
[2018-08-27 09:29:51] doctrine.DEBUG: INSERT INTO directory_platform_users (username, username_canonical, email, email_canonical, enabled, salt, password, last_login, confirmation_token, password_requested_at, roles, is_verified, created, modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) {"1":"dan4","2":"dan4","3":"dan4@gmail.com","4":"dan4@gmail.com","5":false,"6":null,"7":"$2y$13$4.XnFG.PC3Zholme.w4 [...]","8":null,"9":"2R1Z3Qmek2j--loZNXXWcb8TWU [...]","10":null,"11":[],"12":null,"13":"2018-08-27 09:29:51","14":"2018-08-27 09:29:51"} []
[2018-08-27 09:29:51] doctrine.DEBUG: "COMMIT" [] []
[2018-08-27 09:29:51] translation.WARNING: Translation not found. {"id":"Hi,\n\nyour user account has been succesfully created. Your account name is %username% and e-mail account is %email%.","domain":"messages","locale":"en"} []
[2018-08-27 09:29:52] app.ERROR: Exception occurred while flushing email queue: Expected response code 250 but got code "530", with message "530 5.7.0 Must issue a STARTTLS command first. z13-v6sm5400096ioj.51 - gsmtp " [] []
[2018-08-27 09:29:52] request.INFO: Matched route "listing_my". {"route":"listing_my","route_parameters":{"_controller":"DirectoryPlatform\\FrontBundle\\Controller\\ListingController::myAction","_route":"listing_my"},"request_uri":"http://127.0.0.1:8000/account/listings","method":"GET"} []
[2018-08-27 09:29:52] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
[2018-08-27 09:29:52] security.DEBUG: Access denied, the user is not fully authenticated; redirecting to authentication entry point. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException(code: 403): Access Denied. at /home/dan/directory-platform-1.0.8/directory-platform/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/AccessListener.php:68)"} []
[2018-08-27 09:29:52] security.DEBUG: Calling Authentication entry point. [] []
[2018-08-27 09:29:52] request.INFO: Matched route "fos_user_security_login". {"route":"fos_user_security_login","route_parameters":{"_controller":"fos_user.security.controller:loginAction","_route":"fos_user_security_login"},"request_uri":"http://127.0.0.1:8000/login","method":"GET"} []
[2018-08-27 09:29:52] security.INFO: Populated the TokenStorage with an anonymous Token. [] []

它还将用户添加到我在mysql中检查过的数据库中。我不确定这是否是所需的行为。我不认为电子邮件确认是该php脚本的预期行为,否则,将有一个确认页面重定向,而不是重定向到登录页面。

编辑:我正在localhost上工作,所以我使用了gmail并将其设置为

FOS用户

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: DirectoryPlatform\AppBundle\Entity\User
    from_email:
        address: me@gmail.com
        sender_name: name
    registration:
      confirmation:
        enabled: true

parameters.yml

mailer_transport: gmail
mailer_host: ~
mailer_user: me@gmail.com
mailer_password: password

这似乎可行,仍然必须找到一种方法来警告用户已发送电子邮件,但是很好。

1 个答案:

答案 0 :(得分:0)

这是fos_user的参数。我将其设置为

config.yml

registration:
  confirmation:
    enabled: true