Created
January 10, 2012 13:36
-
-
Save havvg/1589120 to your computer and use it in GitHub Desktop.
Impersonating a User in Symfony2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\DemoBundle\Controller; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\HttpFoundation\Response; | |
use Symfony\Component\Security\Core\Role\SwitchUserRole; | |
use FOS\UserBundle\Propel\UserQuery; | |
class DemoController extends Controller | |
{ | |
public function yourAction(Request $request) | |
{ | |
$parameters = array(); | |
// plenty of stuff to do? | |
$security = $this->get('security.context'); | |
if ($security->isGranted('ROLE_ALLOWED_TO_SWITCH') or $security->isGranted('ROLE_PREVIOUS_ADMIN')) { | |
$parameters['users'] = UserQuery::create()->find(); | |
$parameters['original_user'] = $this->get('security.context')->getToken(); | |
foreach ($security->getToken()->getRoles() as $role) { | |
if ($role instanceof SwitchUserRole) { | |
$parameters['original_user'] = $role->getSource(); | |
break; | |
} | |
} | |
} | |
return $this->render('AcmeDemoBundle:Demo:yourAction.html.twig', $parameters); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- twitter bootstrap snippet --> | |
<p class="pull-right">Logged in as <span>{{ app.security.token.username }}</span></p> | |
{% if users is defined %} | |
<ul class="nav secondary-nav"> | |
<li class="dropdown" data-dropdown="dropdown"> | |
<a href="#" class="dropdown-toggle">Switch User</a> | |
<ul class="dropdown-menu"> | |
{% for user in users %} | |
{% if user.username != original_user.username %} | |
<li><a href="?_switch_user={{ user.username }}">{{ user.username }}</a></li> | |
{% endif %} | |
{% endfor %} | |
<li class="divider"></li> | |
<li><a href="?_switch_user=_exit">{{ original_user.username }}</a></li> | |
</ul> | |
</li> | |
</ul> | |
{% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment