PageRenderTime 56ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/doctrine/doctrine-module/docs/authentication.md

https://bitbucket.org/zbahij/eprojets_app
Markdown | 179 lines | 134 code | 45 blank | 0 comment | 0 complexity | f2819412078586778bf92c129d883c47 MD5 | raw file
  1. # Authentication
  2. Authentication through Doctrine is fully supported by DoctrineModule through an authentication adapter, and a specific storage implementation that relies on the database. Most of the time, those classes will be used in conjunction with `Zend\Authentication\AuthenticationService` class.
  3. ### Simple example
  4. In order to authenticate a user (or anything else) against Doctrine, the following workflow will be use :
  5. 1. Create an authentication adapter that contains options about the entity that is authenticated (credential property, identity property).
  6. 2. Create a storage adapter. If the authentication succeeds, the identifier of the entity will be automatically stored in session.
  7. 3. Create a `Zend\Authentication\AuthenticationService`instance that contains both the authentication adapter and the storage adapter.
  8. #### Authentication factory
  9. To make your life easier, DoctrineModule provides an Authentication factory through the ``DoctrineModule\Options\Authentication`` class.
  10. The first task is to configure the Authentication by adding the ``authentication`` key to the ``doctrine`` key in your config file (we assume here that the entity we want to authentication is simply called `Application\Entity\User`):
  11. ```php
  12. // in your module.config.php:
  13. return array(
  14. 'doctrine' => array(
  15. 'authentication' => array(
  16. 'orm_default' => array(
  17. 'object_manager' => 'Doctrine\ORM\EntityManager',
  18. 'identity_class' => 'Application\Entity\User',
  19. 'identity_property' => 'email',
  20. 'credential_property' => 'password',
  21. ),
  22. ),
  23. ),
  24. );
  25. ```
  26. Here are some explanations about the keys:
  27. * the `object_manager` key can either be a concrete instance of a `Doctrine\Common\Persistence\ObjectManager` or a single string that will fetched from the Service Manager in order to get a concrete instance. If you are using DoctrineORMModule, you can simply write 'Doctrine\ORM\EntityManager' (as the EntityManager implements the class `Doctrine\Common\Persistence\ObjectManager`).
  28. * the `identity_class` contains the FQCN of the entity that will be used during the authentication process.
  29. * the `identity_property` contains the name of the property that will be used as the identity property (most often, this is email, username). Please note that we are talking here of the PROPERTY, not the table column name (although it can be the same in most of the cases).
  30. * the `credential_property` contains the name of the property that will be used as the credential property (most often, this is password).
  31. The authentication accept some more options that can be used :
  32. * the `object_repository` can be used instead of the `object_manager` key. Most of the time you won't deal with the one, as specifying the `identity_class` name will automatically fetch the `object_repository` for you.
  33. * the `credential_callable` is a very useful option that allow you to perform some custom logic when checking if the credential is correct. For instance, if your password are encrypted using Bcrypt algorithm, you will need to perform specific logic. This option can be any callable function (closure, class method). This function will be given the complete entity fetched from the database, and the credential that was given by the user during the authentication process.
  34. Here is an example code that adds the `credential_callable` function to our previous example :
  35. ```php
  36. // in your module.config.php:
  37. return array(
  38. 'doctrine' => array(
  39. 'authentication' => array(
  40. 'orm_default => array(
  41. 'object_manager' => 'Doctrine\ORM\EntityManager',
  42. 'identity_class' => 'Application\Entity\User',
  43. 'identity_property' => 'email',
  44. 'credential_property' => 'password',
  45. 'credential_callable' => function(User $user, $passwordGiven) {
  46. return my_awesome_check_test($user->getPassword(), $passwordGiven);
  47. },
  48. ),
  49. ),
  50. ),
  51. );
  52. ```
  53. #### Creating the AuthenticationService
  54. Now that we have configured the authentication, we need still need to tell Zend Framework how to construct a correct ``Zend\Authentication\AuthenticationService`` instance. For this, add the following code in your Module.php class:
  55. ```php
  56. namespace Application;
  57. use Zend\Authentication\AuthenticationService;
  58. class Module
  59. {
  60. public function getServiceConfig()
  61. {
  62. return array(
  63. 'factories' => array(
  64. 'Zend\Authentication\AuthenticationService' => function($serviceManager) {
  65. // If you are using DoctrineORMModule:
  66. return $serviceManager->get('doctrine.authenticationservice.orm_default');
  67. // If you are using DoctrineODMModule:
  68. return $serviceManager->get('doctrine.authenticationservice.odm_default');
  69. }
  70. )
  71. );
  72. }
  73. }
  74. ```
  75. Please note that Iam using here a ``Zend\Authentication\AuthenticationService`` name, but it can be anything else (``my_auth_service``). However, using the name ``Zend\Authentication\AuthenticationService`` will allow it to be recognised by the ZF2 view helper.
  76. #### Using the AuthenticationService
  77. Now that we have defined how to create a `Zend\Authentication\AuthenticationService` object, we can use it in our code. For more information about Zend authentication mechanisms, please read [the ZF 2 Authentication's documentation](http://framework.zend.com/manual/2.0/en/modules/zend.authentication.intro.html).
  78. Here is an example of you we could use it from a controller action (we stripped any Form things for simplicity):
  79. ```php
  80. public function loginAction()
  81. {
  82. $data = $this->getRequest()->getPost();
  83. // If you used another name for the authentication service, change it here
  84. $authService = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
  85. $adapter = $authService->getAdapter();
  86. $adapter->setIdentityValue($data['login']);
  87. $adapter->setCredentialValue($data['password']);
  88. $authResult = $authService->authenticate();
  89. if ($authResult->isValid()) {
  90. return $this->redirect()->toRoute('home');
  91. }
  92. return new ViewModel(array(
  93. 'error' => 'Your authentication credentials are not valid',
  94. ));
  95. }
  96. ```
  97. Of course, doing this in the controller is not the best practice, and you'd better move that kind of logic to a service layer. But this is how it works.
  98. Note that when the authentication is valid, we first get the identity :
  99. ```php
  100. $identity = $authenticationResult->getIdentity();
  101. ```
  102. This will return the full entity (in our case, an `Application\Entity\User` instance). However, storing a full entity in session is not a recommended practice. That's why, when writing the identity :
  103. ```php
  104. $authService->getStorage()->write($identity);
  105. ```
  106. The storage automatically extracts ONLY the identifier values and only store this in session (this avoid to store in session a serialized entity, which is a bad practice). Later, when you want to retrieve the logged user :
  107. ```php
  108. $authenticationService = $this->serviceLocator()->get('Zend\Authentication\AuthenticationService');
  109. $loggedUser = $authenticationService->getIdentity();
  110. ```
  111. The authentication storage will automatically handle the conversion from saved data to managed entity and the opposite. It will avoid serializing entities since that is a strongly discouraged practice.
  112. #### View helper and controller helper
  113. You may also need to know if there is an authenticated user within your other controllers or in views. ZF2 provides a controller plugin and a view helper you may use.
  114. Here is how you use it in your controller :
  115. ```php
  116. public function testAction()
  117. {
  118. if ($user = $this->identity()) {
  119. // someone is logged !
  120. } else {
  121. // not logged in
  122. }
  123. }
  124. ```
  125. And in your view :
  126. ```php
  127. <?php
  128. if ($user = $this->identity()) {
  129. echo 'Logged in as ' . $this->escapeHtml($user->getUsername());
  130. } else {
  131. echo 'Not logged in';
  132. }
  133. ?>
  134. ```