PHP code example of serendipity_hq / bundle-users

1. Go to this page and download the library: Download serendipity_hq/bundle-users library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

serendipity_hq / bundle-users example snippets




// src/Controller/UserProfileController.php

declare(strict_types = 1);

/*
 * This file is part of Trust Back Me.
 *
 * Copyright (c) Adamo Aerendir Crespi <[email protected]>.
 *
 * This code is to consider private and non disclosable to anyone for whatever reason.
 * Every right on this code is reserved.
 *
 * For the full copyright and license information, please view the LICENSE file that
 * was distributed with this source code.
 */

namespace App\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Security("is_granted('ROLE_USER')", statusCode=403)
 */
final class UserProfileController extends AbstractController
{
    /**
     * @Route("/me/", name="user_profile")
     */
    public function show(): Response
    {
        return $this->render('user/profile.html.twig', [
            'user' => $this->getUser(),
        ]);
    }
}

// src/Controller/
class UserPasswordController extends AbstractController
{
    /**
     * @Route("password-reset", name="user_password_reset_request")
     */
    public function resetRequest(Request $request): Response
    {
        $form = $this->passwordManager->getPasswordHelper()->createFormPasswordResetRequest();

        $form->handleRequest($request);

        // Listen for the event PasswordResetTokenCreatedEvent or for the event PasswordResetTokenCreationFailedEvent
        // If the user was found, then process the request.
        // If the user is not found, do nothing to avoid disclosing if
        // the user exists or not (for security)
        if (
            $form->isSubmitted() &&
            $form->isValid() &&
            $this->passwordManager->handleResetRequest($request, $form)
        ) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('user_password_reset_check_email');
        }

        return $this->render('App/user/password/reset_request.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}

    /**
     * Confirmation page after a user has requested a password reset.
     *
     * @Route("/password-reset/requested", name="user_password_reset_request_received")
     */
    public function resetRequestReceived(Request $request): Response
    {
        // Prevent users from directly accessing this page
        if (!$this->passwordManager->getPasswordResetHelper()->canAccessPageCheckYourEmail($request)) {
            return $this->redirectToRoute('user_password_reset_request');
        }

        return $this->render('App/user/password/check_email.html.twig', [
            'tokenLifetime' => PasswordResetHelper::RESET_TOKEN_LIFETIME,
        ]);
    }

    /**
     * @Route("/password-reset/reset/{token}", name="user_password_reset_reset_password")
     */
    public function reset(Request $request, EncoderFactoryInterface $passwordEncoderFactory, string $token = null): Response
    {
        if ($token) {
            // We store the token in session and remove it from the URL, to avoid the URL being
            // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
            $this->passwordManager->getPasswordResetHelper()->storeTokenInSession($request, $token);

            return $this->redirectToRoute('user_password_reset_reset_password');
        }

        $token = $this->passwordManager->getPasswordResetHelper()->getTokenFromSession($request);
        if (null === $token) {
            throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
        }

        try {
            /**
             * findUserByPublicToken also validates the token and throws exceptions on failed validation.
             * @var HasPlainPasswordInterface $user
             */
            $user = $this->passwordManager->findUserByPublicToken($token);
        } catch (PasswordResetException $e) {
            $this->addFlash('user_password_reset_error', sprintf(
                'There was a problem validating your reset request - %s',
                $e->getMessage()
            ));

            return $this->redirectToRoute('user_password_reset_request');
        }

        $form = $this->passwordManager->getPasswordHelper()->createFormPasswordReset();

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $this->passwordManager->handleReset($token, $user, $form, $request);
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('auth_login');
        }

        return $this->render('App/user/password/reset_password.html.twig', [
            'form' => $form->createView(),
        ]);
    }

// src/Entity/PasswordResetToken.php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use SerendipityHQ\Bundle\UsersBundle\Model\Property\PasswordResetTokenInterface;
use SerendipityHQ\Bundle\UsersBundle\Model\Property\PasswordResetTokenTrait;
use SerendipityHQ\Bundle\UsersBundle\Repository\PasswordResetTokenRepository;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass=PasswordResetTokenRepository::class)
 * @ORM\Table(name="tbme_users_password_reset_tokens")
 */
class PasswordResetToken implements PasswordResetTokenInterface
{
    use PasswordResetTokenTrait;

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var UserInterface
     * @ORM\ManyToOne(targetEntity=User::class)
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;

    public function __construct(UserInterface $user)
    {
        $this->user = $user;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUser(): UserInterface
    {
        return $this->user;
    }
}


// src/Subscriber/SecurityPasswordResetSubscriber.php

namespace App\Subscriber;

use SerendipityHQ\Bundle\UsersBundle\Event\PasswordResetTokenCreatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;

/**
 * Send reminders to ask the feedback releasing.
 */
final class SecurityPasswordResetSubscriber implements EventSubscriberInterface
{
    private MailerInterface $mailer;
    public function __construct(MailerInterface $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents(): array
    {
        return [
            PasswordResetTokenCreatedEvent::class => 'onPasswordResetTokenCreated'
        ];
    }

    public function onPasswordResetTokenCreated(PasswordResetTokenCreatedEvent $event)
    {
        $user = $event->getUser();
        $token = $event->getToken();

        $email = (new TemplatedEmail())
            // @todo Use values from ENV config
            ->from(new Address('[email protected]', 'TrustBack.Me'))
            ->to($user->getEmail())
            // @todo translate this message
            ->subject('Your password reset request')
            ->htmlTemplate('App/user/password/reset_email.html.twig')
            ->context(['token' => $token]);

        $this->mailer->send($email);
    }
}
diff


// config/bundles.php

return [
    Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
    Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
    Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true],
    Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
    Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
    Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
+    SerendipityHQ\Bundle\UsersBundle\SHQUsersBundle::class => ['all' => true],
    Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
    Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
    Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
];
diff
// src/Controller/UserProfileController.php

+ use App\Form\UserType;

final class UserProfileController extends AbstractController
{
    ...

+    /**
+     * @Route("/profile/edit", name="user_profile_edit")
+     */
+    public function edit(Request $request): Response
+    {
+        /** @var User $user */
+        $user = $this->getUser();
+        $form = $this->getFormFactory()->create(UserType::class, $user, [
+            'action' => $this->generateUrl('user_profile_edit'),
+            'method' => 'POST',
+        ]);
+
+        $form->handleRequest($request);
+
+        if ($form->isSubmitted() && $form->isValid()) {
+            $this->getDoctrine()->getManager()->flush();
+            $url = $this->generateUrl('user_profile');
+
+            return new RedirectResponse($url);
+        }
+
+        return $this->render('user/edit.html.twig', [
+            'form' => $form->createView(),
+        ]);
+    }
...
}
diff


namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
+ use SerendipityHQ\Bundle\UsersBundle\Manager\PasswordManager;
+ use SerendipityHQ\Bundle\UsersBundle\Property\HasPlainPasswordInterface;
+ use SerendipityHQ\Bundle\UsersBundle\SHQUsersBundle;
+ use Symfony\Component\HttpFoundation\RedirectResponse;
+ use Symfony\Component\HttpFoundation\Request;
+ use Symfony\Component\HttpFoundation\Response;
+ use Symfony\Contracts\Translation\TranslatorInterface;

class UserPasswordController extends AbstractController
{
+    private PasswordManager $passwordManager;
+
+    public function __construct(PasswordManager $passwordManager)
+    {
+        $this->passwordManager = $passwordManager;
+    }

-    /**
-     * @Route("/user/password", name="user_password")
-     */
-    public function index()
-    {
-        return $this->render('user_password_test/index.html.twig', [
-            'controller_name' => 'UserPasswordTestController',
-        ]);
-    }

+    /**
+     * @Route("/profile/password", name="user_password_change")
+     * @Security("is_granted('ROLE_USER')", statusCode=403)
+     */
+    public function changePassword(Request $request, TranslatorInterface $translator): Response
+    {
+        /** @var HasPlainPasswordInterface $user */
+        $user = $this->getUser();
+        $form = $this->passwordManager->getPasswordHelper()->createFormPasswordChange($user);
+
+        $form->handleRequest($request);
+
+        if ($form->isSubmitted() && $form->isValid()) {
+            $this->getDoctrine()->getManager()->flush();
+            $this->addFlash('success', $translator->trans('user.password.change_password.success', [], 'shq_users'));
+            $url = $this->generateUrl('user_profile');
+
+            return new RedirectResponse($url);
+        }
+
+        return $this->render('user/password/password_change.html.twig', [
+            'form' => $form->createView(),
+        ]);
+    }
}