Skip to content

EventSubscriber does not work for graphql #3081

Description

@BernardA

For user registration, I have an EventSubscriber to encode password, generate confirmation token and finally to send email confirmation to the user.

This works fine in REST but not at all in graphql.

Searching in this repository I found a couple of issues related to this, including this one, but it is not clear to me the current status.

It seems to have been merged but the issue is present on my installation with
"api-platform/api-pack": "^1.2",.

This is the code in case of need:

 <?php

 namespace App\EventSubscriber;

use App\Entity\User;
use App\Email\Mailer;
use App\Security\TokenGenerator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\HttpFoundation\Request;

class UserRegisterSubscriber implements EventSubscriberInterface
{
/**
 * @var UserPasswordEncoderInterface
 */
private $passwordEncoder;
/**
 * @var TokenGenerator
 */
private $tokenGenerator;
/**
 * @var Mailer
 */
private $mailer;

public function __construct(
    UserPasswordEncoderInterface $passwordEncoder,
    TokenGenerator $tokenGenerator,
    Mailer $mailer
)
{
    $this->passwordEncoder = $passwordEncoder;
    $this->tokenGenerator = $tokenGenerator;
    $this->mailer = $mailer;
}

public static function getSubscribedEvents()
{
    return [
        KernelEvents::VIEW => ['userRegistered', EventPriorities::PRE_WRITE],
    ];
}

public function userRegistered(GetResponseForControllerResultEvent $event)
{
    $user = $event->getControllerResult();
    $method = $event->getRequest()->getMethod();
    if (!$user instanceof User ||
        !in_array($method, [Request::METHOD_POST])) {
        return;
    }
    $user->setPassword(
        $this->passwordEncoder->encodePassword($user, $user->getPassword())
    );

    // Create confirmation token
    $user->setConfirmationToken(
        $this->tokenGenerator->getRandomSecureToken()
    );

    // Send e-mail here...
    $this->mailer->sendConfirmationEmail($user);
}
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions