Commit eb8f6a6a authored by Sebastian Castro's avatar Sebastian Castro

Fixs SecurityContext to Security TokenStorage

parent a31f40ce
<?php
namespace Application\Sonata\UserBundle\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
......@@ -9,17 +9,16 @@ use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Security;
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface, LogoutSuccessHandlerInterface
{
private $router;
private $session;
/**
* Constructor
*
......@@ -27,13 +26,13 @@ class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, Au
* @param RouterInterface $router
* @param Session $session
*/
public function __construct( RouterInterface $router, Session $session, SecurityContext $securityContext )
public function __construct( RouterInterface $router, Session $session, $securityToken )
{
$this->router = $router;
$this->session = $session;
$this->securityContext = $securityContext;
$this->securityToken = $securityToken;
}
/**
* onAuthenticationSuccess
*
......@@ -46,40 +45,40 @@ class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, Au
{
// if AJAX login
if ( $request->isXmlHttpRequest() ) {
$user = $this->securityContext->getToken()->getUser();
$user = $this->securityToken->getToken()->getUser();
$redirectionUrl = '';
if ( $this->session->get('_security.main.target_path' ) ) {
$redirectionUrl = $this->session->get( '_security.main.target_path' );
if ( $this->session->get('_security.main.target_path' ) ) {
$redirectionUrl = $this->session->get( '_security.main.target_path' );
}
$array = array( 'success' => true,
$array = array( 'success' => true,
'redirectionUrl' => $redirectionUrl,
'roles' => $user->getRoles(),
'username' => $user->getUsername(),
'roles' => $user->getRoles(),
'username' => $user->getUsername(),
'email' => $user->getEmail()); // data to return via JSON
$response = new Response( json_encode( $array ) );
$response->headers->set( 'Content-Type', 'application/json' );
return $response;
// if form login
// if form login
} else {
if ( $this->session->get('_security.main.target_path' ) ) {
$url = $this->session->get( '_security.main.target_path' );
} else {
$url = $this->router->generate( 'biopen_homepage' );
} // end if
return new RedirectResponse( $url );
}
}
/**
* onAuthenticationFailure
*
......@@ -92,24 +91,24 @@ class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, Au
{
// if AJAX login
if ( $request->isXmlHttpRequest() ) {
$array = array( 'success' => false, 'message' => $exception->getMessage() ); // data to return via JSON
$response = new Response( json_encode( $array ) );
$response->headers->set( 'Content-Type', 'application/json' );
return $response;
// if form login
// if form login
} else {
// set authentication exception to session
$request->getSession()->set(SecurityContextInterface::AUTHENTICATION_ERROR, $exception);
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
return new RedirectResponse( $this->router->generate( 'login_route' ) );
}
}
public function onLogoutSuccess(Request $request)
public function onLogoutSuccess(Request $request)
{
$this->session->remove("userEmail");
return new Response('{"success": true}');
......
......@@ -5,14 +5,13 @@ use Sonata\AdminBundle\Security\Handler\RoleSecurityHandler as RoleSecurityHandl
use Sonata\AdminBundle\Admin\AdminInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
class CustomRoleSecurityHandler implements SecurityHandlerInterface
{
/**
* @var AuthorizationCheckerInterface|SecurityContextInterface
* @var AuthorizationCheckerInterface
*/
protected $authorizationChecker;
......@@ -24,13 +23,13 @@ class CustomRoleSecurityHandler implements SecurityHandlerInterface
/**
* NEXT_MAJOR: Go back to signature class check when bumping requirements to SF 2.6+.
*
* @param AuthorizationCheckerInterface|SecurityContextInterface $authorizationChecker
* @param AuthorizationCheckerInterface $authorizationChecker
* @param array $superAdminRoles
*/
public function __construct($authorizationChecker, array $superAdminRoles)
{
if (!$authorizationChecker instanceof AuthorizationCheckerInterface && !$authorizationChecker instanceof SecurityContextInterface) {
throw new \InvalidArgumentException('Argument 1 should be an instance of Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface or Symfony\Component\Security\Core\SecurityContextInterface');
if (!$authorizationChecker instanceof AuthorizationCheckerInterface) {
throw new \InvalidArgumentException('Argument 1 should be an instance of Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
}
$this->authorizationChecker = $authorizationChecker;
......
......@@ -2,9 +2,9 @@
namespace Biopen\CoreBundle\Services;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\Security\Core\SecurityContext;
class ConfigurationService
use Symfony\Component\Security\Core\Security;
class ConfigurationService
{
protected $em;
protected $securityContext;
......@@ -13,7 +13,7 @@ class ConfigurationService
/**
* Constructor
*/
public function __construct(DocumentManager $documentManager, SecurityContext $securityContext)
public function __construct(DocumentManager $documentManager, $securityContext)
{
$this->em = $documentManager;
$this->securityContext = $securityContext;
......@@ -21,10 +21,10 @@ class ConfigurationService
}
public function isUserAllowed($featureName, $request = null, $email = null)
{
{
if ($email === null && $request !== null) $email = $request->get('userEmail');
$user = $this->securityContext->getToken()->getUser();
$user = $this->securityContext->getToken()->getUser();
if ($user == 'anon.') $user = null;
......
......@@ -123,9 +123,10 @@ class UserInteraction
public function updateUserInformation($securityContext, $email = null, $directModerationWithHash = false)
{
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED'))
$user = $securityContext->getToken() ? $securityContext->getToken()->getUser() : null;
$user = is_object($user) ? $user : null;
if ($user)
{
$user = $securityContext->getToken()->getUser();
$this->setUserEmail($user->getEmail());
$this->setUserRole($user->isAdmin() ? UserRoles::Admin : UserRoles::Loggued);
}
......@@ -144,9 +145,10 @@ class UserInteraction
public function updateResolvedBy($securityContext, $email = null, $directModerationWithHash = false)
{
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED'))
$user = $securityContext->getToken() ? $securityContext->getToken()->getUser() : null;
$user = is_object($user) ? $user : null;
if ($user)
{
$user = $securityContext->getToken()->getUser();
$this->setResolvedBy($user->getEmail());
}
else
......
......@@ -15,7 +15,7 @@ services:
biopen.element_pending_service:
class: Biopen\GeoDirectoryBundle\Services\ElementPendingService
arguments: [ "@doctrine.odm.mongoDB.document_manager", "@security.token_storage", "@biopen.mail_service", "@biopen.user_interaction_service" ]
arguments: [ "@doctrine.odm.mongoDB.document_manager", "@biopen.mail_service", "@biopen.user_interaction_service" ]
biopen.element_form_service:
class: Biopen\GeoDirectoryBundle\Services\ElementFormService
......
......@@ -9,43 +9,43 @@
* @license MIT License
* @Last Modified time: 2018-06-17 19:57:54
*/
namespace Biopen\GeoDirectoryBundle\Services;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Security;
use Biopen\GeoDirectoryBundle\Document\ElementStatus;
use Biopen\GeoDirectoryBundle\Document\ModerationState;
use Biopen\GeoDirectoryBundle\Document\UserInteractionContribution;
use Biopen\GeoDirectoryBundle\Services\ElementPendingService;
use Biopen\GeoDirectoryBundle\Services\ValidationType;
use Biopen\CoreBundle\Services\MailService;
use Biopen\CoreBundle\Services\MailService;
use Biopen\GeoDirectoryBundle\Services\UserInteractionService;
// strange bug importing this class does not work, so redeclare it here
abstract class InteractType
{
const Deleted = -1;
const Deleted = -1;
const Add = 0;
const Edit = 1;
const Vote = 2;
const Vote = 2;
const Report = 3;
const Import = 4;
const Restored = 5;
const ModerationResolved = 6;
const Import = 4;
const Restored = 5;
const ModerationResolved = 6;
}
/**
* Service used to handle to resolution of pending Elements
**/
class ElementActionService
{
{
protected $preventAddingContribution = false;
/**
* Constructor
*/
public function __construct(DocumentManager $documentManager, SecurityContext $securityContext, MailService $mailService, ElementPendingService $elementPendingService, UserInteractionService $interactionService)
public function __construct(DocumentManager $documentManager, $securityContext, MailService $mailService, ElementPendingService $elementPendingService, UserInteractionService $interactionService)
{
$this->em = $documentManager;
$this->securityContext = $securityContext;
......@@ -57,7 +57,7 @@ class ElementActionService
public function add($element, $sendMail = true, $message = null)
{
$this->addContribution($element, $message, InteractType::Add, ElementStatus::AddedByAdmin);
$element->setStatus(ElementStatus::AddedByAdmin);
$element->setStatus(ElementStatus::AddedByAdmin);
if($sendMail) $this->mailService->sendAutomatedMail('add', $element, $message);
$element->updateTimestamp();
}
......@@ -74,8 +74,8 @@ class ElementActionService
$status = $modifiedByOwner ? ElementStatus::ModifiedByOwner : ElementStatus::ModifiedByAdmin;
$status = $directModerationWithHash ? ElementStatus::ModifiedFromHash : $status;
$this->addContribution($element, $message, InteractType::Edit, $status, $directModerationWithHash);
$element->setStatus($status);
if (!$modifiedByOwner) $this->resolveReports($element, $message);
$element->setStatus($status);
if (!$modifiedByOwner) $this->resolveReports($element, $message);
$element->updateTimestamp();
}
......@@ -95,17 +95,17 @@ class ElementActionService
{
$this->elementPendingService->resolve($element, $isAccepted, $validationType, $message);
$element->updateTimestamp();
}
}
public function delete($element, $sendMail = true, $message = null)
{
if($sendMail) $this->mailService->sendAutomatedMail('delete', $element, $message);
// do not add contribution for elements already deleted
if ($element->isVisible()) $this->addContribution($element, $message, InteractType::Deleted, ElementStatus::Deleted);
$newStatus = $element->isPotentialDuplicate() ? ElementStatus::Duplicate : ElementStatus::Deleted;
$element->setStatus($newStatus);
$this->resolveReports($element, $message);
$element->setStatus($newStatus);
$this->resolveReports($element, $message);
$element->updateTimestamp();
}
......@@ -119,10 +119,10 @@ class ElementActionService
}
public function resolveReports($element, $message = '', $addContribution = false)
{
{
$reports = $element->getUnresolvedReports();
if (count($reports) > 0)
foreach ($reports as $key => $report)
foreach ($reports as $key => $report)
{
$report->setResolvedMessage($message);
$report->updateResolvedBy($this->securityContext);
......@@ -133,7 +133,7 @@ class ElementActionService
$this->addContribution($element, $message, InteractType::ModerationResolved, $element->getStatus());
// Dealing with potential duplicates
if ($element->getModerationState() == ModerationState::PotentialDuplicate)
if ($element->getModerationState() == ModerationState::PotentialDuplicate)
{
if ($element->getIsDuplicateNode()) {
$element->setIsDuplicateNode(false);
......@@ -143,12 +143,12 @@ class ElementActionService
foreach ($potentialOwners as $key => $owner) {
$this->em->persist($owner);
$owner->removePotentialDuplicate($element);
}
}
}
}
}
}
$element->updateTimestamp();
$element->setModerationState(ModerationState::NotNeeded);
$element->setModerationState(ModerationState::NotNeeded);
}
public function setPreventAddingContribution($bool)
......@@ -162,7 +162,7 @@ class ElementActionService
if ($this->preventAddingContribution) return;
// clear contributions with same type that have not been dispatched yet
if ($element->getContributions())
foreach ($element->getContributions() as $contribution) {
foreach ($element->getContributions() as $contribution) {
if ($contribution->getType() == $interactType && $contribution->getWebhookPosts()) $contribution->clearWebhookPosts();
}
$contribution = $this->interactionService->createContribution($message, $interactType, $status, $directModerationWithHash);
......
......@@ -14,7 +14,7 @@
namespace Biopen\GeoDirectoryBundle\Services;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Security;
use Biopen\GeoDirectoryBundle\Document\ElementStatus;
use Biopen\GeoDirectoryBundle\Document\UserInteractionContribution;
use Biopen\CoreBundle\Services\MailService;
......@@ -34,10 +34,9 @@ class ElementPendingService
/**
* Constructor
*/
public function __construct(DocumentManager $documentManager, SecurityContext $securityContext, MailService $mailService, UserInteractionService $interactionService)
public function __construct(DocumentManager $documentManager, MailService $mailService, UserInteractionService $interactionService)
{
$this->em = $documentManager;
$this->securityContext = $securityContext;
$this->mailService = $mailService;
$this->interactionService = $interactionService;
}
......
......@@ -18,7 +18,7 @@ use Biopen\GeoDirectoryBundle\Document\ElementStatus;
use Biopen\GeoDirectoryBundle\Document\ModerationState;
use Biopen\GeoDirectoryBundle\Document\UserInteractionVote;
use Biopen\GeoDirectoryBundle\Document\VoteValue;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Security;
use Biopen\CoreBundle\Services\ConfigurationService;
use Biopen\GeoDirectoryBundle\Services\ElementPendingService;
use Biopen\GeoDirectoryBundle\Services\ValidationType;
......@@ -28,7 +28,7 @@ class ElementVoteService
/**
* Constructor
*/
public function __construct(DocumentManager $documentManager, SecurityContext $securityContext, ConfigurationService $confService, ElementPendingService $elementPendingService)
public function __construct(DocumentManager $documentManager, $securityContext, ConfigurationService $confService, ElementPendingService $elementPendingService)
{
$this->em = $documentManager;
$this->user = $securityContext->getToken() ? $securityContext->getToken()->getUser() : null;
......
......@@ -3,12 +3,12 @@
namespace Biopen\GeoDirectoryBundle\Services;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class GoGoCartoJsService
{
public function __construct(DocumentManager $documentManager, SecurityContext $securityContext, $router, $session, $base_protocol)
public function __construct(DocumentManager $documentManager, $securityContext, $router, $session, $base_protocol)
{
$this->odm = $documentManager;
$this->securityContext = $securityContext;
......@@ -28,17 +28,17 @@ class GoGoCartoJsService
$config = $this->odm->getRepository('BiopenCoreBundle:Configuration')->findConfiguration();
$user = $this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') ? $this->securityContext->getToken()->getUser() : null;
$user = $this->securityContext->getToken() ? $this->securityContext->getToken()->getUser() : null;
$roles = $user ? $user->getRoles() : [];
$userGogocartoRole = $user && $user->isAdmin() ? 'admin' : (in_array('ROLE_USER', $roles) ? 'user' : 'anonymous');
$roles = is_object($user) ? $user->getRoles() : [];
$userGogocartoRole = is_object($user) && $user->isAdmin() ? 'admin' : (in_array('ROLE_USER', $roles) ? 'user' : 'anonymous');
$userGogocartoRole = [$userGogocartoRole];
$userEmail = $user ? $user->getEmail() : $this->session->get('userEmail');
$userEmail = is_object($user) ? $user->getEmail() : $this->session->get('userEmail');
$allowedStamps = [];
if ($config->getStampFeature()->getActive())
{
$allowedStamps = $user ? $user->getAllowedStamps()->toArray() : [];
$allowedStamps = is_object($user) ? $user->getAllowedStamps()->toArray() : [];
foreach ($allowedStamps as $stamp) {
$result = $elementsRep->findStampedWithId($stamp->getId());
$elementIds = [];
......
......@@ -3,7 +3,7 @@
namespace Biopen\GeoDirectoryBundle\Services;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Security;
use Biopen\GeoDirectoryBundle\Document\Webhook;
use Biopen\GeoDirectoryBundle\Document\WebhookPost;
use Biopen\GeoDirectoryBundle\Document\UserInteractionContribution;
......@@ -19,7 +19,7 @@ class UserInteractionService
/**
* Constructor
*/
public function __construct(DocumentManager $documentManager, SecurityContext $securityContext)
public function __construct(DocumentManager $documentManager, $securityContext)
{
$this->em = $documentManager;
$this->securityContext = $securityContext;
......
......@@ -19,7 +19,7 @@ use http\Exception\InvalidArgumentException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Security;
use Biopen\GeoDirectoryBundle\Document\UserInteractionContribution;
class WebhookService
......@@ -28,7 +28,7 @@ class WebhookService
protected $router;
public function __construct(DocumentManager $documentManager, Router $router, SecurityContext $securityContext, $baseUrl, $basePath)
public function __construct(DocumentManager $documentManager, Router $router, $securityContext, $baseUrl, $basePath)
{
$this->em = $documentManager;
$this->router = $router;
......@@ -44,7 +44,7 @@ class WebhookService
{
$contributions = $this->em->createQueryBuilder(UserInteractionContribution::class)
->field('status')->exists(true)
->field('webhookPosts.nextAttemptAt')->lte(new \DateTime())
->field('webhookPosts.nextAttemptAt')->lte(new \DateTime())
->limit($limit)
->getQuery()->execute();
......@@ -55,27 +55,27 @@ class WebhookService
$postsToProceed = [];
// PREPARE EACH POST (calculate data, url...)
foreach ($contributions as $contribution)
{
foreach ($contributions as $contribution)
{
$data = $this->calculateData($contribution);
foreach($contribution->getWebhookPosts() as $webhookPost)
foreach($contribution->getWebhookPosts() as $webhookPost)
{
if (!$webhookPost->getStatus())
if (!$webhookPost->getStatus())
{
$webhook = $webhookPost->getWebhook();
$webhookPost->setUrl($webhook->getUrl());
$webhookPost->setUrl($webhook->getUrl());
$jsonData = json_encode($this->formatData($webhook->getFormat(), $data));
$webhookPost->setData($jsonData);
$postsToProceed[] = $webhookPost;
$contributionsToProceed[] = $contribution;
}
}
}
}
}
}
// CREATE POST REQUESTS
$requests = function() use($client, $postsToProceed) {
foreach($postsToProceed as $post) yield new \GuzzleHttp\Psr7\Request('POST', $post->getUrl() , [], $post->getData() );
};
};
// SEND REQUEST CONCURRENTLY AND HANDLE RESULTS
$pool = new Pool($client, $requests(), [
......@@ -89,15 +89,15 @@ class WebhookService
$post = $postsToProceed[$index];
$attemps = $post->incrementNumAttempts();
if ($attemps < 6) {
// After first try, wait 5m, 25m, 2h, 10h, 2d
$intervalInMinutes = pow(5, $attemps);
$interval = new \DateInterval("PT{$intervalInMinutes}M");
// After first try, wait 5m, 25m, 2h, 10h, 2d
$intervalInMinutes = pow(5, $attemps);
$interval = new \DateInterval("PT{$intervalInMinutes}M");
$now = new \DateTime();
$post->setNextAttemptAt($now->add($interval));
} else {
} else {
$post->setStatus('failed');
$post->setNextAttemptAt(new \DateTime('3000-01-01'));
}
}
},
]);
......@@ -114,7 +114,7 @@ class WebhookService
private function calculateData($contribution)
{
// STANDRD CONTIRBUTION
if ($contribution->getElement())
if ($contribution->getElement())
{
$element = $contribution->getElement();
$this->em->refresh($element);
......@@ -129,7 +129,7 @@ class WebhookService
$data = ['ids' => $contribution->getElementIds()];
}
$mappingType = [InteractionType::Deleted => 'delete', InteractionType::Add => 'add', InteractionType::Edit => 'edit',
$mappingType = [InteractionType::Deleted => 'delete', InteractionType::Add => 'add', InteractionType::Edit => 'edit',
InteractionType::Import => 'add', InteractionType::Restored => 'add'];
$result = [
'action' => $mappingType[$contribution->getType()],
......@@ -169,7 +169,7 @@ class WebhookService
}
private function getBotIcon()
{
{
/** @var ConfImage $img */
$img = $this->config->getFavicon() ? $this->config->getFavicon() : $this->config->getLogo();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment