Skip to content

Instantly share code, notes, and snippets.

@developerdino
Forked from danvbe/1-Explanations.md
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developerdino/186f8b17e68dd9e4e404 to your computer and use it in GitHub Desktop.
Save developerdino/186f8b17e68dd9e4e404 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;
}
}
<?php
namespace danvbe\UserBundle\Security\Handler;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface
{
/**
* @var Router $router
*/
protected $router;
/**
* @param Router $router
*/
function __construct(Router $router)
{
$this->router = $router;
}
/**
* This is called when an interactive authentication attempt succeeds. This
* is called by authentication listeners inheriting from
* AbstractAuthenticationListener.
*
* @param Request $request
* @param TokenInterface $token
*
* @return Response never null
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
// check if this is the first time the user has connected
// and redirect to the profile page to continue filling in
// their profile data
if ($token->getUser()->isNewUser()) {
// redirect to profile for newly created user so they can continue
// registration process
$uri = $this->router->generate('profile');
} else {
$uri = $request->headers->get('referer');
}
return new RedirectResponse($uri);
}
#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
success_handler: security.authentication.success_handler.main.oauth
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}]
security.authentication.success_handler.main.oauth:
class: danvbe\UserBundle\Security\Handler\LoginSuccessHandler
arguments: [@router]
<?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