本文整理汇总了PHP中Symfony\Component\Security\Core\SecurityContext类的典型用法代码示例。如果您正苦于以下问题:PHP SecurityContext类的具体用法?PHP SecurityContext怎么用?PHP SecurityContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SecurityContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
public function __construct(AkismetInterface $akismet, SecurityContext $securityContext)
{
$this->akismet = $akismet;
// On détermine si l'utilisateur courant est identifié
// Si c'est le cas, on n'utilisera pas akismet
$this->isAuthenticated = $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED');
}
示例2: __construct
/**
* @param EntityManager $manager
* @param SecurityContext $context
* @param GlobalAccessorObject $globalAccessorObject
* @param Stopwatch $stopwatch
*/
public function __construct(EntityManager $manager, SecurityContext $context, GlobalAccessorObject $globalAccessorObject, Stopwatch $stopwatch = null)
{
$this->manager = $manager;
$this->user = $context->getToken()->getUser();
$this->globalAccessorObject = $globalAccessorObject;
$this->stopwatch = $stopwatch;
}
示例3: let
public function let(ArticleService $articleService, AuthorService $authorService, CacheService $cacheService, Container $container, ArticleRepository $articleRepository, LanguageRepository $languageRepository, ArticleTypeRepository $articleTypeRepository, PublicationRepository $publicationRepository, IssueRepository $issueRepository, SectionRepository $sectionRepository, AuthorTypeRepository $authorTypeRepository, EntityManager $entityManager, Request $request, FormFactory $formFactory, FormBuilder $formBuilder, Form $form, FormView $formView, User $user, UserService $userService, Article $article, Publication $publication, ArticleType $articleType, Issue $issue, Section $section, Language $language, Author $author, AuthorType $authorType, AbstractQuery $query, SecurityContext $security, TokenInterface $token, Router $router)
{
$container->get('em')->willReturn($entityManager);
$container->get('request')->willReturn($request);
$container->get('user')->willReturn($userService);
$container->get('form.factory')->willReturn($formFactory);
$container->get('newscoop_newscoop.article_service')->willReturn($articleService);
$container->get('author')->willReturn($authorService);
$container->get('newscoop.cache')->willReturn($cacheService);
$container->get('router')->willReturn($router);
$formBuilder->getForm(Argument::cetera())->willReturn($form);
$formFactory->create(Argument::cetera())->willReturn($form);
$form->createView()->willReturn($formView);
$form->handleRequest(Argument::cetera())->willReturn(true);
$form->isValid()->willReturn(true);
$security->getToken()->willReturn($token);
$container->get('security.context')->willReturn($security);
$container->has('security.context')->willReturn(true);
$this->setContainer($container);
$entityManager->getRepository('Newscoop\\Entity\\Article')->willReturn($articleRepository);
$entityManager->getRepository('Newscoop\\Entity\\Language')->willReturn($languageRepository);
$entityManager->getRepository('Newscoop\\Entity\\ArticleType')->willReturn($articleTypeRepository);
$entityManager->getRepository('Newscoop\\Entity\\Publication')->willReturn($publicationRepository);
$entityManager->getRepository('Newscoop\\Entity\\Issue')->willReturn($issueRepository);
$entityManager->getRepository('Newscoop\\Entity\\Section')->willReturn($sectionRepository);
$entityManager->getRepository('Newscoop\\Entity\\AuthorType')->willReturn($authorTypeRepository);
$articleRepository->getArticle(Argument::cetera())->willReturn($query);
$entityManager->flush(Argument::any())->willReturn(true);
$userService->getCurrentUser()->willReturn($user);
$number = 64;
$language = "en";
}
示例4: __construct
public function __construct(EntityManager $em, SecurityContext $securityContext, ServerManager $serverManager, Translator $translator)
{
$this->em = $em;
$this->user = $securityContext->getToken()->getUser();
$this->serverManager = $serverManager;
$this->translator = $translator;
}
示例5: testGetSetToken
public function testGetSetToken()
{
$context = new SecurityContext($this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\AuthenticationManagerInterface'), $this->getMock('Symfony\\Component\\Security\\Core\\Authorization\\AccessDecisionManagerInterface'));
$this->assertNull($context->getToken());
$context->setToken($token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface'));
$this->assertSame($token, $context->getToken());
}
示例6: __construct
/**
* @param EntityManager $entityManager
* @param TranslatorInterface $translator
* @param SecurityContext $securityContext
* @param ServiceLink $securityFacadeLink
* @param EmailManager $emailManager
*/
public function __construct(EntityManager $entityManager, TranslatorInterface $translator, SecurityContext $securityContext, ServiceLink $securityFacadeLink, EmailManager $emailManager)
{
$this->entityManager = $entityManager;
$this->translator = $translator;
$this->securityContext = $securityContext;
$this->user = $this->securityContext->getToken()->getUser();
$this->securityFacade = $securityFacadeLink->getService();
$this->emailManager = $emailManager;
}
示例7: createSecurityContext
protected function createSecurityContext($granted = false)
{
$authManager = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\AuthenticationManagerInterface');
$decisionManager = $this->getMock('Symfony\\Component\\Security\\Core\\Authorization\\AccessDecisionManagerInterface');
$decisionManager->expects($this->any())->method('decide')->will($this->returnValue($granted));
$context = new SecurityContext($authManager, $decisionManager, false);
$context->setToken($token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface'));
$token->expects($this->any())->method('isAuthenticated')->will($this->returnValue(true));
return $context;
}
示例8: onFilterController
public function onFilterController(FilterControllerEvent $event)
{
list($object, $method) = $event->getController();
// the controller could be a proxy
$className = ClassUtils::getClass($object);
$reflectionClass = new \ReflectionClass($className);
$reflectionMethod = $reflectionClass->getMethod($method);
$allControllerAnnotations = $this->annotationReader->getClassAnnotations($reflectionClass);
$allMethodAnnotations = $this->annotationReader->getMethodAnnotations($reflectionMethod);
$guardAnnotationsFilter = function ($annotation) {
return $annotation instanceof Guard;
};
$controllerGuardAnnotations = array_filter($allControllerAnnotations, $guardAnnotationsFilter);
$methodGuardAnnotations = array_filter($allMethodAnnotations, $guardAnnotationsFilter);
$guardAnnotations = array_merge($controllerGuardAnnotations, $methodGuardAnnotations);
$permissions = [];
foreach ($guardAnnotations as $guardAnnotation) {
$value = $guardAnnotation->value;
if (!is_array($value)) {
$value = [$value];
}
$permissions = array_merge($value, $permissions);
}
$permissions = array_unique($permissions);
if (!empty($permissions) && !$this->security->isGranted($permissions)) {
$e = new PermissionRequiredException();
$e->setRequiredPermissions($permissions)->setCurrentPermissions($this->security->getToken()->getUser()->getPermissions());
throw $e;
}
}
示例9: avoidIncorrectVoting
/**
* Listener for comments' votes persistence to avoid voting for own comments
* and multiple voting for comments
*
* @param VotePersistEvent $event
* @return void
*/
public function avoidIncorrectVoting(VotePersistEvent $event)
{
try {
if (!$this->context->isGranted(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED)) {
throw new \Exception('Avoid voting if user is not authenticated');
}
/** @var $vote SignedVoteInterface */
$vote = $event->getVote();
/** @var $user User */
$user = $this->context->getToken()->getUser();
if ($vote->getVoter() !== $user) {
throw new \Exception('Attempt to vote for different user');
}
if ($vote->getComment()->getAuthor() === $user) {
throw new \Exception('Attempt to vote for own comment');
}
$existingVote = $this->voteManager->findVoteBy(array('comment' => $vote->getComment(), 'voter' => $user));
if ($existingVote) {
throw new \Exception('Attempt to vote multiple times for same comment');
}
} catch (\Exception $e) {
$event->abortPersistence();
$event->stopPropagation();
}
}
示例10: onCoreController
/**
* Update the user "lastActivity" on each request
*
* @param FilterControllerEvent $event
*/
public function onCoreController(FilterControllerEvent $event)
{
// Here we are checking that the current request is a "MASTER_REQUEST",
// and ignore any
// subrequest in the process (for example when
// doing a render() in a twig template)
if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
return;
}
// We are checking a token authentification is available before using
// the User
if ($this->securityContext->getToken()) {
$user = $this->securityContext->getToken()->getUser();
// We are using a delay during wich the user will be considered as
// still active, in order to
// avoid too much UPDATE in the
// database
// $delay = new \DateTime ();
// $delay->setTimestamp (strtotime ('2 minutes ago'));
// We are checking the Admin class in order to be certain we can
// call "getLastActivity".
// && $user->getLastActivity() < $delay) {
if ($user instanceof User) {
$user->isActiveNow();
$this->em->persist($user);
$this->em->flush();
}
}
}
示例11: contentBlock
/**
* @param string $blockName
* @param array $options
* @param string $default
* @return string
*/
public function contentBlock($blockName, $options = array(), $default = null)
{
$em = $this->doctrine->getManager();
$repository = $em->getRepository('GlavwebContentBlockBundle:ContentBlock');
$contentBlock = $repository->findOneByName($blockName);
$tag = isset($options['tag']) ? $options['tag'] : 'div';
$attr = isset($options['attr']) ? $options['attr'] : array();
if (isset($options['class'])) {
$attr['class'] = $options['class'];
}
if (isset($options['href'])) {
$attr['href'] = $options['href'];
}
if (!$contentBlock) {
$contentBlock = new ContentBlock();
$contentBlock->setName($blockName);
$contentBlock->setBody($default ? $default : $blockName);
$em->persist($contentBlock);
$em->flush();
}
$contentEditable = '';
$dataBlockName = '';
$isEditable = $this->request && $this->request->get('contenteditable') && $this->securityContext->isGranted('ROLE_ADMIN');
if ($isEditable) {
$contentEditable = ' contenteditable="true"';
$dataBlockName = ' data-block-name="' . $blockName . '"';
$attr['class'] = isset($attr['class']) ? $attr['class'] . ' js-content-block' : 'js-content-block';
}
$attrParts = array();
foreach ($attr as $attrName => $value) {
$attrParts[] = sprintf('%s="%s"', $attrName, $value);
}
return '<' . $tag . ' ' . implode(' ', $attrParts) . ' ' . $contentEditable . $dataBlockName . '>' . $contentBlock->getBody() . '</' . $tag . '>';
}
示例12: onKernelRequest
public function onKernelRequest(GetResponseEvent $event)
{
if ($this->kernel->getEnvironment() != "dev") {
if (preg_match("/\\/api\\//", $event->getRequest()->getUri())) {
$requestUri = $event->getRequest()->getUri();
$requestMethod = $event->getRequest()->getMethod();
if ($requestMethod !== "GET") {
$token = $this->context->getToken();
if (isset($token)) {
$user = $token->getUser();
if (!isset($user) || "anon." === $user) {
if (!$event->getRequest()->query->has('api_key')) {
$event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401));
}
}
} else {
$event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401));
}
}
}
}
$request = $event->getRequest();
if (!count($request->request->all()) && in_array($request->getMethod(), array('POST', 'PUT', 'PATCH', 'DELETE'))) {
$contentType = $request->headers->get('Content-Type');
$format = null === $contentType ? $request->getRequestFormat() : $request->getFormat($contentType);
if (!$this->decoderProvider->supports($format)) {
return;
}
$decoder = $this->decoderProvider->getDecoder($format);
$data = $decoder->decode($request->getContent(), $format);
if (is_array($data)) {
$request->request = new ParameterBag($data);
}
}
}
示例13: onSecurityInteractiveLogin
/**
* Do the magic.
*
* @param InteractiveLoginEvent $event
*/
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
if ($this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
// user has just logged in
}
if ($this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
// user has logged in using remember_me cookie
}
// do some other magic here
$session = $event->getRequest()->getSession();
$referrer = $session->get('referrer');
if (empty($referrer)) {
$referrer = $event->getRequest()->getUri();
}
$user = $event->getAuthenticationToken()->getUser();
$log = new Log();
$log->setIdUsuario($user);
$log->setDtAcao(new \DateTime());
$log->setNmTabela('acesso');
$log->setCsAcao('ACE');
$log->setTeIpOrigem($event->getRequest()->getClientIp());
$log->setNmScript($referrer);
// Registra login
$this->em->persist($log);
$this->em->flush();
// TODO: Redireciona para útima página visitada
}
示例14: getCustomer
/**
* @return CustomerInterface null
*/
protected function getCustomer()
{
$customer = null;
if ($user = $this->securityContext->getToken()->getUser()) {
$customer = $user->getCustomer();
}
return $customer;
}
示例15: getCurrentUser
/**
* Return current user's entity or null if not logged in
*
* @return null|App/UserBundle/Entity/User
*/
public function getCurrentUser()
{
$user = $this->security->getToken()->getUser();
if ($user === 'anon.') {
return null;
}
return $user;
}