Table of Contents
Cakephp 3 Instructions for Users
In the first post, when we created the database, we also created a table users to perform the most basic cms management, so in this lesson we will use table users there to perform login page, logout, post management…
Similar to articles there are tags, we also create the necessary files, we can use Composer or directly create each file. I also have the source code, but I don’t recommend taking it from me, so I can remember.
Use Composer to create: bin/cake bake all users
After successfully running the above, try to access the url: http://localhost:8888/cakephp_3_7_2/users, to see the list of existing users.
You notice there is a Password column, it shows as secret this is the user’s pass, but for that it is not possible, when it comes to the password we must encrypt it. Regarding coding, there are many standards for coding, here I use the default one in CakePHP is bcrypt , you can use SHA-1 or MD5.
When the user enters their password, we will take that input string and encrypt it through the Entity of the User Model, adding the following encryption in src/Model/Entity/User.php:
<?php namespace AppModelEntity; use CakeAuthDefaultPasswordHasher; // Add this line use CakeORMEntity; class User extends Entity { // Code from bake. // Add this method protected function _setPassword($value) { if (strlen($value)) { $hasher = new DefaultPasswordHasher(); return $hasher->hash($value); } } }
Now, if you go back to the list of users and edit the existing user and update the new password, you will realize that the password has been encrypted when reviewing.
Add Login section
Here we will use Components AuthComponent , more AuthComponent to enter AppController.php
// In src/Controller/AppController.php namespace AppController; use CakeControllerController; class AppController extends Controller { public function initialize() { // Existing code $this->loadComponent('Auth', [ 'authenticate' => [ 'Form' => [ 'fields' => [ 'username' => 'email', 'password' => 'password' ] ] ], 'loginAction' => [ 'controller' => 'Users', 'action' => 'login' ], //use isAuthorized in Controllers 'authorize' => ['Controller'], // If unauthorized, return them to page they were just on 'unauthorizedRedirect' => $this->referer() ]); // Allow the display action so our PagesController // continues to work. Also enable the read only actions. $this->Auth->allow(['display', 'view', 'index']); } public function isAuthorized($user = null) { // Any registered user can access public functions if (!$this->request->getParam('prefix')) { return true; } // Default deny return false; } }
The upper part has a paragraph
'authenticate' => [ 'Form' => [ 'fields' => [ 'username' => 'email', 'password' => 'password' ] ] ],
It is used to determine which field in the users table to log in, in our example we do not use username but use email + password to login.
Next the following paragraph is to define which controller and action the login form
'loginAction' => [ 'controller' => 'Users', 'action' => 'login' ],
At the line $this->Auth->allow([‘display’, ‘view’, ‘index’]); xDetermine which actions do not need to be logged in to still be able to access it, which means that if you access it now add, edit hay delete then it will be redirected to /users/login , display an error message Missing Method in UsersController because we have not created action and view for login page yet. So we create 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 create template file /src/Template/Users/login.ctp
<h1>Login</h1> <?= $this->Form->create() ?> <?= $this->Form->control('email') ?> <?= $this->Form->control('password') ?> <?= $this->Form->button('Login') ?> <?= $this->Form->end() ?>
Now go to the list of posts by url: http://localhost:8888/cakephp_3_7_2/articles, then select an article and then edit or add more, it will automatically go to the login page, enter the email and password changed above (encrypted), after entering correctly it will automatically switch back to the page. edit or add that you selected earlier.
Add Logout section
Add the following to src/Controller/UsersController.php:
public function initialize() { parent::initialize(); $this->Auth->allow(['logout']); } public function logout() { $this->Flash->success('You are now logged out.'); return $this->redirect($this->Auth->logout()); }
Proceed to visit the url: http://localhost:8888/cakephp_3_7_2/users/logout you will get the message ‘You are now logged out’ and return to the login page.
Registration
If you are not logged in, access it http://localhost:8888/cakephp_3_7_2/users/add will be redirected to the login page. Now we open this page so that users can access and register for an account. In src/Controller/UsersController.php edit below line again, add action add to enter:
$this->Auth->allow(['logout','add']);
Here you can access http://localhost:8888/cakephp_3_7_2/users/add to register a user, without prior login.
Restrict access to articles
Next we will make it possible for users to edit their own posts, but not other people’s posts. Update AppController.php again as follows:
public function isAuthorized($user) { $action = $this->request->getParam('action'); // The add and tags actions are always allowed to logged in users. if (in_array($action, ['add', 'tags'])) { return true; } // All other actions require a slug. $slug = $this->request->getParam('pass.0'); if (!$slug) { return false; } // Check that the article belongs to the current user. $article = $this->Articles->findBySlug($slug)->first(); return $article->user_id === $user['id']; }
Here, when accessing to edit or delete an article that is not yours, you will be redirected to the previous page and receive a notification.
Edit more and update the article
The two actions that need updating are add() and edit() in src/Controller/ArticlesController.php
public function add() { $article = $this->Articles->newEntity(); if ($this->request->is('post')) { $article = $this->Articles->patchEntity($article, $this->request->getData()); // Changed: Set the user_id from the session. $article->user_id = $this->Auth->user('id'); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to add your article.')); } $tags = $this->Articles->Tags->find('list'); $this->set('tags', $tags); $this->set('article', $article); } public function edit($slug) { $article = $this->Articles->findBySlug($slug)->contain('Tags')->firstOrFail(); if ($this->request->is(['post', 'put'])) { $this->Articles->patchEntity($article, $this->request->getData(), [ // Added: Disable modification of user_id. 'accessibleFields' => ['user_id' => false] ]); if ($this->Articles->save($article)) { $this->Flash->success(__('Your article has been updated.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('Unable to update your article.')); } $tags = $this->Articles->Tags->find('list'); $this->set('tags', $tags); $this->set('article', $article); }
Remember to let go user_id
control from at add.ctp and edit.ctp
At this point, the basic of a simple cms has been completed, allowing users to log in, post articles, tags, control limit access to articles…
[create_button_post thamso1=” thamso2=’Demo’ thamso3=’http://nongdanit.info/download/cakephp3/users.zip’] [/create_button_post]
[thongbao]
- If you have any questions, please leave a comment below and I will reply as soon as possible.
- Thank you for reading.
[/thongbao]