Showing posts with label symfony. Show all posts
Showing posts with label symfony. Show all posts

Wednesday, September 21, 2016

[Security] Switching Users with HTTP Basic Auth does not work

https://github.com/symfony/symfony/issues/8260

A part of the discussion
I'm experiencing an issue with HTTP Basic Auth and the SwitchUserListener. The symptoms are that switching users just does not work:
  • The firewall is configured with stateless: false and switch_user: true
  • When attempting to GET /<existing_path>?_switch_user=<valid_other_user>, the SwitchUserListenerredirectes to /<existing_path>.
  • The active token still points to the 'old' user.
After some research, I found out that this behaviour is caused by two things:
  1. The BasicAuthenticationListener is built in a way that should prevent credentials being checked again when the current token is already authenticated. This condition (among others) is being tested in line 64 and evaluates to false since $token->getUsername() !== $username. This results in the token withROLE_PREVIOUS_ADMIN to be overwritten in SecurityContext (line 75).
  2. Apparently persisting a token with ROLE_PREVIOUS_ADMIN does not work as expected. There already is anissue for this to which I added a comment.
In general, I don't know whether this is a bug or a feature that was never planned, but I would really appreciate some feedback on this. Switching users when providing the user's credentials with every request might sound strange, but there are cases in which this makes perfect sense.
Thank you in advance,

Friday, September 9, 2016

Friday, July 29, 2016

How to check if an user is logged in Symfony2 inside a controller?


106down voteaccepted
Warning: Checking for 'IS_AUTHENTICATED_FULLY' alone will return false if the user has logged in using "Remember me" functionality.
According to Symfony 2 documentation, there are 3 possibilities:
IS_AUTHENTICATED_ANONYMOUSLY - automatically assigned to a user who is in a firewall protected part of the site but who has not actually logged in. This is only possible if anonymous access has been allowed.
IS_AUTHENTICATED_REMEMBERED - automatically assigned to a user who was authenticated via a remember me cookie.
IS_AUTHENTICATED_FULLY - automatically assigned to a user that has provided their login details during the current session.
Those roles represent three levels of authentication:
If you have the IS_AUTHENTICATED_REMEMBERED role, then you also have the IS_AUTHENTICATED_ANONYMOUSLY role. If you have the IS_AUTHENTICATED_FULLY role, then you also have the other two roles. In other words, these roles represent three levels of increasing "strength" of authentication.
I ran into an issue where users of our system that had used "Remember Me" functionality were being treated as if they had not logged in at all on pages that only checked for 'IS_AUTHENTICATED_FULLY'.
The answer then is to require them to re-login if they are not authenticated fully, or to check for the remembered role:
$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
    // authenticated REMEMBERED, FULLY will imply REMEMBERED (NON anonymous)
}
Hopefully, this will save someone out there from making the same mistake I made. I used this very post as a reference when looking up how to check if someone was logged in or not on Symfony 2.

Sunday, July 24, 2016

Identifier Generation Strategies

The previous example showed how to use the default identifier generation strategy without knowing the underlying database with the AUTO-detection strategy. It is also possible to specify the identifier generation strategy more explicitly, which allows you to make use of some additional features.
Here is the list of possible generation strategies:
  • AUTO (default): Tells Doctrine to pick the strategy that is preferred by the used database platform. The preferred strategies are IDENTITY for MySQL, SQLite, MsSQL and SQL Anywhere and SEQUENCE for Oracle and PostgreSQL. This strategy provides full portability.
  • SEQUENCE: Tells Doctrine to use a database sequence for ID generation. This strategy does currently not provide full portability. Sequences are supported by Oracle, PostgreSql and SQL Anywhere.
  • IDENTITY: Tells Doctrine to use special identity columns in the database that generate a value on insertion of a row. This strategy does currently not provide full portability and is supported by the following platforms: MySQL/SQLite/SQL Anywhere (AUTO_INCREMENT), MSSQL (IDENTITY) and PostgreSQL (SERIAL).
  • UUID: Tells Doctrine to use the built-in Universally Unique Identifier generator. This strategy provides full portability.
  • TABLE: Tells Doctrine to use a separate table for ID generation. This strategy provides full portability. *This strategy is not yet implemented!*
  • NONE: Tells Doctrine that the identifiers are assigned (and thus generated) by your code. The assignment must take place before a new entity is passed to EntityManager#persist. NONE is the same as leaving off the @GeneratedValue entirely.

Thursday, June 30, 2016

Selected value in Twig

The resolution was to force conversion of int to string:
{{ form_widget(form.item1, {value: myvariable ~ ""}) }}
Check this out :

http://stackoverflow.com/questions/25326400/selected-value-in-twig

Tuesday, June 28, 2016

Explicitly print CSRF token field instead of form_rest(form)

Types doctrine

How to catch Exception in symfony 2 ?

You should take care for the exceptions that could be raised:
try{
  $em = $this->getDoctrine()->getManager();
  $em->persist($entity);
  $em->flush();

  return $this->redirect($this->generateUrl('target page'));

} catch(\Doctrine\ORM\ORMException $e){
  // flash msg
  $this->get('session')->getFlashBag()->add('error', 'Your custom message');
  // or some shortcut that need to be implemented
  // $this->addFlash('error', 'Custom message');

  // error logging - need customization
  $this->get('logger')->error($e->getMessage());
  //$this->get('logger')->error($e->getTraceAsString());
  // or some shortcut that need to be implemented
  // $this->logError($e);

  // some redirection e. g. to referer
  return $this->redirect($this->getRequest()->headers->get('referer'));
} catch(\Exception $e){
  // other exceptions
  // flash
  // logger
  // redirection
}

return $this->render('MyTestBundle:Article:new.html.twig', array(
  'entity' => $entity,
  'form'   => $form->createView(),
));


New in Symfony 2.6: New shortcut methods for controllers

Thursday, April 7, 2016

[Symfony] how to load data fixtures with --fixtures

You need to specify the folder

doctrine:fixtures:load --fixtures=src/PMI/UserBundle/DataFixtures/ORM --append

Monday, March 21, 2016

Symfony 2 How To Disable CSRF on a Per Form Basis

Here are two ways to disable the CSRF in Symfony 2 Forms:
public function getDefaultOptions(array $options)
   {
       return array(
           'data_class'      => 'Acme\TaskBundle\Entity\Task',
           'csrf_protection' => false,  // <---- set this to false on a per Form Type basis
           //'csrf_field_name' => '_token',
           // a unique key to help generate the secret token
           //'intention'       => 'task_item',
       );
   }
And while creating the form:
$form = $this->createFormBuilder($users, array(
    'csrf_protection' => false,  // <---- set this to false on a per Form Instance basis
))->add(...)
;
If this has been helpful please donate, thanks!
http://www.craftitonline.com/2011/08/symfony-2-how-to-disable-csrf-on-a-per-form-basis/

Friday, March 18, 2016

PPM - PHP Process Manager

PHP-PM is a process manager, supercharger and load balancer for PHP applications.
It's based on ReactPHP and works best with applications that use request-response frameworks like Symfony's HTTPKernel. The approach of this is to kill the expensive bootstrap of PHP (declaring symbols, loading/parsing files) and the bootstrap of feature-rich frameworks. See Performance section for a quick hint. PHP-PM basically spawns several PHP instances as worker bootstraping your application (eg. the whole Symfony Kernel) and hold it in the memory to be prepared for every incoming request: This is why PHP-PM makes your application so fast.
More information can be found in the article: Bring High Performance Into Your PHP App (with ReactPHP)

Features

  • Performance boost of over 15x (compared to PHP-FPM, Symfony applications).
  • Integrated load balancer.
  • Hot-Code reload (when PHP files changes).
  • Static file serving for easy development procedures.
  • Support for HttpKernel (Symfony/Laravel), Drupal, Zend.
Check this out
https://github.com/php-pm/php-pm

Wednesday, February 10, 2016

Faire un include avec Symfony2 et Twig

Symfony 2 Génération des traductions

Symfony propose un outil console qui génère des traductions.

Extraction des traductions dans un bundle avec translation:update
php app/console translation:update fr --force --output-format=xlf

Cette commande crée le fichier app/Resources/translations/messages.fr.xlf

Le premier paramètre de ces deux commandes est la locale pour laquelle il faut générer la liste des traductions ( fr dans notre exemple)
Si un fichier de traduction existe déjà, il est mis à jour en ajoutant les clés absentes de la précédente version

La valeur de --outpu-format indique que le format du fichier de sortie :xlf pour XLIFF, yml pour Yaml et php pour PHP

Thursday, January 21, 2016

Doctrine 2 et Oracle

Configuration Symfony2 et Oracle :

  • /app/config/config.yml

services: listener: 
       class: Doctrine\DBAL\Event\Listeners\OracleSessionInit 
       tags: 
            - { name: doctrine.event_listener, event: postConnect }

Check this out : http://tekcollab.imdeo.com/doctrine-2-et-oracle-utilisation-du-type-datetime/
http://www.tutoriel-symfony2.fr/blog/symfony2-avec-oracle-database-sous-ubuntu



Monday, January 11, 2016

How to specify default format for FOS\RestBundle to json

In src/apibundle/Resources/config/routing.yml with yaml configuration

api:
    type:     rest
    resource: "@APIBundle/Resources/config/routing.yml"
    defaults: {_format: json} 
    prefix:   /api

Friday, January 23, 2015

Limiter la longueur d'une chaine avec twig

Check this out : http://francois-deleglise.fr/2012/06/limiter-la-longueur-dune-chaine-avec-twig-filtre-truncate/