Skip to content

Instantly share code, notes, and snippets.

@stoefln
Created October 5, 2011 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stoefln/1263863 to your computer and use it in GitHub Desktop.
Save stoefln/1263863 to your computer and use it in GitHub Desktop.
facebook connect
{% extends "AjadoEventHubBundle::layout.html.twig" %}
{% block title %}Facebook Kontakt Import{% endblock %}
{% block content %}
<h1>Facebook Contact Import</h1>
{% if not connectedToFacebook %}
You have to authorize via facebook:
<a href="{{ facebook_login_url('create_event', 'manage_pages', 'publish_stream', 'manage_pages') }}" class="facebook-connect"><span>Facebook Connect</span></a>
{% else %}
<a href="{{ path('_contact_importFromFacebook', {'action': 'import'}) }}" class="buttonBlue">
{% if contactsImported %}
Kontakte aktualisieren / ergänzen
{% else %}
Import starten
{% endif %}
</a>
{% endif %}
{% endblock %}
<?php
namespace Ajado\EventHubBundle\Twig\Extension;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
*
*/
class EventiplyExtension extends \Twig_Extension
{
protected $container;
protected $facebook;
protected function getContainer(){
return $this->container;
}
/**
* Constructor.
*
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
*
* @return \Facebook
*/
protected function getFacebook() {
//return $this->container->get('ajado_facebook');
if(!$this->facebook){
//require_once '../vendor/facebook/src/facebook.php';
$this->facebook = new \Ajado\EventHubBundle\Library\FacebookSessionPersistence(array(
'appId' => $this->getContainer()->getParameter('facebook.app_id'),//'216760401701682',
'secret' => $this->getContainer()->getParameter('facebook.secret'),//'7619413039c46b020d4fd48d95a92d94',
), $this->getSession());
}
return $this->facebook;
}
/**
*
* @return \Symfony\Component\HttpFoundation\Session
*/
protected function getSession() {
return $this->container->get('session');
}
/**
* Returns a list of global functions to add to the existing list.
*
* @return array An array of global functions
*/
public function getFunctions()
{
return array(
'facebook_login_url' => new \Twig_Function_Method($this, 'renderFacebookLoginUrl', array('is_safe' => array('html'))),
'connected_to_facebook' => new \Twig_Function_Method($this, 'renderConnectedToFacebook'),
'debug' => new \Twig_Function_Method($this, 'renderDebug'),
);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'eventiply';
}
public function renderDebug($obj)
{
return var_dump($obj);
}
public function renderFacebookLoginUrl($scope = '')
{
/* @var $request \Symfony\Component\HttpFoundation\Request */
$request = $this->container->get('request');
//print_r($parameters);
$loginUrl = $this->getFacebook()->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $this->container->get('router')->generate('_validate_facebookConnect',array(),true).'?redirect='.'http://'.$request->getHost().$request->getRequestUri(),
));
$_SERVER['HTTP_HOST'] = $request->getHost();
$_SERVER['REQUEST_URI'] = $request->getRequestUri();
return $loginUrl;
}
public function renderConnectedToFacebook(){
return $this->getFacebook()->getUser();
}
}
<?php
namespace Ajado\EventHubBundle\Library;
use Symfony\Component\HttpFoundation\Session;
/**
* Implements Symfony2 session persistence for Facebook.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
* @author Stephan Petzl
*/
class FacebookSessionPersistence extends \BaseFacebook
{
const PREFIX = '_ajado_facebook_';
private $session;
private $prefix;
public function __construct($config, Session $session, $prefix = self::PREFIX)
{
$this->session = $session;
$this->prefix = $prefix;
parent::__construct($config);
}
/**
* Stores the given ($key, $value) pair, so that future calls to
* getPersistentData($key) return $value. This call may be in another request.
*
* @param string $key
* @param array $value
*
* @return void
*/
protected function setPersistentData($key, $value)
{
$this->session->set($this->prefix.$key, $value);
}
/**
* Get the data for $key, persisted by BaseFacebook::setPersistentData()
*
* @param string $key The key of the data to retrieve
* @param boolean $default The default value to return if $key is not found
*
* @return mixed
*/
protected function getPersistentData($key, $default = false)
{
return $this->session->get($this->prefix.$key, $default);
}
/**
* Clear the data with $key from the persistent storage
*
* @param string $key
* @return void
*/
protected function clearPersistentData($key)
{
$this->session->remove($this->prefix.$key);
}
/**
* Clear all data from the persistent storage
*
* @return void
*/
protected function clearAllPersistentData()
{
foreach ($this->session->all() as $k => $v) {
if (0 !== strpos($k, $this->prefix)) {
continue;
}
$this->session->remove($k);
}
}
}
<?php
namespace Ajado\EventHubBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/**
* authorizes the user at facebook and attaches the facebook account to the currently logged in user
* @Route("/validate")
*/
class ValidateController extends BaseController
{
/**
*
* @var \Doctrine\ORM\EntityManager
*/
private $em;
/**
*
* @var \Symfony\Component\HttpFoundation\Request
*/
private $request;
/**
*
* @Route("/facebook-connect",name="_validate_facebookConnect")
*/
public function facebookConnectAction(){
if(!$this->getUser()){
throw new \Exception("login before connecting to facebook");
}
$perms = 'offline_access';
$facebookId = $this->getFacebook()->getUser();
if($facebookId){
$user = $this->getUser();
$user->setFacebookID($facebookId);
$user->setFacebookAccessToken($this->getFacebook()->getAccessToken());
$this->em()->persist($user);
$this->em()->flush();
$redirectUrl = $this->getRequest()->get('redirect');
if($redirectUrl){
return $this->redirect($redirectUrl);
}else{
return $this->redirect($this->generateUrl('_index_index'));
}
}
throw new \Exception("something went wrong during facebook authorization! Current URL: ". urldecode($this->getRequest()->getUri()));
/* not needed right now:
else{
return $this->redirect($this->getFacebook()->getLoginUrl(array(
'scope' => $perms,
)));
}*/
}
/**
*
* @Route("/logout",name="_validate_logout")
*/
public function logoutAction(){
$symfonyLogoutUrl = $this->generateUrl('fos_user_security_logout', array(), true);
// if user is logged in in facebook -> log him/her out there too
if($this->getFacebook()->getUser()){
//session_destroy();
//TODO: try this instead:
$this->getRequest()->getSession()->invalidate();
$logoutUrl = $this->getFacebook()->getLogoutUrl(array(
//'next' => $symfonyLogoutUrl,
));
return $this->redirect($logoutUrl);
}
//return $this->redirect($this->generateUrl('_index_index'));
return $this->redirect($symfonyLogoutUrl);
}
}
@stoefln
Copy link
Author

stoefln commented Oct 5, 2011

Forgot to say: this is without popup (client side authentication with FB JS sdk). but you can do the authorization client side too, and redirect to facebookConnectAction() after popup has closed.

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