/** * @return \Zend\Http\Response * @throws \Facebook\FacebookRequestException */ public function facebookCallbackAction() { $config = $this->getServiceLocator()->get('config')['facebook']; $config['callbackUrl'] = $this->url()->fromRoute('user/default', ['controller' => 'auth', 'action' => 'facebook-callback'], ['force_canonical' => true]); FacebookSession::setDefaultApplication($config['appId'], $config['appSecret']); $helper = new FacebookRedirectLoginHelper($config['callbackUrl']); try { $session = $helper->getSessionFromRedirect(); } catch (\Exception $ex) { $this->flashMessenger()->addErrorMessage("Invalid callback request. Oops. Sorry."); return $this->redirect()->toRoute('home'); } if ($session) { // Logged in $request = new FacebookRequest($session, 'GET', '/me'); $response = $request->execute(); $graphObject = $response->getGraphObject(); /** * @var \Doctrine\ORM\EntityManager $objectManager */ $objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager'); /** * @var \User\Entity\Auth $auth */ $auth = $objectManager->getRepository('User\\Entity\\Auth')->getAuthRow(Auth::PROVIDER_FACEBOOK, $graphObject->getProperty('id')); if ($auth) { $user = $auth->getUser(); if (!$user->isActive()) { $this->flashMessenger()->addSuccessMessage("'User is not active'"); return $this->redirect()->toRoute('home'); } $auth->setToken($session->getAccessToken()); $auth->setTokenSecret(0); $auth->setTokenType(Auth::TYPE_ACCESS); $message = "You've successfully logged in via facebook"; } else { if (!$this->identity()) { //create new user $user = new \User\Entity\User(); $displayName = $graphObject->getProperty('first_name') . ' ' . $graphObject->getProperty('last_name'); $user->setDisplayName($displayName); $user->setRole($user::ROLE_USER); $user->activate(); $objectManager->persist($user); $objectManager->flush(); } else { //get current authorized user $user = $this->identity()->getUser(); } $auth = new \User\Entity\Auth(); $auth->setToken($session->getAccessToken()); $auth->setTokenSecret(0); $auth->setForeignKey($graphObject->getProperty('id')); $auth->setProvider(Auth::PROVIDER_FACEBOOK); $auth->setTokenType(Auth::TYPE_ACCESS); $auth->setUserId($user->getId()); $user->getAuths()->add($auth); $auth->setUser($user); $message = "You've successfully registered via facebook"; } $objectManager->persist($user); $objectManager->persist($auth); $objectManager->flush(); $auth->login($this->getServiceLocator()); $this->flashMessenger()->addSuccessMessage($message); $session = new Container('location'); $location = $session->location; if ($location) { $session->getManager()->getStorage()->clear('location'); return $this->redirect()->toUrl($location); } return $this->redirect()->toRoute('home'); } }