Skip to content

Commit

Permalink
Add strict user converter
Browse files Browse the repository at this point in the history
  • Loading branch information
stefk committed Nov 10, 2015
1 parent 3fd417f commit 95174bf
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Converter/AuthenticatedUserConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function __construct(TokenStorageInterface $tokenStorage, TranslatorInter
* @{inheritDoc}
*
* @throws InvalidConfigurationException if the parameter name is missing
* @throws AccessDeniedHttpException if the current user is not authenticated
* @throws AccessDeniedException if the current request is anonymous
*/
public function apply(Request $request, ParamConverter $configuration)
{
Expand Down
69 changes: 69 additions & 0 deletions Converter/CurrentUserConverter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

/*
* This file is part of the Claroline Connect package.
*
* (c) Claroline Consortium <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Claroline\CoreBundle\Converter;

use Claroline\CoreBundle\Entity\User;
use JMS\DiExtraBundle\Annotation as DI;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

/**
* @DI\Service
* @DI\Tag("request.param_converter", attributes={"converter"="current_user"})
*/
class CurrentUserConverter implements ParamConverterInterface
{
private $tokenStorage;

/**
* @DI\InjectParams({"tokenStorage" = @DI\Inject("security.token_storage")})
*
* @param TokenStorageInterface $tokenStorage
*/
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}

/**
* {@inheritDoc}
*
* @throws InvalidConfigurationException if the parameter name is missing
* @throws AccessDeniedHttpException if the current request is anonymous
*/
public function apply(Request $request, ParamConverter $configuration)
{
if (null === $parameter = $configuration->getName()) {
throw new InvalidConfigurationException(InvalidConfigurationException::MISSING_NAME);
}

if (($user = $this->tokenStorage->getToken()->getUser()) instanceof User) {
$request->attributes->set($parameter, $user);

return true;
}

throw new AccessDeniedHttpException();
}

/**
* {@inheritDoc}
*/
public function supports(ParamConverter $configuration)
{
return $configuration->getConverter() === 'current_user';
}
}

0 comments on commit 95174bf

Please sign in to comment.