diff --git a/Controller/AuthController.php b/Controller/AuthController.php new file mode 100644 index 0000000..3d2b18c --- /dev/null +++ b/Controller/AuthController.php @@ -0,0 +1,16 @@ +getRequest( )->get( "accessToken" ); + $this->get( "session" )->set( "fb.accessToken", $accessToken ); + return new JsonResponse( array( "accessToken" => $accessToken )); + } +} diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index b37049c..e27932b 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -10,9 +10,7 @@ */ namespace FOS\FacebookBundle\DependencyInjection; - -use Symfony\Component\Config\Definition\Builder\TreeBuilder, - Symfony\Component\Config\Definition\ConfigurationInterface; +use Symfony\Component\Config\Definition\Builder\TreeBuilder, Symfony\Component\Config\Definition\ConfigurationInterface; /** * This class contains the configuration information for the bundle @@ -24,38 +22,28 @@ */ class Configuration implements ConfigurationInterface { - /** - * Generates the configuration tree. - * - * @return TreeBuilder - */ - public function getConfigTreeBuilder() - { - $treeBuilder = new TreeBuilder(); - $rootNode = $treeBuilder->root('fos_facebook'); - - $rootNode - ->fixXmlConfig('permission', 'permissions') - ->children() - ->scalarNode('app_id')->isRequired()->cannotBeEmpty()->end() - ->scalarNode('secret')->isRequired()->cannotBeEmpty()->end() - ->scalarNode('file')->defaultNull()->end() - ->scalarNode('cookie')->defaultFalse()->end() - ->scalarNode('domain')->defaultNull()->end() - ->scalarNode('alias')->defaultNull()->end() - ->scalarNode('logging')->defaultValue('%kernel.debug%')->end() - ->scalarNode('culture')->defaultValue('en_US')->end() - ->arrayNode('class') - ->addDefaultsIfNotSet() - ->children() - ->scalarNode('api')->defaultValue('FOS\FacebookBundle\Facebook\FacebookSessionPersistence')->end() - ->scalarNode('helper')->defaultValue('FOS\FacebookBundle\Templating\Helper\FacebookHelper')->end() - ->scalarNode('twig')->defaultValue('FOS\FacebookBundle\Twig\Extension\FacebookExtension')->end() - ->end() - ->end() - ->arrayNode('permissions')->prototype('scalar')->end() - ->end(); - - return $treeBuilder; - } + /** + * Generates the configuration tree. + * + * @return TreeBuilder + */ + + public function getConfigTreeBuilder( ) + { + $treeBuilder = new TreeBuilder( ); + $rootNode = $treeBuilder->root( 'fos_facebook' ); + + $rootNode->fixXmlConfig( 'permission', 'permissions' )->children( )->scalarNode( 'app_id' )->isRequired( ) + ->cannotBeEmpty( )->end( )->scalarNode( 'secret' )->isRequired( )->cannotBeEmpty( )->end( )->scalarNode( 'file' ) + ->defaultNull( )->end( )->scalarNode( 'cookie' )->defaultFalse( )->end( )->scalarNode( 'domain' ) + ->defaultNull( )->end( )->scalarNode( 'alias' )->defaultNull( )->end( )->scalarNode( 'logging' ) + ->defaultValue( '%kernel.debug%' )->end( )->scalarNode( 'culture' )->defaultValue( 'en_US' )->end( ) + ->arrayNode( 'class' )->addDefaultsIfNotSet( )->children( )->scalarNode( 'api' ) + ->defaultValue( 'FOS\FacebookBundle\Facebook\FacebookSessionPersistence' )->end( )->scalarNode( 'helper' ) + ->defaultValue( 'FOS\FacebookBundle\Templating\Helper\FacebookHelper' )->end( )->scalarNode( 'twig' ) + ->defaultValue( 'FOS\FacebookBundle\Twig\Extension\FacebookExtension' )->end( )->end( )->end( ) + ->arrayNode( 'permissions' )->prototype( 'scalar' )->end( )->end( ); + + return $treeBuilder; + } } diff --git a/DependencyInjection/FOSFacebookExtension.php b/DependencyInjection/FOSFacebookExtension.php index da243b0..9743492 100644 --- a/DependencyInjection/FOSFacebookExtension.php +++ b/DependencyInjection/FOSFacebookExtension.php @@ -10,7 +10,6 @@ */ namespace FOS\FacebookBundle\DependencyInjection; - use Symfony\Component\Config\Definition\Processor; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; @@ -19,62 +18,67 @@ class FOSFacebookExtension extends Extension { - protected $resources = array( - 'facebook' => 'facebook.xml', - 'security' => 'security.xml', - ); - - public function load(array $configs, ContainerBuilder $container) + protected $resources = array( 'facebook' => 'facebook.xml', 'security' => 'security.xml', ); + + public function load( array $configs, ContainerBuilder $container ) + { + $processor = new Processor( ); + $configuration = new Configuration( ); + $config = $processor->processConfiguration( $configuration, $configs ); + + $this->loadDefaults( $container ); + + if ( isset( $config[ 'alias' ] ) ) { - $processor = new Processor(); - $configuration = new Configuration(); - $config = $processor->processConfiguration($configuration, $configs); - - $this->loadDefaults($container); - - if (isset($config['alias'])) { - $container->setAlias($config['alias'], 'fos_facebook.api'); - } - - foreach (array('api', 'helper', 'twig') as $attribute) { - $container->setParameter('fos_facebook.'.$attribute.'.class', $config['class'][$attribute]); - } - - foreach (array('app_id', 'secret', 'cookie', 'domain', 'logging', 'culture', 'permissions') as $attribute) { - $container->setParameter('fos_facebook.'.$attribute, $config[$attribute]); - } - - if (isset($config['file']) && $container->hasDefinition('fos_facebook.api')) { - $facebookApi = $container->getDefinition('fos_facebook.api'); - $facebookApi->setFile($config['file']); - } + $container->setAlias( $config[ 'alias' ], 'fos_facebook.api' ); } - - /** - * @codeCoverageIgnore - */ - public function getXsdValidationBasePath() + + foreach ( array( 'api', 'helper', 'twig' ) as $attribute ) { - return __DIR__ . '/../Resources/config/schema'; + $container->setParameter( 'fos_facebook.' . $attribute . '.class', $config[ 'class' ][ $attribute ] ); } - - /** - * @codeCoverageIgnore - */ - public function getNamespace() + + foreach ( array( 'app_id', 'secret', 'cookie', 'domain', 'logging', 'culture', 'permissions' ) as $attribute ) { - return 'http://symfony.com/schema/dic/fos_facebook'; + $container->setParameter( 'fos_facebook.' . $attribute, $config[ $attribute ] ); } - - /** - * @codeCoverageIgnore - */ - protected function loadDefaults($container) + + if ( isset( $config[ 'file' ] ) && $container->hasDefinition( 'fos_facebook.api' ) ) { - $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); - - foreach ($this->resources as $resource) { - $loader->load($resource); - } + $facebookApi = $container->getDefinition( 'fos_facebook.api' ); + $facebookApi->setFile( $config[ 'file' ] ); + } + } + + /** + * @codeCoverageIgnore + */ + + public function getXsdValidationBasePath( ) + { + return __DIR__ . '/../Resources/config/schema'; + } + + /** + * @codeCoverageIgnore + */ + + public function getNamespace( ) + { + return 'http://symfony.com/schema/dic/fos_facebook'; + } + + /** + * @codeCoverageIgnore + */ + + protected function loadDefaults( $container ) + { + $loader = new XmlFileLoader( $container, new FileLocator( __DIR__ . '/../Resources/config')); + + foreach ( $this->resources as $resource ) + { + $loader->load( $resource ); } + } } diff --git a/DependencyInjection/Security/Factory/FacebookFactory.php b/DependencyInjection/Security/Factory/FacebookFactory.php index 67b10cc..5885c7d 100644 --- a/DependencyInjection/Security/Factory/FacebookFactory.php +++ b/DependencyInjection/Security/Factory/FacebookFactory.php @@ -18,60 +18,57 @@ class FacebookFactory extends AbstractFactory { - public function __construct() + + public function __construct( ) + { + $this->addOption( 'display', 'page' ); + $this->addOption( 'app_url' ); + $this->addOption( 'server_url' ); + $this->addOption( 'create_user_if_not_exists', false ); + } + + public function getPosition( ) + { + return 'pre_auth'; + } + + public function getKey( ) + { + return 'fos_facebook'; + } + + protected function getListenerId( ) + { + return 'fos_facebook.security.authentication.listener'; + } + + protected function createAuthProvider( ContainerBuilder $container, $id, $config, $userProviderId ) + { + $authProviderId = 'fos_facebook.auth.' . $id; + + $definition = $container->setDefinition( $authProviderId, new DefinitionDecorator( 'fos_facebook.auth') ) + ->replaceArgument( 0, $id ); + + // with user provider + if ( isset( $config[ 'provider' ] ) ) { - $this->addOption('display', 'page'); - $this->addOption('app_url'); - $this->addOption('server_url'); - $this->addOption('create_user_if_not_exists', false); - } - - public function getPosition() - { - return 'pre_auth'; - } - - public function getKey() - { - return 'fos_facebook'; - } - - protected function getListenerId() - { - return 'fos_facebook.security.authentication.listener'; - } - - protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId) - { - $authProviderId = 'fos_facebook.auth.'.$id; - - $definition = $container - ->setDefinition($authProviderId, new DefinitionDecorator('fos_facebook.auth')) - ->replaceArgument(0, $id); - - // with user provider - if (isset($config['provider'])) { - $definition - ->addArgument(new Reference($userProviderId)) - ->addArgument(new Reference('security.user_checker')) - ->addArgument($config['create_user_if_not_exists']) - ; - } - - return $authProviderId; - } - - protected function createEntryPoint($container, $id, $config, $defaultEntryPointId) - { - $entryPointId = 'fos_facebook.security.authentication.entry_point.'.$id; - $container - ->setDefinition($entryPointId, new DefinitionDecorator('fos_facebook.security.authentication.entry_point')) - ->replaceArgument(1, $config) - ; - - // set options to container for use by other classes - $container->setParameter('fos_facebook.options.'.$id, $config); - - return $entryPointId; + $definition->addArgument( new Reference( $userProviderId) )->addArgument( new Reference( 'security.user_checker') ) + ->addArgument( $config[ 'create_user_if_not_exists' ] ); } + + return $authProviderId; + } + + protected function createEntryPoint( $container, $id, $config, $defaultEntryPointId ) + { + $entryPointId = 'fos_facebook.security.authentication.entry_point.' . $id; + $container + ->setDefinition( $entryPointId, new DefinitionDecorator( 'fos_facebook.security.authentication.entry_point') ) + ->replaceArgument( 1, $config ); + + // set options to container for use by other classes + $container->setParameter( 'fos_facebook.options.' . $id, $config ); + + return $entryPointId; + } } diff --git a/FOSFacebookBundle.php b/FOSFacebookBundle.php index ab9904b..3105194 100644 --- a/FOSFacebookBundle.php +++ b/FOSFacebookBundle.php @@ -10,18 +10,18 @@ */ namespace FOS\FacebookBundle; - use FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; class FOSFacebookBundle extends Bundle { - public function build(ContainerBuilder $container) - { - parent::build($container); - - $extension = $container->getExtension('security'); - $extension->addSecurityListenerFactory(new FacebookFactory()); - } + + public function build( ContainerBuilder $container ) + { + parent::build( $container ); + + $extension = $container->getExtension( 'security' ); + $extension->addSecurityListenerFactory( new FacebookFactory( ) ); + } } diff --git a/Facebook/FacebookSessionPersistence.php b/Facebook/FacebookSessionPersistence.php index a724e90..96751dd 100644 --- a/Facebook/FacebookSessionPersistence.php +++ b/Facebook/FacebookSessionPersistence.php @@ -1,7 +1,6 @@ session = $session; - $this->prefix = $prefix; - $this->session->start(); - - 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) + const PREFIX = '_fos_facebook_'; + + protected $session; + protected $prefix; + protected static $kSupportedKeys = array( 'state', 'code', 'access_token', 'user_id' ); + + /** + * @param array $config the application configuration. + * @see BaseFacebook::__construct in facebook.php + */ + + public function __construct( $config, Session $session, $prefix = self::PREFIX ) + { + $this->session = $session; + $this->prefix = $prefix; + $this->session->start( ); + + 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 ) + { + if ( !in_array( $key, self::$kSupportedKeys ) ) { - if (!in_array($key, self::$kSupportedKeys)) { - self::errorLog('Unsupported key passed to setPersistentData.'); - return; - } - - $this->session->set($this->constructSessionVariableName($key), $value); + self::errorLog( 'Unsupported key passed to setPersistentData.' ); + return; } - - /** - * 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) + + $this->session->set( $this->constructSessionVariableName( $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 ) + { + if ( !in_array( $key, self::$kSupportedKeys ) ) { - if (!in_array($key, self::$kSupportedKeys)) { - self::errorLog('Unsupported key passed to getPersistentData.'); - return $default; - } - - $sessionVariableName = $this->constructSessionVariableName($key); - if ($this->session->has($sessionVariableName)) { - return $this->session->get($sessionVariableName); - } - - return $default; - + self::errorLog( 'Unsupported key passed to getPersistentData.' ); + return $default; } - - /** - * Clear the data with $key from the persistent storage - * - * @param string $key - * @return void - */ - protected function clearPersistentData($key) + + $sessionVariableName = $this->constructSessionVariableName( $key ); + if ( $this->session->has( $sessionVariableName ) ) { - if (!in_array($key, self::$kSupportedKeys)) { - self::errorLog('Unsupported key passed to clearPersistentData.'); - return; - } - - $this->session->remove($this->constructSessionVariableName($key)); + return $this->session->get( $sessionVariableName ); } - - /** - * Clear all data from the persistent storage - * - * @return void - */ - protected function clearAllPersistentData() + + return $default; + + } + + /** + * Clear the data with $key from the persistent storage + * + * @param string $key + * @return void + */ + + protected function clearPersistentData( $key ) + { + if ( !in_array( $key, self::$kSupportedKeys ) ) { - foreach ($this->session->all() as $k => $v) { - if (0 !== strpos($k, $this->prefix)) { - continue; - } - - $this->session->remove($k); - } + self::errorLog( 'Unsupported key passed to clearPersistentData.' ); + return; } - - protected function constructSessionVariableName($key) + + $this->session->remove( $this->constructSessionVariableName( $key ) ); + } + + /** + * Clear all data from the persistent storage + * + * @return void + */ + + protected function clearAllPersistentData( ) + { + foreach ( $this->session->all( ) as $k => $v ) { - return $this->prefix.implode('_', array( - 'fb', - $this->getAppId(), - $key, - )); + if ( 0 !== strpos( $k, $this->prefix ) ) + { + continue; + } + + $this->session->remove( $k ); } + } + + protected function constructSessionVariableName( $key ) + { + return $this->prefix + . implode( '_', array( 'fb', $this->getAppId( ), $key, ) ); + } } diff --git a/README.md b/README.md deleted file mode 100644 index 1364948..0000000 --- a/README.md +++ /dev/null @@ -1,491 +0,0 @@ -Introduction -============ - -This Bundle enables integration of the Facebook PHP and JS SDK's. Furthermore it -also provides a Symfony2 authentication provider so that users can login to a -Symfony2 application via Facebook. Furthermore via custom user provider support -the Facebook login can also be integrated with other data sources like the -database based solution provided by FOSUserBundle. - -Note that logging in a user requires multiple steps: - - 1. the user must be logged into Facebook - 2. the user must connect his Facebook account to your site - 3. once the user has done 1. and 2. you must trigger the login - -For step 1. and 2. there are two options: - - 1. Select "OAuth Migration" in the Facebook application settings. - 2. Add a Facebook login button, this approach requires JS code to handle step 3. - 3. Letting FOSFacebookBundle redirect to the Facebook login page. - -Note that the later happens automatically if the first provider in your first -firewall configuration is configured to FOSFacebookBundle and the user accesses -a page that requires authentication without being authenticated. - -Please also refer to the Facebook documentation: -https://developers.facebook.com/docs/guides/web/ - -Please also refer to the official documentation of the SecurityBundle, especially -for details on the configuration: -http://symfony.com/doc/current/book/security.html - -[![Build Status](https://secure.travis-ci.org/FriendsOfSymfony/FOSFacebookBundle.png?branch=master)](http://travis-ci.org/FriendsOfSymfony/FOSFacebookBundle) - -Installation -============ - - 1. Add this bundle and the Facebook PHP SDK to your ``vendor/`` dir: - * Using the vendors script. - - Add the following lines in your ``deps`` file:: - - [FOSFacebookBundle] - git=git://github.com/FriendsOfSymfony/FOSFacebookBundle.git - target=/bundles/FOS/FacebookBundle - version=origin/master - - [FacebookSDK] - git=git://github.com/facebook/facebook-php-sdk.git - target=/facebook - - Run the vendors script: - - php bin/vendors install - - * Using git submodules. - - $ git submodule add git://github.com/FriendsOfSymfony/FOSFacebookBundle.git vendor/bundles/FOS/FacebookBundle - $ git submodule add git://github.com/facebook/facebook-php-sdk.git vendor/facebook - - 2. Add the FOS namespace to your autoloader: - - // app/autoload.php - $loader->registerNamespaces(array( - 'FOS' => __DIR__.'/../vendor/bundles', - // your other namespaces - )); - - 3. Add this bundle to your application's kernel: - - // app/ApplicationKernel.php - public function registerBundles() - { - return array( - // ... - new FOS\FacebookBundle\FOSFacebookBundle(), - // ... - ); - } - - 4. Add the following routes to your application and point them at actual controller actions - - #application/config/routing.yml - _security_check: - pattern: /login_check - _security_logout: - pattern: /logout - - #application/config/routing.xml - - - - 5. Configure the `facebook` service in your config: - - # application/config/config.yml - fos_facebook: - file: %kernel.root_dir%/../vendor/facebook/src/base_facebook.php - alias: facebook - app_id: 123456879 - secret: s3cr3t - cookie: true - permissions: [email, user_birthday, user_location] - - # application/config/config.xml - - email - user_birthday - user_location - - - If you do not include a `file` value in the config you will have to - configure your application to autoload the `BaseFacebook` class. - - 6. Add this configuration if you want to use the `security component`: - - # application/config/config.yml - security: - firewalls: - public: - # since anonymous is allowed users will not be forced to login - pattern: ^/.* - fos_facebook: - app_url: "http://apps.facebook.com/appName/" - server_url: "http://localhost/facebookApp/" - anonymous: true - logout: - handlers: ["fos_facebook.logout_handler"] - - access_control: - - { path: ^/secured/.*, role: [IS_AUTHENTICATED_FULLY] } # This is the route secured with fos_facebook - - { path: ^/.*, role: [IS_AUTHENTICATED_ANONYMOUSLY] } - - You have to add `/secured/` in your routing for this to work. An example would be... - - _facebook_secured: - pattern: /secured/ - defaults: { _controller: AcmeDemoBundle:Welcome:index } - - 7. Optionally define a custom user provider class and use it as the provider or define path for login - - # application/config/config.yml - security: - providers: - # choose the provider name freely - my_fos_facebook_provider: - id: my.facebook.user # see "Example Custom User Provider using the FOS\UserBundle" chapter further down - - firewalls: - public: - pattern: ^/.* - fos_facebook: - app_url: "http://apps.facebook.com/appName/" - server_url: "http://localhost/facebookApp/" - login_path: ^/login - check_path: ^/login_check$ - default_target_path: / - provider: my_fos_facebook_provider - anonymous: true - logout: - handlers: ["fos_facebook.logout_handler"] - - # application/config/config_dev.yml - security: - firewalls: - public: - fos_facebook: - app_url: "http://apps.facebook.com/appName/" - server_url: "http://localhost/facebookApp/app_dev.php/" - - 8. Optionally use access control to secure specific URLs - - - # application/config/config.yml - security: - # ... - - access_control: - - { path: ^/facebook/, role: [ROLE_FACEBOOK] } - - { path: ^/.*, role: [IS_AUTHENTICATED_ANONYMOUSLY] } - - The role `ROLE_FACEBOOK` has to be added in your User class (see Acme\MyBundle\Entity\User::setFBData() below). - > Note that the order of access control rules matters! - -Setting up the JavaScript SDK ------------------------------ - -A templating helper is included for loading the Facebook JavaScript SDK and -initializing it with parameters from your service container. To setup the -Facebook JavaScript environment, add the following to your layout just after -the opening `body` tag: - - - - initialize(array('xfbml' => true, 'fbAsyncInit' => 'onFbInit();')) ?> - - {{ facebook_initialize({'xfbml': true, 'fbAsyncInit': 'onFbInit();'}) }} - -Note that `fbAsyncInit` is a parameter helping you to execute JavaScript within -the function initializing the connection with Facebook, just after the `FB.init();` -call. `onFbInit();` is a JavaScript function defined furthermore to execute functions -which need `FB` initialized. - -If you will be adding XFBML markup to your site you may also declare the -namespace, perhaps in the opening `html` tag: - - - -Include the login button in your templates ------------------------------------------- - -Just add the following code in one of your templates: - - - loginButton(array('autologoutlink' => true)) ?> - - {{ facebook_login_button({'autologoutlink': true}) }} - -Note that with this approach only the login and connecting with Facebook will -be handled. The step of logging in the user into your Symfony2 application -still needs to be triggered. To do this you will in most cases simply subscribe -to the `auth.statusChange` event and then redirect to the `check_path`: - - - -Note that we wait 500ms before redirecting to let the browser dealing with the -Facebook cookie. You can avoid this step but you might get this error message: -*"The Facebook user could not be retrieved from the session."* - -The "_security_check" route would need to point to a "/login_check" pattern -to match the above configuration. - -Also, you need to trigger the logout action, so, using the same event (`auth.statusChange`), add a simple -check for `response.session` to redirect to the "logout" route: - - - - -Example Custom User Provider using the FOS\UserBundle -------------------------------------------------------- - -This requires adding a service for the custom user provider which is then set -to the provider id in the "provider" section in the config.yml: - - services: - my.facebook.user: - class: Acme\MyBundle\Security\User\Provider\FacebookProvider - arguments: - facebook: "@fos_facebook.api" - userManager: "@fos_user.user_manager" - validator: "@validator" - container: "@service_container" - - facebook = $facebook; - $this->userManager = $userManager; - $this->validator = $validator; - } - - public function supportsClass($class) - { - return $this->userManager->supportsClass($class); - } - - public function findUserByFbId($fbId) - { - return $this->userManager->findUserBy(array('facebookId' => $fbId)); - } - - public function loadUserByUsername($username) - { - $user = $this->findUserByFbId($username); - - try { - $fbdata = $this->facebook->api('/me'); - } catch (FacebookApiException $e) { - $fbdata = null; - } - - if (!empty($fbdata)) { - if (empty($user)) { - $user = $this->userManager->createUser(); - $user->setEnabled(true); - $user->setPassword(''); - } - - // TODO use http://developers.facebook.com/docs/api/realtime - $user->setFBData($fbdata); - - if (count($this->validator->validate($user, 'Facebook'))) { - // TODO: the user was found obviously, but doesnt match our expectations, do something smart - throw new UsernameNotFoundException('The facebook user could not be stored'); - } - $this->userManager->updateUser($user); - } - - if (empty($user)) { - throw new UsernameNotFoundException('The user is not authenticated on facebook'); - } - - return $user; - } - - public function refreshUser(UserInterface $user) - { - if (!$this->supportsClass(get_class($user)) || !$user->getFacebookId()) { - throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); - } - - return $this->loadUserByUsername($user->getFacebookId()); - } - } - -Finally one also needs to add a getFacebookId() and setFBData() method to the User model. -The following example also adds "firstname" and "lastname" properties, using the Doctrine ORM: - - facebookId, parent::serialize())); - } - - public function unserialize($data) - { - list($this->facebookId, $parentData) = unserialize($data); - parent::unserialize($parentData); - } - - /** - * @return string - */ - public function getFirstname() - { - return $this->firstname; - } - - /** - * @param string $firstname - */ - public function setFirstname($firstname) - { - $this->firstname = $firstname; - } - - /** - * @return string - */ - public function getLastname() - { - return $this->lastname; - } - - /** - * @param string $lastname - */ - public function setLastname($lastname) - { - $this->lastname = $lastname; - } - - /** - * Get the full name of the user (first + last name) - * @return string - */ - public function getFullName() - { - return $this->getFirstName() . ' ' . $this->getLastname(); - } - - /** - * @param string $facebookId - * @return void - */ - public function setFacebookId($facebookId) - { - $this->facebookId = $facebookId; - $this->setUsername($facebookId); - $this->salt = ''; - } - - /** - * @return string - */ - public function getFacebookId() - { - return $this->facebookId; - } - - /** - * @param Array - */ - public function setFBData($fbdata) - { - if (isset($fbdata['id'])) { - $this->setFacebookId($fbdata['id']); - $this->addRole('ROLE_FACEBOOK'); - } - if (isset($fbdata['first_name'])) { - $this->setFirstname($fbdata['first_name']); - } - if (isset($fbdata['last_name'])) { - $this->setLastname($fbdata['last_name']); - } - if (isset($fbdata['email'])) { - $this->setEmail($fbdata['email']); - } - } - } diff --git a/Resources/config/facebook.xml b/Resources/config/facebook.xml index a376d91..4cbcf2e 100644 --- a/Resources/config/facebook.xml +++ b/Resources/config/facebook.xml @@ -1,34 +1,34 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - + - - - %fos_facebook.app_id% - %fos_facebook.secret% - %fos_facebook.cookie% - %fos_facebook.domain% - - - + + + %fos_facebook.app_id% + %fos_facebook.secret% + %fos_facebook.cookie% + %fos_facebook.domain% + + + - - - - %fos_facebook.logging% - %fos_facebook.culture% - %fos_facebook.permissions% - - + + + + %fos_facebook.logging% + %fos_facebook.culture% + %fos_facebook.permissions% + + - - - - + + + + - + diff --git a/Resources/config/routing.yml b/Resources/config/routing.yml new file mode 100644 index 0000000..13c9d1b --- /dev/null +++ b/Resources/config/routing.yml @@ -0,0 +1,4 @@ +fbWriteAuthInSession: + pattern: /fb/writeAuthInSession + defaults: { _controller: FOSFacebookBundle:Auth:writeAuthInSession } + methods: [POST] \ No newline at end of file diff --git a/Resources/config/security.xml b/Resources/config/security.xml index 7057ecf..c9318bf 100644 --- a/Resources/config/security.xml +++ b/Resources/config/security.xml @@ -1,30 +1,35 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - - - - - + + + + + + - - - + + + - - + + - - - - %fos_facebook.permissions% - + + + + %fos_facebook.permissions% + - + diff --git a/Resources/views/initialize.html.php b/Resources/views/initialize.html.php index dcbf54c..82b63f5 100644 --- a/Resources/views/initialize.html.php +++ b/Resources/views/initialize.html.php @@ -1,27 +1,34 @@ +
- - + + + diff --git a/Resources/views/initialize.html.twig b/Resources/views/initialize.html.twig index b9995ee..edd507d 100644 --- a/Resources/views/initialize.html.twig +++ b/Resources/views/initialize.html.twig @@ -1,8 +1,11 @@ +{% if not onlycode %}
{% if not async %} - + {% endif %} +{% endif %} \ No newline at end of file diff --git a/Resources/views/loginButton.html.php b/Resources/views/loginButton.html.php index 8f39685..51e7f49 100644 --- a/Resources/views/loginButton.html.php +++ b/Resources/views/loginButton.html.php @@ -1 +1 @@ - + diff --git a/Resources/views/loginFunction.html.twig b/Resources/views/loginFunction.html.twig new file mode 100644 index 0000000..53add4b --- /dev/null +++ b/Resources/views/loginFunction.html.twig @@ -0,0 +1,25 @@ +function fbLogin(callbackFnc, notAuthCallbackFnc){ + if (typeof (FB) != 'undefined' && FB != null) { + FB.getLoginStatus(function(response) { + if (response.status === 'connected') { + var accessToken = response.authResponse.accessToken; + $.post("{{ path('fbWriteAuthInSession') }}", { + "accessToken" : accessToken + }, function(response) { + if (response.accessToken == accessToken) { + $.oauthpopup({ + path : "{{ path(loginCheck) }}" + "?facebook=true", + callback : callbackFnc + }); + } + }); + } + else { + $.oauthpopup({ + path : "{{ facebook_login_url(url(loginCheck)) }}", + callback : callbackFnc + }); + } + }); + } +} \ No newline at end of file diff --git a/Resources/views/scope.html.php b/Resources/views/scope.html.php new file mode 100644 index 0000000..ad41df8 --- /dev/null +++ b/Resources/views/scope.html.php @@ -0,0 +1 @@ +"" \ No newline at end of file diff --git a/Resources/views/scope.html.twig b/Resources/views/scope.html.twig new file mode 100644 index 0000000..75f6840 --- /dev/null +++ b/Resources/views/scope.html.twig @@ -0,0 +1 @@ +'{{ scope }}' \ No newline at end of file diff --git a/Security/Authentication/Provider/FacebookProvider.php b/Security/Authentication/Provider/FacebookProvider.php index 8fdf80c..c71b878 100644 --- a/Security/Authentication/Provider/FacebookProvider.php +++ b/Security/Authentication/Provider/FacebookProvider.php @@ -10,106 +10,128 @@ */ namespace FOS\FacebookBundle\Security\Authentication\Provider; - -use FOS\FacebookBundle\Security\User\UserManagerInterface; - use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; - use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserCheckerInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface; - +use Symfony\Component\HttpFoundation\Session\Session; +use FOS\FacebookBundle\Security\User\UserManagerInterface; use FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken; class FacebookProvider implements AuthenticationProviderInterface { - /** - * @var \BaseFacebook - */ - protected $facebook; - protected $providerKey; - protected $userProvider; - protected $userChecker; - protected $createIfNotExists; - - public function __construct($providerKey, \BaseFacebook $facebook, UserProviderInterface $userProvider = null, UserCheckerInterface $userChecker = null, $createIfNotExists = false) + protected $providerKey; + protected $facebook; + protected $session; + protected $userProvider; + protected $userChecker; + protected $createIfNotExists; + + public function __construct( $providerKey, \BaseFacebook $facebook, Session $session, + UserProviderInterface $userProvider = null, UserCheckerInterface $userChecker = null, $createIfNotExists = false ) + { + if ( null !== $userProvider && null === $userChecker ) { - if (null !== $userProvider && null === $userChecker) { - throw new \InvalidArgumentException('$userChecker cannot be null, if $userProvider is not null.'); - } - - if ($createIfNotExists && !$userProvider instanceof UserManagerInterface) { - throw new \InvalidArgumentException('The $userProvider must implement UserManagerInterface if $createIfNotExists is true.'); - } - - $this->providerKey = $providerKey; - $this->facebook = $facebook; - $this->userProvider = $userProvider; - $this->userChecker = $userChecker; - $this->createIfNotExists = $createIfNotExists; + throw new \InvalidArgumentException( '$userChecker cannot be null, if $userProvider is not null.'); } - - public function authenticate(TokenInterface $token) + + if ( $createIfNotExists && !$userProvider instanceof UserManagerInterface ) { - if (!$this->supports($token)) { - return null; - } - - $user = $token->getUser(); - if ($user instanceof UserInterface) { - $this->userChecker->checkPostAuth($user); - - $newToken = new FacebookUserToken($this->providerKey, $user, $user->getRoles()); - $newToken->setAttributes($token->getAttributes()); - - return $newToken; - } - - try { - if ($uid = $this->facebook->getUser()) { - $newToken = $this->createAuthenticatedToken($uid); - $newToken->setAttributes($token->getAttributes()); - - return $newToken; - } - } catch (AuthenticationException $failed) { - throw $failed; - } catch (\Exception $failed) { - throw new AuthenticationException($failed->getMessage(), null, (int)$failed->getCode(), $failed); - } - - throw new AuthenticationException('The Facebook user could not be retrieved from the session.'); + throw new \InvalidArgumentException( + 'The $userProvider must implement UserManagerInterface if $createIfNotExists is true.'); } - - public function supports(TokenInterface $token) + + $this->providerKey = $providerKey; + $this->facebook = $facebook; + $this->session = $session; + $this->userProvider = $userProvider; + $this->userChecker = $userChecker; + $this->createIfNotExists = $createIfNotExists; + + // workaraound to use a previous login valid js access token setted in the session + $sessionAccessToken = $this->session->get( "fb.accessToken" ); + $apiAccessToken = $this->facebook->getAccessToken( ); + $appAccessToken = $this->facebook->getAppId( ) . '|' . $this->facebook->getAppSecret( ); + + if ( $sessionAccessToken !== $apiAccessToken && $apiAccessToken === $appAccessToken ) + $this->facebook->setAccessToken( $sessionAccessToken ); + } + + public function authenticate( TokenInterface $token ) + { + if ( !$this->supports( $token ) ) { - return $token instanceof FacebookUserToken && $this->providerKey === $token->getProviderKey(); + return null; } - - protected function createAuthenticatedToken($uid) + + $user = $token->getUser( ); + if ( $user instanceof UserInterface ) { - if (null === $this->userProvider) { - return new FacebookUserToken($this->providerKey, $uid); - } - - try { - $user = $this->userProvider->loadUserByUsername($uid); - $this->userChecker->checkPostAuth($user); - } catch (UsernameNotFoundException $ex) { - if (!$this->createIfNotExists) { - throw $ex; - } - - $user = $this->userProvider->createUserFromUid($uid); - } - - if (!$user instanceof UserInterface) { - throw new \RuntimeException('User provider did not return an implementation of user interface.'); - } - - return new FacebookUserToken($this->providerKey, $user, $user->getRoles()); + $this->userChecker->checkPostAuth( $user ); + + $newToken = new FacebookUserToken( $this->providerKey, $user, $user->getRoles( )); + $newToken->setAttributes( $token->getAttributes( ) ); + + return $newToken; + } + + try + { + if ( $uid = $this->facebook->getUser( ) ) + { + $newToken = $this->createAuthenticatedToken( $uid ); + $newToken->setAttributes( $token->getAttributes( ) ); + + return $newToken; + } + } + catch ( AuthenticationException $failed ) + { + throw $failed; + } + catch ( \Exception $failed ) + { + throw new AuthenticationException( $failed->getMessage( ), ( int ) $failed->getCode( ), $failed); + } + + throw new AuthenticationException( 'The Facebook user could not be retrieved from the session.'); + } + + public function supports( TokenInterface $token ) + { + return $token instanceof FacebookUserToken && $this->providerKey === $token->getProviderKey( ); + } + + protected function createAuthenticatedToken( $uid ) + { + if ( null === $this->userProvider ) + { + return new FacebookUserToken( $this->providerKey, $uid); + } + + try + { + $user = $this->userProvider->loadUserByUsername( $uid ); + $this->userChecker->checkPostAuth( $user ); + } + catch ( UsernameNotFoundException $ex ) + { + if ( !$this->createIfNotExists ) + { + throw $ex; + } + + $user = $this->userProvider->createUserFromUid( $uid ); + } + + if ( !$user instanceof UserInterface ) + { + throw new \RuntimeException( 'User provider did not return an implementation of user interface.'); } + + return new FacebookUserToken( $this->providerKey, $user, $user->getRoles( )); + } } diff --git a/Security/Authentication/Token/FacebookUserToken.php b/Security/Authentication/Token/FacebookUserToken.php index 3adc4b0..2ca960c 100644 --- a/Security/Authentication/Token/FacebookUserToken.php +++ b/Security/Authentication/Token/FacebookUserToken.php @@ -10,44 +10,44 @@ */ namespace FOS\FacebookBundle\Security\Authentication\Token; - use Symfony\Component\Security\Core\Authentication\Token\AbstractToken; class FacebookUserToken extends AbstractToken { - private $providerKey; - - public function __construct($providerKey, $uid = '', array $roles = array()) - { - parent::__construct($roles); - - $this->setUser($uid); - - if (!empty($uid)) { - $this->setAuthenticated(true); - } - - $this->providerKey = $providerKey; - } - - public function getCredentials() - { - return ''; - } - - public function getProviderKey() - { - return $this->providerKey; - } - - public function serialize() - { - return serialize(array($this->providerKey, parent::serialize())); - } - - public function unserialize($str) + private $providerKey; + + public function __construct( $providerKey, $uid = '', array $roles = array( ) ) + { + parent::__construct( $roles ); + + $this->setUser( $uid ); + + if ( !empty( $uid ) ) { - list($this->providerKey, $parentStr) = unserialize($str); - parent::unserialize($parentStr); + $this->setAuthenticated( true ); } + + $this->providerKey = $providerKey; + } + + public function getCredentials( ) + { + return ''; + } + + public function getProviderKey( ) + { + return $this->providerKey; + } + + public function serialize( ) + { + return serialize( array( $this->providerKey, parent::serialize( ) ) ); + } + + public function unserialize( $str ) + { + list($this->providerKey, $parentStr) = unserialize( $str ); + parent::unserialize( $parentStr ); + } } diff --git a/Security/EntryPoint/FacebookAuthenticationEntryPoint.php b/Security/EntryPoint/FacebookAuthenticationEntryPoint.php index 8b7cf9a..c5425b2 100644 --- a/Security/EntryPoint/FacebookAuthenticationEntryPoint.php +++ b/Security/EntryPoint/FacebookAuthenticationEntryPoint.php @@ -10,7 +10,6 @@ */ namespace FOS\FacebookBundle\Security\EntryPoint; - use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -25,44 +24,47 @@ */ class FacebookAuthenticationEntryPoint implements AuthenticationEntryPointInterface { - protected $facebook; - protected $options; - protected $permissions; - - /** - * Constructor - * - * @param BaseFacebook $facebook - * @param array $options - */ - public function __construct(\BaseFacebook $facebook, array $options = array(), array $permissions = array()) + protected $facebook; + protected $options; + protected $permissions; + + /** + * Constructor + * + * @param BaseFacebook $facebook + * @param array $options + */ + + public function __construct( \BaseFacebook $facebook, array $options = array( ), array $permissions = array( ) ) + { + $this->facebook = $facebook; + $this->permissions = $permissions; + $this->options = new ParameterBag( $options); + } + + /** + * {@inheritdoc} + */ + + public function start( Request $request, AuthenticationException $authException = null ) + { + $redirect_uri = $request->getUriForPath( $this->options->get( 'check_path', '' ) ); + if ( $this->options->get( 'server_url' ) && $this->options->get( 'app_url' ) ) { - $this->facebook = $facebook; - $this->permissions = $permissions; - $this->options = new ParameterBag($options); + $redirect_uri = str_replace( $this->options->get( 'server_url' ), $this->options->get( 'app_url' ), $redirect_uri ); } - - /** - * {@inheritdoc} - */ - public function start(Request $request, AuthenticationException $authException = null) + + $loginUrl = $this->facebook + ->getLoginUrl( + array( 'display' => $this->options->get( 'display', 'page' ), 'scope' => implode( ',', $this->permissions ), + 'redirect_uri' => $redirect_uri, ) ); + + if ( $this->options->get( 'server_url' ) && $this->options->get( 'app_url' ) ) { - $redirect_uri = $request->getUriForPath($this->options->get('check_path', '')); - if ($this->options->get('server_url') && $this->options->get('app_url')) { - $redirect_uri = str_replace($this->options->get('server_url'), $this->options->get('app_url'), $redirect_uri); - } - - $loginUrl = $this->facebook->getLoginUrl( - array( - 'display' => $this->options->get('display', 'page'), - 'scope' => implode(',', $this->permissions), - 'redirect_uri' => $redirect_uri, - )); - - if ($this->options->get('server_url') && $this->options->get('app_url')){ - return new Response(''); - } - - return new RedirectResponse($loginUrl); + return new Response( ''); } + + return new RedirectResponse( $loginUrl); + } } diff --git a/Security/Firewall/FacebookListener.php b/Security/Firewall/FacebookListener.php index 00ef0ea..56a21d5 100644 --- a/Security/Firewall/FacebookListener.php +++ b/Security/Firewall/FacebookListener.php @@ -10,7 +10,6 @@ */ namespace FOS\FacebookBundle\Security\Firewall; - use FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken; use Symfony\Component\Security\Http\Firewall\AbstractAuthenticationListener; use Symfony\Component\HttpFoundation\Request; @@ -20,8 +19,10 @@ */ class FacebookListener extends AbstractAuthenticationListener { - protected function attemptAuthentication(Request $request) - { - return $this->authenticationManager->authenticate(new FacebookUserToken($this->providerKey)); - } + + protected function attemptAuthentication( Request $request ) + { + if ( $request->get( "facebook", null ) ) + return $this->authenticationManager->authenticate( new FacebookUserToken( $this->providerKey) ); + } } diff --git a/Security/Logout/FacebookHandler.php b/Security/Logout/FacebookHandler.php index 0d73ce0..cb6cd3c 100644 --- a/Security/Logout/FacebookHandler.php +++ b/Security/Logout/FacebookHandler.php @@ -10,7 +10,6 @@ */ namespace FOS\FacebookBundle\Security\Logout; - use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; @@ -23,15 +22,15 @@ */ class FacebookHandler implements LogoutHandlerInterface { - private $facebook; - - public function __construct(\BaseFacebook $facebook) - { - $this->facebook = $facebook; - } - - public function logout(Request $request, Response $response, TokenInterface $token) - { - $this->facebook->destroySession(); - } + private $facebook; + + public function __construct( \BaseFacebook $facebook ) + { + $this->facebook = $facebook; + } + + public function logout( Request $request, Response $response, TokenInterface $token ) + { + $this->facebook->destroySession( ); + } } diff --git a/Security/User/UserManagerInterface.php b/Security/User/UserManagerInterface.php index 89e3288..0858bcd 100644 --- a/Security/User/UserManagerInterface.php +++ b/Security/User/UserManagerInterface.php @@ -1,10 +1,10 @@ templating = $templating; - $this->logging = $logging; - $this->culture = $culture; - $this->scope = $scope; - $this->facebook = $facebook; - } - - /** - * Returns the HTML necessary for initializing the JavaScript SDK. - * - * The default template includes the following parameters: - * - * * async - * * fbAsyncInit - * * appId - * * xfbml - * * oauth - * * status - * * cookie - * * logging - * * culture - * - * @param array $parameters An array of parameters for the initialization template - * @param string $name A template name - * - * @return string An HTML string - */ - public function initialize($parameters = array(), $name = null) - { - $name = $name ?: 'FOSFacebookBundle::initialize.html.php'; - return $this->templating->render($name, $parameters + array( - 'async' => true, - 'fbAsyncInit' => '', - 'appId' => (string) $this->facebook->getAppId(), - 'xfbml' => false, - 'oauth' => true, - 'status' => false, - 'cookie' => true, - 'logging' => $this->logging, - 'culture' => $this->culture, - )); - } - - public function loginButton($parameters = array(), $name = null) - { - $name = $name ?: 'FOSFacebookBundle::loginButton.html.php'; - return $this->templating->render($name, $parameters + array( - 'autologoutlink' => 'false', - 'label' => '', - 'scope' => implode(',', $this->scope), - )); - } - - public function logoutUrl($parameters = array(), $name = null) - { - return $this->facebook->getLogoutUrl($parameters); - } - - /** - * @codeCoverageIgnore - */ - public function getName() - { - return 'facebook'; - } + protected $templating; + protected $logging; + protected $culture; + protected $scope; + protected $facebook; + + public function __construct( EngineInterface $templating, \BaseFacebook $facebook, $logging = true, + $culture = 'en_US', array $scope = array( ) ) + { + $this->templating = $templating; + $this->logging = $logging; + $this->culture = $culture; + $this->scope = $scope; + $this->facebook = $facebook; + } + + /** + * Returns the HTML necessary for initializing the JavaScript SDK. + * + * The default template includes the following parameters: + * + * * async + * * fbAsyncInit + * * appId + * * xfbml + * * oauth + * * status + * * cookie + * * logging + * * culture + * + * @param array $parameters An array of parameters for the initialization template + * @param string $name A template name + * + * @return string An HTML string + */ + + public function initialize( $parameters = array( ), $name = null ) + { + $name = $name ? : 'FOSFacebookBundle::initialize.html.php'; + return $this->templating + ->render( $name, + $parameters + + array( 'async' => true, 'fbAsyncInit' => '', 'appId' => ( string ) $this->facebook->getAppId( ), + 'xfbml' => false, 'oauth' => true, 'status' => false, 'cookie' => true, + 'logging' => $this->logging, 'culture' => $this->culture, 'onlycode' => false ) ); + } + + public function loginButton( $parameters = array( ), $name = null ) + { + $name = $name ? : 'FOSFacebookBundle::loginButton.html.php'; + return $this->templating + ->render( $name, + $parameters + + array( 'autologoutlink' => 'false', 'label' => '', 'scope' => implode( ',', $this->scope ), + 'onlycode' => false ) ); + } + + public function scope( $name = null ) + { + $name = $name ? : 'FOSFacebookBundle::scope.html.twig'; + return $this->templating->render( $name, array( 'scope' => implode( ',', $this->scope ) ) ); + } + + public function loginUrl( $redirectUrl, $parameters = array( ) ) + { + $parameters[ "redirect_uri" ] = $redirectUrl . "?facebook=true"; + return $this->facebook->getLoginUrl( $parameters + array( 'scope' => implode( ',', $this->scope ) ) ); + } + + public function loginFunction( $loginCheck, $name = null ) + { + $name = $name ? : 'FOSFacebookBundle::loginFunction.html.twig'; + return $this->templating->render( $name, array( 'loginCheck' => $loginCheck ) ); + } + + public function logoutUrl( $parameters = array( ), $name = null ) + { + return $this->facebook->getLogoutUrl( $parameters ); + } + + /** + * @codeCoverageIgnore + */ + + public function getName( ) + { + return 'facebook'; + } } diff --git a/Tests/DependencyInjection/ConfigurationTest.php b/Tests/DependencyInjection/ConfigurationTest.php deleted file mode 100644 index 2ee2943..0000000 --- a/Tests/DependencyInjection/ConfigurationTest.php +++ /dev/null @@ -1,24 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests\DependencyInjection; - -use Symfony\Component\Config\Definition\ConfigurationInterface; -use FOS\FacebookBundle\DependencyInjection\Configuration; - -class ConfigurationTest extends \PHPUnit_Framework_TestCase -{ - public function testThatCanGetConfigTreeBuilder() - { - $configuration = new Configuration(); - $this->assertInstanceOf('Symfony\Component\Config\Definition\Builder\TreeBuilder', $configuration->getConfigTreeBuilder()); - } -} diff --git a/Tests/DependencyInjection/FOSFacebookExtensionTest.php b/Tests/DependencyInjection/FOSFacebookExtensionTest.php deleted file mode 100644 index 89b1cef..0000000 --- a/Tests/DependencyInjection/FOSFacebookExtensionTest.php +++ /dev/null @@ -1,97 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests\DependencyInjection; - -use FOS\FacebookBundle\DependencyInjection\FOSFacebookExtension; - -class FOSFacebookExtensionTest extends \PHPUnit_Framework_TestCase -{ - /** - * @covers FOS\FacebookBundle\DependencyInjection\FOSFacebookExtension::load - */ - public function testLoadFailure() - { - $container = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ContainerBuilder') - ->disableOriginalConstructor() - ->getMock(); - - $extension = $this->getMockBuilder('FOS\\FacebookBundle\\DependencyInjection\\FOSFacebookExtension') - ->getMock(); - - $extension->load(array(array()), $container); - } - - /** - * @covers FOS\FacebookBundle\DependencyInjection\FOSFacebookExtension::load - */ - public function testLoadSetParameters() - { - $container = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ContainerBuilder') - ->disableOriginalConstructor() - ->getMock(); - - $parameterBag = $this->getMockBuilder('Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag') - ->disableOriginalConstructor() - ->getMock(); - - $parameterBag - ->expects($this->any()) - ->method('add'); - - $container - ->expects($this->any()) - ->method('getParameterBag') - ->will($this->returnValue($parameterBag)); - - $extension = new FOSFacebookExtension(); - $configs = array( - array('class' => array('api' => 'foo')), - array('file' => 'foo'), - array('app_id' => 'foo'), - array('secret' => 'foo'), - array('cookie' => 'foo'), - array('domain' => 'foo'), - array('logging' => 'foo'), - array('culture' => 'foo'), - array('permissions' => array('email')), - ); - $extension->load($configs, $container); - } - - /** - * @covers FOS\FacebookBundle\DependencyInjection\FOSFacebookExtension::load - */ - public function testThatCanSetContainerAlias() - { - $container = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\ContainerBuilder') - ->disableOriginalConstructor() - ->getMock(); - $container->expects($this->once()) - ->method('setAlias') - ->with($this->equalTo('facebook_alias'), $this->equalTo('fos_facebook.api')); - - $configs = array( - array('class' => array('api' => 'foo')), - array('file' => 'foo'), - array('app_id' => 'foo'), - array('secret' => 'foo'), - array('cookie' => 'foo'), - array('domain' => 'foo'), - array('logging' => 'foo'), - array('culture' => 'foo'), - array('permissions' => array('email')), - array('alias' => 'facebook_alias') - ); - $extension = new FOSFacebookExtension(); - $extension->load($configs, $container); - } -} diff --git a/Tests/DependencyInjection/Security/Factory/FacebookFactoryTest.php b/Tests/DependencyInjection/Security/Factory/FacebookFactoryTest.php deleted file mode 100644 index c0c6b5b..0000000 --- a/Tests/DependencyInjection/Security/Factory/FacebookFactoryTest.php +++ /dev/null @@ -1,106 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests\DependencyInjection\Security\Factory; - -use FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory; - -class FacebookFactoryTest extends \PHPUnit_Framework_TestCase -{ - /** - * @var FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory - */ - private $factory = null; - - public function setUp() - { - $this->factory = new FacebookFactory(); - } - - public function testThatCanGetPosition() - { - $this->assertEquals('pre_auth', $this->factory->getPosition()); - } - - public function testThatCanGetKey() - { - $this->assertEquals('fos_facebook', $this->factory->getKey()); - } - - /** - * @covers FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory::createAuthProvider - */ - public function testThatCreateUserAuthProviderWhenDefinedInConfig() - { - $idsArray = $this->facebookFactoryCreate(array('provider' => true, 'remember_me' => false, 'create_user_if_not_exists' => false)); - $this->assertEquals('fos_facebook.auth.l3l0', $idsArray[0]); - } - - /** - * @covers FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory::createAuthProvider - */ - public function testThatCreateUserAuthProviderEvenWhenNotDefinedInConfig() - { - $idsArray = $this->facebookFactoryCreate(array('remember_me' => false)); - $this->assertEquals('fos_facebook.auth.l3l0', $idsArray[0]); - } - - /** - * @covers FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory::createAuthProvider - */ - public function testThatCreateDifferentUserAuthProviderForDifferentFirewalls() - { - $idsArray = $this->facebookFactoryCreate(array('remember_me' => false)); - $this->assertEquals('fos_facebook.auth.l3l0', $idsArray[0]); - - $idsArray = $this->facebookFactoryCreate(array('remember_me' => false), 'main'); - $this->assertEquals('fos_facebook.auth.main', $idsArray[0]); - } - - /** - * @covers FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory::createEntryPoint - */ - public function testThatCreateEntryPoint() - { - $idsArray = $this->facebookFactoryCreate(array('remember_me' => false)); - $this->assertEquals('fos_facebook.security.authentication.entry_point.l3l0', $idsArray[2]); - } - - /** - * @covers FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory::getListenerId - */ - public function testThatListenerForListenerId() - { - $idsArray = $this->facebookFactoryCreate(array('remember_me' => false)); - $this->assertEquals('fos_facebook.security.authentication.listener.l3l0', $idsArray[1]); - } - - /** - * @param array $config - * @return array - */ - private function facebookFactoryCreate($config = array(), $id = 'l3l0') - { - $definition = $this->getMock('Symfony\Component\DependencyInjection\Definition', array('addArgument', 'replaceArgument')); - $definition->expects($this->any()) - ->method('replaceArgument') - ->will($this->returnValue($definition)); - $definition->expects($this->any()) - ->method('addArgument') - ->will($this->returnValue($definition)); - $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder', array('setDefinition')); - $container->expects($this->any()) - ->method('setDefinition') - ->will($this->returnValue($definition)); - - return $this->factory->create($container, $id, $config, 'l3l0.user.provider', null); - } -} diff --git a/Tests/FacebookApiException.php b/Tests/FacebookApiException.php deleted file mode 100644 index 6e8eb88..0000000 --- a/Tests/FacebookApiException.php +++ /dev/null @@ -1,13 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -class FacebookApiException extends \Exception { -} diff --git a/Tests/Kernel.php b/Tests/Kernel.php deleted file mode 100644 index cca89fe..0000000 --- a/Tests/Kernel.php +++ /dev/null @@ -1,71 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests; - -use Symfony\Component\HttpKernel\Kernel as BaseKernel; -use Symfony\Component\Config\Loader\LoaderInterface; -use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\ClassLoader\UniversalClassLoader; - -class Kernel extends BaseKernel -{ - public function __construct() - { - $this->tmpDir = sys_get_temp_dir().'/sf2_'.rand(1, 9999); - if (!is_dir($this->tmpDir)) { - if (false === @mkdir($this->tmpDir)) { - die(sprintf('Unable to create a temporary directory (%s)', $this->tmpDir)); - } - } elseif (!is_writable($this->tmpDir)) { - die(sprintf('Unable to write in a temporary directory (%s)', $this->tmpDir)); - } - - parent::__construct('env', true); - - require_once __DIR__.'/FacebookApiException.php'; - - $loader = new UniversalClassLoader(); - $loader->loadClass('\FacebookApiException'); - $loader->register(); - } - - public function __destruct() - { - $fs = new Filesystem(); - $fs->remove($this->tmpDir); - } - - public function registerRootDir() - { - return $this->tmpDir; - } - - public function registerBundles() - { - return array( - new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(), - ); - } - - public function registerBundleDirs() - { - return array( - ); - } - - public function registerContainerConfiguration(LoaderInterface $loader) - { - $loader->load(function ($container) { - $container->setParameter('kernel.compiled_classes', array()); - }); - } -} diff --git a/Tests/Security/Authentication/Provider/FacebookProviderTest.php b/Tests/Security/Authentication/Provider/FacebookProviderTest.php deleted file mode 100644 index 55c3bea..0000000 --- a/Tests/Security/Authentication/Provider/FacebookProviderTest.php +++ /dev/null @@ -1,230 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests\Security\Authentication\Provider; - -use FOS\FacebookBundle\Security\Authentication\Provider\FacebookProvider; -use Symfony\Component\Security\Core\Exception\AuthenticationException; - -class FacebookProviderTest extends \PHPUnit_Framework_TestCase -{ - /** - * @expectedException \InvalidArgumentException - */ - public function testThatUserCheckerCannotBeNullWhenUserProviderIsNotNull() - { - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->getMock(); - new FacebookProvider('main', $facebookMock, $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface')); - } - - /** - * @covers FOS\FacebookBundle\Security\Authentication\Provider\FacebookProvider::authenticate - */ - public function testThatCannotAuthenticateWhenTokenIsNotFacebookUserToken() - { - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->getMock(); - $facebookProvider = new FacebookProvider('main', $facebookMock); - $this->assertNull($facebookProvider->authenticate($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'))); - } - - /** - * @covers FOS\FacebookBundle\Security\Authentication\Provider\FacebookProvider::authenticate - * @covers FOS\FacebookBundle\Security\Authentication\Provider\FacebookProvider::supports - */ - public function testThatCannotAuthenticateWhenTokenFromOtherFirewall() - { - $providerKeyForProvider = 'main'; - $providerKeyForToken = 'connect'; - - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->getMock(); - $facebookProvider = new FacebookProvider($providerKeyForProvider, $facebookMock); - - $tokenMock = $this->getMock('FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken', array('getProviderKey'), array($providerKeyForToken)); - $tokenMock->expects($this->any()) - ->method('getProviderKey') - ->will($this->returnValue($providerKeyForToken)); - - $this->assertFalse($facebookProvider->supports($tokenMock)); - $this->assertNull($facebookProvider->authenticate($tokenMock)); - } - - /** - * @covers FOS\FacebookBundle\Security\Authentication\Provider\FacebookProvider::authenticate - * @covers FOS\FacebookBundle\Security\Authentication\Provider\FacebookProvider::supports - * @covers FOS\FacebookBundle\Security\Authentication\Provider\FacebookProvider::createAuthenticatedToken - */ - public function testThatCanAuthenticateUserWithoutUserProvider() - { - $providerKey = 'main'; - - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->setMethods(array('getUser')) - ->getMock(); - $facebookMock->expects($this->once()) - ->method('getUser') - ->will($this->returnValue('123')); - - $facebookProvider = new FacebookProvider($providerKey, $facebookMock); - - $tokenMock = $this->getMock('FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken', array('getAttributes', 'getProviderKey'), array($providerKey)); - $tokenMock->expects($this->once()) - ->method('getAttributes') - ->will($this->returnValue(array())); - $tokenMock->expects($this->any()) - ->method('getProviderKey') - ->will($this->returnValue($providerKey)); - - $this->assertTrue($facebookProvider->supports($tokenMock)); - $this->assertEquals('123', $facebookProvider->authenticate($tokenMock)->getUser()); - } - - /** - * @expectedException Symfony\Component\Security\Core\Exception\AuthenticationException - */ - public function testThatCannotAuthenticateWhenUserProviderThrowsAuthenticationException() - { - $providerKey = 'main'; - - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->setMethods(array('getUser')) - ->getMock(); - $facebookMock->expects($this->once()) - ->method('getUser') - ->will($this->returnValue('123')); - - $userProviderMock = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface'); - $userProviderMock->expects($this->once()) - ->method('loadUserByUsername') - ->with('123') - ->will($this->throwException(new AuthenticationException('test'))); - - $userCheckerMock = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); - $tokenMock = $this->getMock('FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken', array('getProviderKey'), array($providerKey)); - $tokenMock->expects($this->any()) - ->method('getProviderKey') - ->will($this->returnValue($providerKey)); - - $facebookProvider = new FacebookProvider($providerKey, $facebookMock, $userProviderMock, $userCheckerMock); - $facebookProvider->authenticate($tokenMock); - } - - /** - * @expectedException Symfony\Component\Security\Core\Exception\AuthenticationException - */ - public function testThatCannotAuthenticateWhenUserProviderDoesNotReturnUsetInterface() - { - $providerKey = 'main'; - - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->setMethods(array('getUser')) - ->getMock(); - $facebookMock->expects($this->once()) - ->method('getUser') - ->will($this->returnValue('123')); - - $userProviderMock = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface'); - $userProviderMock->expects($this->once()) - ->method('loadUserByUsername') - ->with('123') - ->will($this->returnValue('234')); - - $userCheckerMock = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); - $tokenMock = $this->getMock('FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken', array('getProviderKey'), array($providerKey)); - $tokenMock->expects($this->any()) - ->method('getProviderKey') - ->will($this->returnValue($providerKey)); - - $facebookProvider = new FacebookProvider($providerKey, $facebookMock, $userProviderMock, $userCheckerMock); - $facebookProvider->authenticate($tokenMock); - } - - /** - * @expectedException Symfony\Component\Security\Core\Exception\AuthenticationException - */ - public function testThatCannotAuthenticateWhenCannotRetrieveFacebookUserFromSession() - { - $providerKey = 'main'; - - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->setMethods(array('getUser')) - ->getMock(); - $facebookMock->expects($this->once()) - ->method('getUser') - ->will($this->returnValue(false)); - - $userProviderMock = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface'); - $userCheckerMock = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); - - $tokenMock = $this->getMock('FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken', array('getProviderKey'), array($providerKey)); - $tokenMock->expects($this->any()) - ->method('getProviderKey') - ->will($this->returnValue($providerKey)); - - $facebookProvider = new FacebookProvider($providerKey, $facebookMock, $userProviderMock, $userCheckerMock); - $facebookProvider->authenticate($tokenMock); - } - - /** - * @covers FOS\FacebookBundle\Security\Authentication\Provider\FacebookProvider::authenticate - * @covers FOS\FacebookBundle\Security\Authentication\Provider\FacebookProvider::createAuthenticatedToken - */ - public function testThatCanAutenticateUsingUserProvider() - { - $providerKey = 'main'; - - $userMock = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); - $userMock->expects($this->once()) - ->method('getUsername') - ->will($this->returnValue('l3l0')); - $userMock->expects($this->once()) - ->method('getRoles') - ->will($this->returnValue(array())); - - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->setMethods(array('getUser')) - ->getMock(); - $facebookMock->expects($this->once()) - ->method('getUser') - ->will($this->returnValue('123')); - - $userProviderMock = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface'); - $userProviderMock->expects($this->once()) - ->method('loadUserByUsername') - ->with('123') - ->will($this->returnValue($userMock)); - - $userCheckerMock = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); - $userCheckerMock->expects($this->once()) - ->method('checkPostAuth'); - - $tokenMock = $this->getMock('FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken', array('getAttributes', 'getProviderKey'), array($providerKey)); - $tokenMock->expects($this->once()) - ->method('getAttributes') - ->will($this->returnValue(array())); - $tokenMock->expects($this->any()) - ->method('getProviderKey') - ->will($this->returnValue($providerKey)); - - $facebookProvider = new FacebookProvider($providerKey, $facebookMock, $userProviderMock, $userCheckerMock); - $this->assertEquals('l3l0', $facebookProvider->authenticate($tokenMock)->getUsername()); - } -} diff --git a/Tests/Security/Authentication/Token/FacebookUserTokenTest.php b/Tests/Security/Authentication/Token/FacebookUserTokenTest.php deleted file mode 100644 index f01f00c..0000000 --- a/Tests/Security/Authentication/Token/FacebookUserTokenTest.php +++ /dev/null @@ -1,48 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests\Security\Authentication\Token; - -use FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken; - -class FacebookUserTokenTest extends \PHPUnit_Framework_TestCase -{ - /** - * @dataProvider provider - */ - public function testThatAlwaysReturnEmptyCredentials($uid, $roles) - { - $token = new FacebookUserToken('main', $uid, $roles); - - $this->assertEquals('', $token->getCredentials()); - } - - /** - * @return array - */ - public static function provider() - { - return array( - array('', array()), - array('l3l0', array()), - array('', array('role1', 'role2')), - array('l3l0', array('role1', 'role2')) - ); - } - - public function testThatProviderKeyIsNotEmptyAfterDeserialization() - { - $providerKey = 'main'; - $token = unserialize(serialize(new FacebookUserToken($providerKey))); - - $this->assertEquals($providerKey, $token->getProviderKey()); - } -} diff --git a/Tests/Security/EntryPoint/FacebookAuthenticationEntryPointTest.php b/Tests/Security/EntryPoint/FacebookAuthenticationEntryPointTest.php deleted file mode 100644 index 9e6dc69..0000000 --- a/Tests/Security/EntryPoint/FacebookAuthenticationEntryPointTest.php +++ /dev/null @@ -1,72 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests\Security\EntryPoint; - -use FOS\FacebookBundle\Security\EntryPoint\FacebookAuthenticationEntryPoint; - -class FacebookAuthenticationEntryPointTest extends \PHPUnit_Framework_TestCase -{ - /** - * @covers FOS\FacebookBundle\Security\EntryPoint\FacebookAuthenticationEntryPoint::start - */ - public function testThatRedirectResponseWithFacebookLoginUrlIsCreated() - { - $requestMock = $this->getMock('Symfony\Component\HttpFoundation\Request', array('getUriForPath')); - $requestMock->expects($this->once()) - ->method('getUriForPath') - ->with($this->equalTo('/index')) - ->will($this->returnValue('http://localhost/index')); - - $options = array('check_path' => '/index'); - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->setMethods(array('getLoginUrl')) - ->getMock(); - $facebookMock->expects($this->once()) - ->method('getLoginUrl') - ->with($this->equalTo(array( - 'display' => 'page', - 'scope' => 'email,user_website', - 'redirect_uri' => 'http://localhost/index' - ))) - ->will($this->returnValue('http://localhost/facebook-redirect/index')); - - $facebookAuthentication = new FacebookAuthenticationEntryPoint($facebookMock, $options, array('email', 'user_website')); - $response = $facebookAuthentication->start($requestMock); - - $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response, 'RedirectResponse is returned'); - $this->assertEquals($response->headers->get('location'), 'http://localhost/facebook-redirect/index', 'RedirectResponse has defined expected location'); - } - - /** - * @covers FOS\FacebookBundle\Security\EntryPoint\FacebookAuthenticationEntryPoint::start - */ - public function testThatRedirectionToFacebookLoginUrlIsCreated() - { - $requestMock = $this->getMock('Symfony\Component\HttpFoundation\Request', array('getUriForPath')); - - $options = array('check_path' => '/index', 'server_url' => 'http://server.url', 'app_url' => 'http://app.url'); - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->setMethods(array('getLoginUrl')) - ->getMock(); - $facebookMock->expects($this->once()) - ->method('getLoginUrl') - ->will($this->returnValue('http://localhost/facebook-redirect/index')); - - $facebookAuthentication = new FacebookAuthenticationEntryPoint($facebookMock, $options, array()); - $response = $facebookAuthentication->start($requestMock); - - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response, 'Response is returned'); - $this->assertRegExp('/location\.href="http:\/\/localhost\/facebook-redirect\/index/', $response->getContent(), 'Javascript redirection is in response'); - } -} diff --git a/Tests/Security/Firewall/FacebookListenerTest.php b/Tests/Security/Firewall/FacebookListenerTest.php deleted file mode 100644 index cb6cd10..0000000 --- a/Tests/Security/Firewall/FacebookListenerTest.php +++ /dev/null @@ -1,89 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests\Security\Firewall\FacebookListener; - -use FOS\FacebookBundle\Security\Firewall\FacebookListener; - -class FacebookListenerTest extends \PHPUnit_Framework_TestCase -{ - /** - * @covers FOS\FacebookBundle\Security\Firewall\FacebookListener::attemptAuthentication - */ - public function testThatCanAttemptAuthenticationWithFacebook() - { - $listener = new FacebookListener( - $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'), - $this->getAuthenticationManager(), - $this->getMock('Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface'), - $this->getHttpUtils(), - 'providerKey' - ); - $listener->handle($this->getResponseEvent()); - } - - /** - * @return Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface - */ - private function getAuthenticationManager() - { - $authenticationManagerMock = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'); - $authenticationManagerMock->expects($this->once()) - ->method('authenticate') - ->with($this->isInstanceOf('FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken')); - - return $authenticationManagerMock; - } - - /** - * @return Symfony\Component\Security\Http\HttpUtils - */ - private function getHttpUtils() - { - $httpUtils = $this->getMock('Symfony\Component\Security\Http\HttpUtils'); - $httpUtils->expects($this->once()) - ->method('checkRequestPath') - ->will($this->returnValue(true)); - - return $httpUtils; - } - - /** - * @return Symfony\Component\HttpKernel\Event\GetResponseEvent - */ - private function getResponseEvent() - { - $responseEventMock = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array('getRequest'), array(), '', false); - $responseEventMock->expects($this->any()) - ->method('getRequest') - ->will($this->returnValue($this->getRequest())); - - return $responseEventMock; - } - - /** - * @return Symfony\Component\HttpFoundation\Request - */ - private function getRequest() - { - $requestMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request') - ->disableOriginalClone() - ->getMock(); - $requestMock->expects($this->any()) - ->method('hasSession') - ->will($this->returnValue('true')); - $requestMock->expects($this->any()) - ->method('hasPreviousSession') - ->will($this->returnValue('true')); - - return $requestMock; - } -} diff --git a/Tests/Templating/Helper/FacebookHelperTest.php b/Tests/Templating/Helper/FacebookHelperTest.php deleted file mode 100644 index 83b5603..0000000 --- a/Tests/Templating/Helper/FacebookHelperTest.php +++ /dev/null @@ -1,86 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests\Templating\Helper; - -use FOS\FacebookBundle\Templating\Helper\FacebookHelper; - -class FacebookHelperTest extends \PHPUnit_Framework_TestCase -{ - /** - * @covers FOS\FacebookBundle\Templating\Helper\FacebookHelper::initialize - */ - public function testInitialize() - { - $expected = new \stdClass(); - - $templating = $this->getMockBuilder('Symfony\Component\Templating\DelegatingEngine') - ->disableOriginalConstructor() - ->getMock(); - $templating - ->expects($this->once()) - ->method('render') - ->with('FOSFacebookBundle::initialize.html.php', array( - 'appId' => 123, - 'async' => true, - 'cookie' => false, - 'culture' => 'en_US', - 'fbAsyncInit' => '', - 'logging' => true, - 'oauth' => true, - 'status' => false, - 'xfbml' => false, - )) - ->will($this->returnValue($expected)); - - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->setMethods(array('getAppId')) - ->getMock(); - $facebookMock->expects($this->once()) - ->method('getAppId') - ->will($this->returnValue('123')); - - $helper = new FacebookHelper($templating, $facebookMock); - $this->assertSame($expected, $helper->initialize(array('cookie' => false))); - } - - /** - * @covers FOS\FacebookBundle\Templating\Helper\FacebookHelper::loginButton - */ - public function testLoginButton() - { - $expected = new \stdClass(); - - $templating = $this->getMockBuilder('Symfony\Component\Templating\DelegatingEngine') - ->disableOriginalConstructor() - ->getMock(); - $templating - ->expects($this->once()) - ->method('render') - ->with('FOSFacebookBundle::loginButton.html.php', array( - 'autologoutlink' => 'false', - 'label' => 'testLabel', - 'scope' => '1,2,3', - )) - ->will($this->returnValue($expected)); - - $facebookMock = $this->getMockBuilder('FOS\FacebookBundle\Facebook\FacebookSessionPersistence') - ->disableOriginalConstructor() - ->setMethods(array('getAppId')) - ->getMock(); - $facebookMock->expects($this->any()) - ->method('getAppId'); - - $helper = new FacebookHelper($templating, $facebookMock, true, 'en_US', array(1,2,3) ); - $this->assertSame($expected, $helper->loginButton(array('label' => 'testLabel'))); - } -} diff --git a/Tests/Twig/Extension/FacebookExtensionTest.php b/Tests/Twig/Extension/FacebookExtensionTest.php deleted file mode 100644 index 9fe393e..0000000 --- a/Tests/Twig/Extension/FacebookExtensionTest.php +++ /dev/null @@ -1,82 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace FOS\FacebookBundle\Tests\Twig\Extension; - -use FOS\FacebookBundle\Twig\Extension\FacebookExtension; -use FOS\FacebookBundle\Templating\Helper\FacebookHelper; - -class FacebookExtensionTest extends \PHPUnit_Framework_TestCase -{ - /** - * @covers FOS\FacebookBundle\Twig\Extension\FacebookExtension::getName - */ - public function testGetName() - { - $containerMock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); - $extension = new FacebookExtension($containerMock); - $this->assertSame('facebook', $extension->getName()); - } - - /** - * @covers FOS\FacebookBundle\Twig\Extension\FacebookExtension::getFunctions - */ - public function testGetFunctions() - { - $containerMock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); - $extension = new FacebookExtension($containerMock); - $functions = $extension->getFunctions(); - $this->assertInstanceOf('\Twig_Function_Method', $functions['facebook_initialize']); - $this->assertInstanceOf('\Twig_Function_Method', $functions['facebook_login_button']); - } - - /** - * @covers FOS\FacebookBundle\Twig\Extension\FacebookExtension::renderInitialize - */ - public function testRenderInitialize() - { - $helperMock = $this->getMockBuilder('FOS\FacebookBundle\Templating\Helper\FacebookHelper') - ->disableOriginalConstructor() - ->getMock(); - $helperMock->expects($this->once()) - ->method('initialize') - ->will($this->returnValue('returnedValue')); - $containerMock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); - $containerMock->expects($this->once()) - ->method('get') - ->with('fos_facebook.helper') - ->will($this->returnValue($helperMock)); - - $extension = new FacebookExtension($containerMock); - $this->assertSame('returnedValue', $extension->renderInitialize()); - } - - /** - * @covers FOS\FacebookBundle\Twig\Extension\FacebookExtension::renderloginButton - */ - public function testRenderLoginButton() - { - $helperMock = $this->getMockBuilder('FOS\FacebookBundle\Templating\Helper\FacebookHelper') - ->disableOriginalConstructor() - ->getMock(); - $helperMock->expects($this->once()) - ->method('loginButton') - ->will($this->returnValue('returnedValueLogin')); - $containerMock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); - $containerMock->expects($this->once()) - ->method('get') - ->with('fos_facebook.helper') - ->will($this->returnValue($helperMock)); - - $extension = new FacebookExtension($containerMock); - $this->assertSame('returnedValueLogin', $extension->renderLoginButton()); - } -} diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php deleted file mode 100644 index e0640ab..0000000 --- a/Tests/bootstrap.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -$file = __DIR__.'/../vendor/autoload.php'; -if (!file_exists($file)) { - throw new RuntimeException('Install dependencies to run test suite.'); -} - -$autoload = require_once $file; diff --git a/Twig/Extension/FacebookExtension.php b/Twig/Extension/FacebookExtension.php index 7a151dd..2b541b4 100644 --- a/Twig/Extension/FacebookExtension.php +++ b/Twig/Extension/FacebookExtension.php @@ -10,69 +10,110 @@ */ namespace FOS\FacebookBundle\Twig\Extension; - use FOS\FacebookBundle\Templating\Helper\FacebookHelper; use Symfony\Component\DependencyInjection\ContainerInterface; class FacebookExtension extends \Twig_Extension { - protected $container; - - /** - * Constructor. - * - * @param ContainerInterface $container - */ - public function __construct(ContainerInterface $container) - { - $this->container = $container; - } - - /** - * 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_initialize' => new \Twig_Function_Method($this, 'renderInitialize', array('is_safe' => array('html'))), - 'facebook_login_button' => new \Twig_Function_Method($this, 'renderLoginButton', array('is_safe' => array('html'))), - 'facebook_logout_url' => new \Twig_Function_Method($this, 'renderLogoutUrl', array('is_safe' => array('html'))), - ); - } - - /** - * Returns the name of the extension. - * - * @return string The extension name - */ - public function getName() - { - return 'facebook'; - } - - /** - * @see FacebookHelper::initialize() - */ - public function renderInitialize($parameters = array(), $name = null) - { - return $this->container->get('fos_facebook.helper')->initialize($parameters, $name ?: 'FOSFacebookBundle::initialize.html.twig'); - } - - /** - * @see FacebookHelper::loginButton() - */ - public function renderLoginButton($parameters = array(), $name = null) - { - return $this->container->get('fos_facebook.helper')->loginButton($parameters, $name ?: 'FOSFacebookBundle::loginButton.html.twig'); - } - - /** - * @see FacebookHelper::logoutUrl() - */ - public function renderLogoutUrl($parameters = array(), $name = null) - { - return $this->container->get('fos_facebook.helper')->logoutUrl($parameters); - } + protected $container; + + /** + * Constructor. + * + * @param ContainerInterface $container + */ + + public function __construct( ContainerInterface $container ) + { + $this->container = $container; + } + + /** + * 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_initialize' => new \Twig_Function_Method( $this, 'renderInitialize', + array( 'is_safe' => array( 'html' ) )), + 'facebook_login_button' => new \Twig_Function_Method( $this, 'renderLoginButton', + array( 'is_safe' => array( 'html' ) )), + 'facebook_scope' => new \Twig_Function_Method( $this, 'renderScope', array( 'is_safe' => array( 'html' ) )), + 'facebook_login_function' => new \Twig_Function_Method( $this, 'renderLoginFunction', + array( 'is_safe' => array( 'html' ) )), + 'facebook_login_url' => new \Twig_Function_Method( $this, 'renderLoginUrl', + array( 'is_safe' => array( 'html' ) )), + 'facebook_logout_url' => new \Twig_Function_Method( $this, 'renderLogoutUrl', + array( 'is_safe' => array( 'html' ) )), ); + } + + /** + * Returns the name of the extension. + * + * @return string The extension name + */ + + public function getName( ) + { + return 'facebook'; + } + + /** + * @see FacebookHelper::initialize() + */ + + public function renderInitialize( $parameters = array( ), $name = null ) + { + return $this->container->get( 'fos_facebook.helper' ) + ->initialize( $parameters, $name ? : 'FOSFacebookBundle::initialize.html.twig' ); + } + + /** + * @see FacebookHelper::loginButton() + */ + + public function renderLoginButton( $parameters = array( ), $name = null ) + { + return $this->container->get( 'fos_facebook.helper' ) + ->loginButton( $parameters, $name ? : 'FOSFacebookBundle::loginButton.html.twig' ); + } + + /** + * @see FacebookHelper::scope() + */ + + public function renderScope( ) + { + return $this->container->get( 'fos_facebook.helper' )->scope( ); + } + + /** + * @see FacebookHelper::loginFunction() + */ + + public function renderLoginFunction( $loginCheck ) + { + return $this->container->get( 'fos_facebook.helper' )->loginFunction( $loginCheck ); + } + + /** + * @see FacebookHelper::authUrl() + */ + + public function renderLoginUrl( $redirectUtl, $parameters = array( ) ) + { + return $this->container->get( 'fos_facebook.helper' )->loginUrl( $redirectUtl, $parameters ); + } + + /** + * @see FacebookHelper::logoutUrl() + */ + + public function renderLogoutUrl( $parameters = array( ), $name = null ) + { + return $this->container->get( 'fos_facebook.helper' )->logoutUrl( $parameters ); + } } diff --git a/composer.json b/composer.json index d0ebb75..c4fc44a 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,5 @@ { - "name": "friendsofsymfony/facebook-bundle", + "name": "bitgandtter/facebook-bundle", "type": "symfony-bundle", "description": "Integrate the Facebook Platform into your Symfony2 application.", "keywords": ["facebook"], @@ -16,18 +16,15 @@ "homepage": "https://github.com/friendsofsymfony/FOSFacebookBundle/contributors" } ], - "require": { "php": ">=5.3.2", - "symfony/framework-bundle": "2.1.*", - "symfony/security-bundle": "2.1.*", - "symfony/twig-bundle": "2.1.*", - "facebook/php-sdk": "dev-master" + "symfony/framework-bundle": ">=2.1", + "symfony/security-bundle": ">=2.1", + "symfony/twig-bundle": ">=2.1", + "facebook/php-sdk": ">=v3.2.2" }, - "autoload": { "psr-0": { "FOS\\FacebookBundle": "" } }, - "target-dir": "FOS/FacebookBundle" } diff --git a/phpunit.xml.dist b/phpunit.xml.dist deleted file mode 100644 index 526dddb..0000000 --- a/phpunit.xml.dist +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - ./Tests - - - - - - ./ - - ./Resources - ./Tests - ./vendor - - - -