Skip to content

Instantly share code, notes, and snippets.

@Jolg42
Forked from danvbe/1-Explanations.md
Created March 18, 2014 14:37
Show Gist options
  • Save Jolg42/9621320 to your computer and use it in GitHub Desktop.
Save Jolg42/9621320 to your computer and use it in GitHub Desktop.

I have managed to install this… and make it work. I implemented it for Facebook and Google, but you can extend it. My solution it is mostly as described in #116, with a bit of more code presented. The key aspects that lack in the #116 presentation (IMO) are:

  • the registration as service of your custom FOSUBUserProvider (with the necessary parameters)
  • set the service for oauth_user_provider in the security.yml with your custom created service

Here are the steps:

  1. Routing. In routing.yml I have added all the routes for both bundles.
  2. Configuration. I have set the config.yml mostly as it is presented in the HWIOAuthBundle.
  3. Security. I have set the security.yml mostly as it is presented in the HWIOAuthBundle (though my routes are using /login pattern, not /connect). Also, the oauth_user_provider is set for my custom service.
  4. User. My own User entity, extended from FosUser.
  5. UserProvider. My user provider, registered as service, extended from FOSUBUserProvider. This is the one that actually does the User registration in YOUR database with data from PROVIDERS (Facebook, Google, etc.) and in responsible for connecting already logged in users with accounts from PROVIDERS. It does this by overvriting 2 functions (connect(UserInterface $user, UserResponseInterface $response) and loadUserByOAuthUserResponse(UserResponseInterface $response)). See code below.
  6. Custom service. My user provider is registered as service.

Using this code, when:

  1. No user is authenticated on my site: by accessing http://my_app_web_root/login/facebook or http://my_app_web_root/login/google, a user is created in my database (with data as it is saved in the custom FOSUBUserProvider) and it is automatically login-ed to my site.
  2. A user is authenticated on my site: by accessing http://my_app_web_root/login/facebook or http://my_app_web_root/login/google, the current user is updated with data from the provider (account linking).

I think this is the behavior everybody was expecting :).

#app/config/config.yml
hwi_oauth:
#this is my custom user provider, created from FOSUBUserProvider - will manage the
#automatic user registration on your site, with data from the provider (facebook. google, etc.)
#and also, the connecting part (get the token and the user_id)
connect:
account_connector: my_user_provider
# name of the firewall in which this bundle is active, this setting MUST be set
firewall_name: main
fosub:
username_iterations: 30
properties:
# these properties will be used/redefined later in the custom FOSUBUserProvider service.
facebook: facebook_id
google: google_id
resource_owners:
facebook:
type: facebook
client_id: "%facebook_app_id%"
client_secret: "%facebook_app_secret%"
scope: ""
google:
type: google
client_id: "%google_app_id%"
client_secret: "%google_app_secret%"
scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
# here you will add one (or more) configurations for resource owners
<?php
namespace danvbe\UserBundle\Security\Core\User;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
use Symfony\Component\Security\Core\User\UserInterface;
class FOSUBUserProvider extends BaseClass
{
/**
* {@inheritDoc}
*/
public function connect(UserInterface $user, UserResponseInterface $response)
{
$property = $this->getProperty($response);
$username = $response->getUsername();
//on connect - get the access token and the user ID
$service = $response->getResourceOwner()->getName();
$setter = 'set'.ucfirst($service);
$setter_id = $setter.'Id';
$setter_token = $setter.'AccessToken';
//we "disconnect" previously connected users
if (null !== $previousUser = $this->userManager->findUserBy(array($property => $username))) {
$previousUser->$setter_id(null);
$previousUser->$setter_token(null);
$this->userManager->updateUser($previousUser);
}
//we connect current user
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
$this->userManager->updateUser($user);
}
/**
* {@inheritdoc}
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$username = $response->getUsername();
$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username));
//when the user is registrating
if (null === $user) {
$service = $response->getResourceOwner()->getName();
$setter = 'set'.ucfirst($service);
$setter_id = $setter.'Id';
$setter_token = $setter.'AccessToken';
// create new user here
$user = $this->userManager->createUser();
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
//I have set all requested data with the user's username
//modify here with relevant data
$user->setUsername($username);
$user->setEmail($username);
$user->setPassword($username);
$user->setEnabled(true);
$this->userManager->updateUser($user);
return $user;
}
//if user exists - go with the HWIOAuth way
$user = parent::loadUserByOAuthUserResponse($response);
$serviceName = $response->getResourceOwner()->getName();
$setter = 'set' . ucfirst($serviceName) . 'AccessToken';
//update access token
$user->$setter($response->getAccessToken());
return $user;
}
}
#app/config/routing.yml
#FosUserBundle Routes
fos_user_security:
resource: "@FOSUserBundle/Resources/config/routing/security.xml"
fos_user_profile:
resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
prefix: /profile
fos_user_register:
resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
prefix: /register
fos_user_resetting:
resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
prefix: /resetting
fos_user_change_password:
resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
prefix: /profile
#HWIOAuthBundle routes
hwi_oauth_security:
resource: "@HWIOAuthBundle/Resources/config/routing/login.xml"
prefix: /login
hwi_oauth_connect:
resource: "@HWIOAuthBundle/Resources/config/routing/connect.xml"
prefix: /login
hwi_oauth_redirect:
resource: "@HWIOAuthBundle/Resources/config/routing/redirect.xml"
prefix: /login
facebook_login:
pattern: /login/check-facebook
google_login:
pattern: /login/check-google
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_USER
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
login_path: /login
check_path: /login_check
oauth:
resource_owners:
facebook: "/login/check-facebook"
google: "/login/check-google"
login_path: /login
failure_path: /login
oauth_user_provider:
#this is my custom user provider, created from FOSUBUserProvider - will manage the
#automatic user registration on your site, with data from the provider (facebook. google, etc.)
service: my_user_provider
logout: true
anonymous: true
login:
pattern: ^/login$
security: false
remember_me:
key: "%secret%"
lifetime: 31536000 # 365 days in seconds
path: /
domain: ~ # Defaults to the current domain from $_SERVER
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
#danvbe/UserBundle/Resources/services.yml
parameters:
my_user_provider.class: danvbe\UserBundle\Security\Core\User\FOSUBUserProvider
services:
my_user_provider:
class: "%my_user_provider.class%"
#this is the place where the properties are passed to the UserProvider - see config.yml
arguments: [@fos_user.user_manager,{facebook: facebook_id, google: google_id}]
<?php
namespace danvbe\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity(repositoryClass="danvbe\UserBundle\Repository\UserRepository")
* @ORM\Table(name="lcl_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/** @ORM\Column(name="facebook_id", type="string", length=255, nullable=true) */
protected $facebook_id;
/** @ORM\Column(name="facebook_access_token", type="string", length=255, nullable=true) */
protected $facebook_access_token;
/** @ORM\Column(name="google_id", type="string", length=255, nullable=true) */
protected $google_id;
/** @ORM\Column(name="google_access_token", type="string", length=255, nullable=true) */
protected $google_access_token;
//YOU CAN ADD MORE CODE HERE !
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment