<?php
namespace App\Http\Controller\Auth;
use App\Application\CommandBus\Command\User\RegistrationCommand;
use App\Database\Domain\Entity\User\UserProfile;
use App\Database\Domain\Repository\UserRepository;
use App\Infrastructure\Messenger\CommandBus\CommandBusInterface;
use App\Infrastructure\Security\AuthManager;
use App\Infrastructure\Service\FacebookHelper;
use App\Infrastructure\Util\Identifier;
use Ramsey\Uuid\Uuid;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("", name="facebook_")
*/
class FacebookController extends AbstractController
{
/**
* @Route("/facebook/login", name="login")
*/
public function __invoke(FacebookHelper $facebookHelper)
{
return $this->redirect($facebookHelper->login());
}
/**
* @Route("/user-facebook/login-webhook", name="login_handle")
*/
public function handleLogin(
Request $request,
FacebookHelper $facebookHelper,
CommandBusInterface $commandBus,
UserRepository $userRepository,
AuthManager $authManager
): Response {
$fbInstance = $facebookHelper->makeInstance();
$loginHelper = $fbInstance->getRedirectLoginHelper();
$accessToken = $loginHelper->getAccessToken();
if (null === $accessToken) {
throw new \RuntimeException('Access token is missing');
}
$fbProfile = $fbInstance->get('/me?fields=id,first_name,email,last_name', $accessToken)->getGraphUser();
if (!$fbProfile->getEmail()) {
$request->getSession()->set('facebook_error', 'You must specify email address on your facebook account to continue. https://www.facebook.com/settings');
return $this->redirectToRoute('user_login');
}
$user = $userRepository->findByEmail($fbProfile->getEmail());
if (!$user) {
$command = new RegistrationCommand();
$command->id = Identifier::generate();
$command->name = $fbProfile->getName() ?: $fbProfile->getEmail();
$command->surname = $fbProfile->getLastName();
$command->avatarUrl = 'https://graph.facebook.com/' . $fbProfile->getId() . '/picture?type=large';
$command->email = $fbProfile->getEmail();
$command->username = $fbProfile->getEmail();
$command->emailConfirmed = true;
$command->registrationType = UserProfile::REGISTRATION_TYPE_FACEBOOK;
$commandBus->execute($command);
$user = $userRepository->find($command->id);
return $authManager->manualLogin($user, 'registration_finish_registration');
}
return $authManager->manualLogin($user);
}
}