diff --git a/en/tutorials-and-examples/cms/authentication.rst b/en/tutorials-and-examples/cms/authentication.rst index bfeae7b601..9824dbd540 100644 --- a/en/tutorials-and-examples/cms/authentication.rst +++ b/en/tutorials-and-examples/cms/authentication.rst @@ -1,8 +1,148 @@ CMS Tutorial - Authentication ############################# -* Adding login -* Adding logout +Now that our CMS has users, we should enable them to login, and apply some basic +access control to the article creation & editing experiences. + +Adding Login +============ + +In CakePHP, authentication is handled by :doc:`/controllers/components`. +Components can be thought of as ways to create reusable chunks of controller +code related to a specific feature or concept. Components can hook into the +controller's event life-cycle and interact with your application that way. To +get started, we'll add the :doc:`AuthComponent +` to our application. We'll want the +create, update and delete methods to require authentication, so we'll add +AuthComponent in our AppController:: + + // In src/Controller/AppController.php + namespace App\Controller; + + use Cake\Controller\Controller; + + class AppController extends Controller + { + public function initialize() + { + // Existing code + + $this->loadComponent('Flash'); + $this->loadComponent('Auth', [ + 'authenticate' => [ + 'Form' => [ + 'fields' => [ + 'username' => 'email', + 'password' => 'password' + ] + ] + ], + 'loginAction' => [ + 'controller' => 'Users', + 'action' => 'login' + ], + // If unauthorized, return them to page they were just on + 'unauthorizedRedirect' => $this->referer() + ]); + + // Allow the display action so our pages controller + // continues to work. Also enable the read only actions. + $this->Auth->allow(['display', 'view', 'index']); + } + } + +We've just told CakePHP that we want to load the ``Flash`` and ``Auth`` +components. In addition, we've customized the configuration of AuthComponent, as +our users table uses ``email`` as the username. Now, if you go any protected +URL, such as ``/articles/add``, you'll be redirected to **/users/login**, which +will show an error page as we have not written that code yet. So let's create +the login action:: + + // In src/Controller/UsersController.php + public function login() + { + if ($this->request->is('post')) { + $user = $this->Auth->identify(); + if ($user) { + $this->Auth->setUser($user); + return $this->redirect($this->Auth->redirectUrl()); + } + $this->Flash->error('Your username or password is incorrect.'); + } + } + +And in **src/Template/Users/login.ctp** add the following:: + +