本文整理汇总了PHP中Symfony\Component\Security\Core\SecurityContext::getToken方法的典型用法代码示例。如果您正苦于以下问题:PHP SecurityContext::getToken方法的具体用法?PHP SecurityContext::getToken怎么用?PHP SecurityContext::getToken使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\Security\Core\SecurityContext
的用法示例。
在下文中一共展示了SecurityContext::getToken方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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);
}
}
}
示例2: 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();
}
}
}
示例3: 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;
}
}
示例4: 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());
}
示例5: 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();
}
}
示例6: isOwnerOrAdmin
public function isOwnerOrAdmin(User $user = null)
{
if ($this->isAdmin()) {
return true;
}
return $user && $user === $this->context->getToken()->getUser();
}
示例7: buildForm
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->securityContext->getToken()->getUser();
if ($user === 'anon.') {
$user = false;
}
$builder->add('clientFirstName', null, array('attr' => array('placeholder' => 'Иван', 'class' => 'input_block'), 'label' => 'Имя', 'data' => $user ? $user->getFirstname() : ''))->add('clientLastName', null, array('attr' => array('placeholder' => 'Иванов', 'class' => 'input_block'), 'label' => 'Фамилия', 'data' => $user ? $user->getLastname() : ''))->add('telephone', null, array('attr' => array('placeholder' => '+7 910 001 10 10', 'class' => 'input_block'), 'label' => 'Телефон', 'data' => $user ? $user->getPhone() : ''))->add('email', EmailType::class, array('attr' => array('placeholder' => 'mail@mail.ru', 'class' => 'input_block'), 'label' => 'E-mail', 'data' => $user ? $user->getEmail() : ''))->add('address', new AddressOrderType(), array('label' => false, 'required' => false, 'data_class' => 'ShopBundle\\Entity\\AddressOrder'))->add('wishes', null, array('label' => 'Ваши пожелания'))->add('deliveryType', 'hidden', array('data' => DeliveryType::PICKUP))->add('products', 'hidden', array('data' => $this->session->get('ids')))->add('summ', 'hidden', array('data' => $this->session->get('basketSumm')))->add('bonus', 'hidden', array('data' => 0));
}
示例8: 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;
}
示例9: getUser
/**
* Get the user entity, if applicable
*
* @return User|null
*/
public function getUser()
{
$token = $this->token_storage->getToken();
if (!$token || !$token->getUsername()) {
return null;
}
return $this->getUserByUsername($token->getUsername());
}
示例10: getCustomer
/**
* @return CustomerInterface null
*/
protected function getCustomer()
{
$customer = null;
if ($user = $this->securityContext->getToken()->getUser()) {
$customer = $user->getCustomer();
}
return $customer;
}
示例11: buildForm
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->securityContext->getToken()->getUser();
$builder->add('srcCard', 'entity', array('label' => 'account.main.card.issuing.loyalty', 'required' => false, 'class' => 'SehBundle:Customer\\AccentCard', 'property' => 'number', 'empty_value' => false, 'multiple' => false, 'expanded' => false, 'query_builder' => function (EntityRepository $er) use($user) {
return $er->createQueryBuilder('u')->where('u.customer = :user')->andWhere('u.status = :active')->setParameters(array('user' => $user, 'active' => AccentCard::ACTIF));
}))->add('destCard', 'entity', array('label' => 'account.main.receiving.loyalty.card', 'required' => false, 'class' => 'SehBundle:Customer\\AccentCard', 'property' => 'number', 'empty_value' => false, 'multiple' => false, 'expanded' => false, 'query_builder' => function (EntityRepository $er) use($user) {
return $er->createQueryBuilder('u')->where('u.customer = :user')->andWhere('u.status = :active')->setParameters(array('user' => $user, 'active' => AccentCard::ACTIF));
}))->add('nbPoints', 'text', array('label' => 'account.main.point.transferred', 'required' => false));
}
示例12: __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;
}
示例13: configureFormFields
/**
* {@inheritdoc}
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->with('General')->add('username')->add('email')->add('plainPassword', 'text', array('required' => false))->end()->with('Groups')->add('groups', 'sonata_type_model', array('required' => false, 'expanded' => true, 'multiple' => true))->end()->with('Profile')->add('firstname', null, array('required' => false))->add('lastname', null, array('required' => false))->add('phone', null, array('required' => false))->end();
/** @var $user \Application\Sonata\UserBundle\Entity\User */
$user = $this->security_context->getToken()->getUser();
if ($user->hasRole('ROLE_SUPER_ADMIN')) {
$formMapper->with('Management')->add('roles', 'sonata_security_roles', array('expanded' => true, 'multiple' => true, 'required' => false))->add('locked', null, array('required' => false))->add('expired', null, array('required' => false))->add('enabled', null, array('required' => false, 'attr' => array('checked' => 'yes')))->add('credentialsExpired', null, array('required' => false))->end();
}
$formMapper->with('Security')->add('token', null, array('required' => false))->add('twoStepVerificationCode', null, array('required' => false))->end();
}
示例14: onKernelRequest
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$user = $this->securityContext->getToken() ? $this->securityContext->getToken()->getUser() : null;
if (!$user instanceof User) {
if ($request->get('_route') != null && $request->get('_route') != "login" && $request->get('_route') != "login_check" && $request->get('_route') != "logout" && $request->get('_route') != "fos_user_security_login" && $request->get('_route') != "index" && $request->get('_route') != "api_logo") {
$event->setResponse(new RedirectResponse($this->router->generate('login')));
}
}
}
示例15: onKernelRequest
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$user = $this->securityContext->getToken() ? $this->securityContext->getToken()->getUser() : null;
if (!$user instanceof User) {
if ($request->get('_route') != null && $request->get('_route') != "esn_login_homepage" && $request->get('_route') != "esn_login_check" && $request->get('_route') != "fos_user_security_login" && $request->get('_route') != "esn_hr_recruitment_create" && $request->get('_route') != "esn_hr_recruitment_create_short") {
$event->setResponse(new RedirectResponse($this->router->generate('esn_login_homepage')));
}
}
}