作者:axelvn
项目:KunstmaanBundlesCM
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
/* @var $conn Connection */
$conn = $this->getMockBuilder('Doctrine\\DBAL\\Connection')->disableOriginalConstructor()->getMock();
$conn->expects($this->any())->method('getDatabase')->will($this->returnValue('myDatabase'));
/* @var $platform AbstractPlatform */
$platform = $this->getMockForAbstractClass('Doctrine\\DBAL\\Platforms\\AbstractPlatform');
$conn->expects($this->any())->method('getDatabasePlatform')->will($this->returnValue($platform));
/* @var $stmt Statement */
$stmt = $this->getMockForAbstractClass('Kunstmaan\\AdminBundle\\Tests\\Mocks\\StatementMock');
$conn->expects($this->any())->method('executeQuery')->will($this->returnValue($stmt));
$this->em->expects($this->any())->method('getConnection')->will($this->returnValue($conn));
/* @var $conf Configuration */
$conf = $this->getMockBuilder('Doctrine\\ORM\\Configuration')->disableOriginalConstructor()->getMock();
/* @var $strat QuoteStrategy */
$strat = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\QuoteStrategy')->disableOriginalConstructor()->getMock();
$strat->expects($this->any())->method('getTableName')->will($this->returnValue('rootTable'));
$conf->expects($this->any())->method('getQuoteStrategy')->will($this->returnValue($strat));
$conf->expects($this->any())->method('getDefaultQueryHints')->willReturn(array());
$conf->expects($this->any())->method('isSecondLevelCacheEnabled')->willReturn(false);
$this->em->expects($this->any())->method('getConfiguration')->will($this->returnValue($conf));
/* @var $meta ClassMetadata */
$meta = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadata')->disableOriginalConstructor()->getMock();
$this->em->expects($this->any())->method('getClassMetadata')->will($this->returnValue($meta));
$this->sc = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\SecurityContextInterface')->getMock();
$this->token = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface')->getMock();
$this->sc->expects($this->any())->method('getToken')->will($this->returnValue($this->token));
$this->rh = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Role\\RoleHierarchyInterface')->getMock();
$this->object = new AclHelper($this->em, $this->sc, $this->rh);
}
作者:antramp
项目:cr
/**
* @param FormInterface $form
* @param Request $request
* @param RegistryInterface $registry
* @param SecurityContextInterface $security
*/
public function __construct(FormInterface $form, Request $request, RegistryInterface $registry, SecurityContextInterface $security)
{
$this->form = $form;
$this->request = $request;
$this->manager = $registry->getManager();
$this->organization = $security->getToken()->getOrganizationContext();
}
作者:Strontium-9
项目:Syliu
/**
* {@inheritDoc}
*/
public function login(UserInterface $user, $firewallName = 'main')
{
$this->userChecker->checkPreAuth($user);
$token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
$this->securityContext->setToken($token);
$this->eventDispatcher->dispatch(UserEvents::SECURITY_IMPLICIT_LOGIN, new UserEvent($user));
}
作者:ataxe
项目:t
public function previewContentAction( $contentId, $versionNo, $language, $siteAccessName = null )
{
try
{
$content = $this->contentService->loadContent( $contentId, array( $language ), $versionNo );
$location = $this->previewHelper->getPreviewLocation( $contentId );
}
catch ( UnauthorizedException $e )
{
throw new AccessDeniedException();
}
if ( !$this->securityContext->isGranted( new AuthorizationAttribute( 'content', 'versionread', array( 'valueObject' => $content ) ) ) )
{
throw new AccessDeniedException();
}
$siteAccess = $this->previewHelper->getOriginalSiteAccess();
// Only switch if $siteAccessName is set and different from original
if ( $siteAccessName !== null && $siteAccessName !== $siteAccess->name )
{
$siteAccess = $this->previewHelper->changeConfigScope( $siteAccessName );
}
$response = $this->kernel->handle(
$this->getForwardRequest( $location, $content, $siteAccess ),
HttpKernelInterface::SUB_REQUEST
);
$response->headers->remove( 'cache-control' );
$response->headers->remove( 'expires' );
$this->previewHelper->restoreConfigScope();
return $response;
}
作者:mikegibso
项目:sentien
public function isVisible()
{
if ($this->securityContext === null) {
return true;
}
return !$this->securityContext->getToken();
}
作者:xamin12
项目:platfor
/**
* Refresh organization context in token
*
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$token = $this->context->getToken();
if ($token instanceof OrganizationContextTokenInterface) {
$token->setOrganizationContext($this->manager->getOrganizationById($token->getOrganizationContext()->getId()));
}
}
作者:tuandv261
项目:api-key-bundl
/**
* This interface must be implemented by firewall listeners.
*
* @param GetResponseEvent $event
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$this->keyExtractor->hasKey($request)) {
$response = new Response();
$response->setStatusCode(401);
$event->setResponse($response);
return;
}
$apiKey = $this->keyExtractor->extractKey($request);
$token = new ApiKeyUserToken();
$token->setApiKey($apiKey);
try {
$authToken = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
$token = $this->securityContext->getToken();
if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
$this->securityContext->setToken(null);
}
$message = $failed->getMessage();
}
$response = new Response();
$response->setContent($message);
$response->setStatusCode(403);
$event->setResponse($response);
}
作者:unpetitl
项目:stor
/**
* Methode qui est déclenché après l'événement InteractiveLogin
* qui est l'action de login dans la sécurité
* @param InteractiveLoginEvent $event
*/
public function onAuthenticationSuccess(InteractiveLoginEvent $event)
{
$now = new \DateTime('now');
// récupére l'utilisateur courant connecté
$user = $this->securityContext->getToken()->getUser();
//recupere tous les produits de l'utilisateur via le repository ProductRepository
// et via getProductsQuantityIsLower() qui on une quantité < 5
$products = $this->em->getRepository('StoreBackendBundle:Product')->getProductsQuantityIsLower($user);
//pour chaque produit
foreach ($products as $product) {
// si la quantité du produit est égal à 1
if ($product->getQuantity() == 1) {
$this->notification->notify($product->getId(), 'Attention, votre produit ' . $product->getTitle() . ' a une seule quantité', 'product', 'danger');
} else {
$this->notification->notify($product->getId(), 'Attention, votre produit ' . $product->getTitle() . ' a quantité bientot épuisé', 'product', 'warning');
}
}
// declencher une notification dans mes produits
$date = $user->getDateAuth();
$oldyear = new \DateTime('-2 month');
$route = 'store_backend_index';
// Long time to control use account
if ($date < $oldyear || !$date) {
$this->session->set('first', true);
$route = 'store_backend_jeweler_myaccount';
}
// met à jour la date de connexion de l'utilisateur
$user->setDateAuth($now);
//enregistre mon utilisateur avec sa date modifié
$this->em->persist($user);
$this->em->flush();
return new RedirectResponse($this->router->generate($route));
}
作者:MathiasDeweld
项目:EscapeWSSEAuthenticationBundl
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
//find out if the current request contains any information by which the user might be authenticated
if (!$request->headers->has('X-WSSE')) {
return;
}
$ae_message = null;
$this->wsseHeader = $request->headers->get('X-WSSE');
$wsseHeaderInfo = $this->parseHeader();
if ($wsseHeaderInfo !== false) {
$token = new Token($wsseHeaderInfo['Username'], $wsseHeaderInfo['PasswordDigest'], $this->providerKey);
$token->setAttribute('nonce', $wsseHeaderInfo['Nonce']);
$token->setAttribute('created', $wsseHeaderInfo['Created']);
try {
$returnValue = $this->authenticationManager->authenticate($token);
if ($returnValue instanceof TokenInterface) {
return $this->tokenStorage->setToken($returnValue);
} else {
if ($returnValue instanceof Response) {
return $event->setResponse($returnValue);
}
}
} catch (AuthenticationException $ae) {
$event->setResponse($this->authenticationEntryPoint->start($request, $ae));
}
}
}
作者:baszoetekou
项目:janu
/**
* @param GetResponseEvent $event
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->headers->has('cookie')) {
return;
}
if (strstr($request->headers->get('cookie'), 'SimpleSAMLAuthToken') === false) {
return;
}
if (!$request->query->has('csrf-token')) {
$this->logger->notice('Ssp Firewall: Auth Token cookie but no CSRF Token');
return;
}
$csrfToken = $request->query->getAlnum('csrf-token');
if (!$this->csrfProvider->isCsrfTokenValid('api', $csrfToken)) {
$this->logger->notice('Ssp Firewall: Invalid CSRF token for api use: ' . $csrfToken);
return;
}
try {
$authToken = $this->authenticationManager->authenticate(new SspToken());
$this->securityContext->setToken($authToken);
} catch (AuthenticationException $failed) {
$this->logger->warning('Ssp Firewall: failed:' . $failed->getMessage());
$token = $this->securityContext->getToken();
if ($token instanceof SspToken) {
$this->securityContext->setToken(null);
}
return;
}
}
作者:Maksol
项目:platfor
public function testBuild()
{
$organization = new Organization();
$type = 'history';
$userId = 1;
$user = $this->getMockBuilder('stdClass')->setMethods(array('getId'))->getMock();
$user->expects($this->once())->method('getId')->will($this->returnValue($userId));
$token = $this->getMockBuilder('Oro\\Bundle\\SecurityBundle\\Authentication\\Token\\UsernamePasswordOrganizationToken')->disableOriginalConstructor()->getMock();
$token->expects($this->once())->method('getUser')->will($this->returnValue($user));
$token->expects($this->once())->method('getOrganizationContext')->will($this->returnValue($organization));
$this->securityContext->expects($this->atLeastOnce())->method('getToken')->will($this->returnValue($token));
$item = $this->getMock('Oro\\Bundle\\NavigationBundle\\Entity\\NavigationItemInterface');
$this->factory->expects($this->once())->method('createItem')->with($type, array())->will($this->returnValue($item));
$repository = $this->getMockBuilder('Oro\\Bundle\\NavigationBundle\\Entity\\Repository\\HistoryItemRepository')->disableOriginalConstructor()->getMock();
$items = array(array('id' => 1, 'title' => 'test1', 'url' => '/'), array('id' => 2, 'title' => 'test2', 'url' => '/home'));
$repository->expects($this->once())->method('getNavigationItems')->with($userId, $organization, $type)->will($this->returnValue($items));
$this->em->expects($this->once())->method('getRepository')->with(get_class($item))->will($this->returnValue($repository));
$menu = $this->getMockBuilder('Knp\\Menu\\MenuItem')->disableOriginalConstructor()->getMock();
$childMock = $this->getMock('Knp\\Menu\\ItemInterface');
$childMock2 = clone $childMock;
$children = array($childMock, $childMock2);
$matcher = $this->getMock('\\Knp\\Menu\\Matcher\\Matcher');
$matcher->expects($this->once())->method('isCurrent')->will($this->returnValue(true));
$this->builder->setMatcher($matcher);
$menu->expects($this->exactly(2))->method('addChild');
$menu->expects($this->once())->method('setExtra')->with('type', $type);
$menu->expects($this->once())->method('getChildren')->will($this->returnValue($children));
$menu->expects($this->once())->method('removeChild');
$n = rand(1, 10);
$configMock = $this->getMockBuilder('Oro\\Bundle\\ConfigBundle\\Config\\ConfigManager')->disableOriginalConstructor()->getMock();
$configMock->expects($this->once())->method('get')->with($this->equalTo('oro_navigation.maxItems'))->will($this->returnValue($n));
$this->manipulator->expects($this->once())->method('slice')->with($menu, 0, $n);
$this->builder->setOptions($configMock);
$this->builder->build($menu, array(), $type);
}
作者:hyrmedi
项目:KunstmaanBundlesCM
/**
* @return \Symfony\Component\Security\Core\User\UserInterface
*/
private function getUser()
{
if (is_null($this->user)) {
$this->user = $this->securityContext->getToken()->getUser();
}
return $this->user;
}
作者:peterA
项目:pgs-st
/**
* @param string $role
*
* @return bool
*/
protected function isGranted($role)
{
if (!$this->securityContext) {
$this->securityContext = $this->getSecurityContext();
}
return $this->securityContext->isGranted($role);
}
作者:acorbe
项目:FOSUserBundl
public final function logInUser($firewallName, UserInterface $user, Response $response = null)
{
$this->userChecker->checkPostAuth($user);
$token = $this->createToken($firewallName, $user);
$request = null;
if ($this->container->has('request_stack')) {
$request = $this->container->get('request_stack')->getCurrentRequest();
} elseif (method_exists($this->container, 'isScopeActive') && $this->container->isScopeActive('request')) {
// BC for SF <2.4
$request = $this->container->get('request');
}
if (null !== $request) {
$this->sessionStrategy->onAuthentication($request, $token);
if (null !== $response) {
$rememberMeServices = null;
if ($this->container->has('security.authentication.rememberme.services.persistent.' . $firewallName)) {
$rememberMeServices = $this->container->get('security.authentication.rememberme.services.persistent.' . $firewallName);
} elseif ($this->container->has('security.authentication.rememberme.services.simplehash.' . $firewallName)) {
$rememberMeServices = $this->container->get('security.authentication.rememberme.services.simplehash.' . $firewallName);
}
if ($rememberMeServices instanceof RememberMeServicesInterface) {
$rememberMeServices->loginSuccess($request, $response, $token);
}
}
}
$this->tokenStorage->setToken($token);
}
作者:ezsystemstrainin
项目:ez54trainin
/**
* If user is logged-in in legacy_mode (e.g. legacy admin interface),
* will inject currently logged-in user in the repository.
*
* @param GetResponseEvent $event
*/
public function onKernelRequest( GetResponseEvent $event )
{
/** @var \eZ\Publish\Core\MVC\ConfigResolverInterface $configResolver */
$request = $event->getRequest();
$session = $request->getSession();
if (
$event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST
|| !$this->configResolver->getParameter( 'legacy_mode' )
|| !( $session->isStarted() && $session->has( 'eZUserLoggedInID' ) )
)
{
return;
}
try
{
$apiUser = $this->repository->getUserService()->loadUser( $session->get( 'eZUserLoggedInID' ) );
$this->repository->setCurrentUser( $apiUser );
$token = $this->securityContext->getToken();
if ( $token instanceof TokenInterface )
{
$token->setUser( new User( $apiUser ) );
$token->setAuthenticated( true );
}
}
catch ( NotFoundException $e )
{
// Invalid user ID, the user may have been removed => invalidate the token and the session.
$this->securityContext->setToken( null );
$session->invalidate();
}
}
作者:notsentien
项目:CreateBundl
/**
* Render js inclusion for create.js and dependencies and bootstrap code.
*
* THe hallo editor is bundled with create.js and available automatically.
* To use aloha, you need to download the zip, as explained in step 8 of
* the README.
*
* @param string $editor the name of the editor to load, currently hallo and aloha are supported
*/
public function includeJSFilesAction($editor = 'hallo')
{
if ($this->securityContext && false === $this->securityContext->isGranted($this->requiredRole)) {
return new Response('');
}
// We could inject a list of names to template mapping for this
// to allow adding other editors without changing this bundle
$view = new View();
switch ($editor) {
case 'hallo':
if ($this->coffee) {
$view->setTemplate('SymfonyCmfCreateBundle::includecoffeefiles-hallo.html.twig');
} else {
$view->setTemplate('SymfonyCmfCreateBundle::includejsfiles-hallo.html.twig');
}
break;
case 'aloha':
$view->setTemplate('SymfonyCmfCreateBundle::includejsfiles-aloha.html.twig');
break;
default:
throw new \InvalidArgumentException("Unknown editor '{$editor}' requested");
}
$view->setData(array('cmfCreateStanbolUrl' => $this->stanbolUrl, 'cmfCreateImageUploadEnabled' => (bool) $this->imageClass));
return $this->viewHandler->handle($view);
}
作者:viettu
项目:tod
public function onKernelController(FilterControllerEvent $event)
{
if (!is_array($controller = $event->getController())) {
return;
}
$className = class_exists('Doctrine\\Common\\Util\\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]);
$object = new \ReflectionClass($className);
$method = $object->getMethod($controller[1]);
/**
* @var UserType\UserTypeInterface[] $requiredUserTypes
*/
$requiredUserTypes = array_merge($this->getConfigurations($this->reader->getClassAnnotations($object)), $this->getConfigurations($this->reader->getMethodAnnotations($method)));
if (count($requiredUserTypes) === 0) {
return;
}
$token = $this->securityContext->getToken();
if (null === $token) {
throw new AccessDeniedException(sprintf("You are not authenticated, a known user type is required for access."));
}
$user = $token->getUser();
foreach ($requiredUserTypes as $userType) {
$userClass = $userType->getUserClass();
if (!interface_exists($userClass) && !class_exists($userClass)) {
throw new RuntimeException(sprintf("The user type class '%s' does not exist", $userClass));
}
if (!$user instanceof $userClass) {
throw new AccessDeniedException(sprintf("You do not have the required user type. A user type of '%s' is required.", $userClass));
}
unset($userType, $userClass);
}
}
作者:Exanru
项目:crm-bundl
/**
* {@inheritdoc}
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if ($this->securityContext->getToken() !== null) {
return;
}
if ($request->getRequestUri() == '/app_dev.php/api/login' || $request->getRequestUri() == '/api/login') {
return;
}
//Try to reach token from HTTP headers
if ($request->headers->has('X-Auth-Token')) {
$tokenId = $request->headers->get('X-Auth-Token');
} else {
$tokenId = $request->get('token');
}
//by token
if (isset($tokenId)) {
$user = $this->userProvider->findUserByToken($tokenId);
if (!$user) {
throw new BadCredentialsException();
}
try {
$token = new ApiToken([], $this->providerId, $this->key);
$token->setUser($user);
$authenticatedToken = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authenticatedToken);
} catch (AuthenticationException $e) {
//log something
}
}
}
作者:hafeez300
项目:orocommerc
/**
* Process form
*
* @param AccountUser $accountUser
* @return bool True on successful processing, false otherwise
*/
public function process(AccountUser $accountUser)
{
if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
$this->form->submit($this->request);
if ($this->form->isValid()) {
if (!$accountUser->getId()) {
if ($this->form->get('passwordGenerate')->getData()) {
$generatedPassword = $this->userManager->generatePassword(10);
$accountUser->setPlainPassword($generatedPassword);
}
if ($this->form->get('sendEmail')->getData()) {
$this->userManager->sendWelcomeEmail($accountUser);
}
}
$token = $this->securityContext->getToken();
if ($token instanceof OrganizationContextTokenInterface) {
$organization = $token->getOrganizationContext();
$accountUser->setOrganization($organization)->addOrganization($organization);
}
$this->userManager->updateUser($accountUser);
return true;
}
}
return false;
}
作者:ramunas
项目:platfor
/**
* Checking request and response and decide whether we need a redirect
*
* @param FilterResponseEvent $event
*/
public function onResponse(FilterResponseEvent $event)
{
$request = $event->getRequest();
$response = $event->getResponse();
if ($request->get(self::HASH_NAVIGATION_HEADER) || $request->headers->get(self::HASH_NAVIGATION_HEADER)) {
$location = '';
$isFullRedirect = false;
if ($response->isRedirect()) {
$location = $response->headers->get('location');
if ($request->attributes->get('_fullRedirect') || !is_object($this->security->getToken())) {
$isFullRedirect = true;
}
}
if ($response->isNotFound() || $response->getStatusCode() == 503 && !$this->isDebug) {
$location = $request->getUri();
$isFullRedirect = true;
}
if ($location) {
$response = $this->templating->renderResponse('OroNavigationBundle:HashNav:redirect.html.twig', array('full_redirect' => $isFullRedirect, 'location' => $location));
}
// disable cache for ajax navigation pages and change content type to json
$response->headers->set('Content-Type', 'application/json');
$response->headers->addCacheControlDirective('no-cache', true);
$response->headers->addCacheControlDirective('max-age', 0);
$response->headers->addCacheControlDirective('must-revalidate', true);
$response->headers->addCacheControlDirective('no-store', true);
$event->setResponse($response);
}
}