Issue
I am using cakephp 2.4.5. I would like to redirect all users who have not logged in to a login page. I basically followed the instructions available here.
In summary, the important part is the following code to AppController.php
public $components = array('Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authError' => 'You must be logged in to view this page.',
'loginError' => 'Invalid Username or Password entered, please try again.'
));
Any websites with this URL format http://localhost/cakephp245/controllers/XXX
will be re-directed to the login page. However, websites that are located inside app/webroot
with URL that looks like this http://localhost/cakephp245/app/webroot/XXX
will not be re-directed to the login page.
How can I force websites located inside app/webroot folder to be re-directed to the login page?
Thank you very much.
Solution
Below are the steps that can help to resolve the issues :-
1) Read the documentation how to load the auth componenet in appController
https://book.cakephp.org/3.0/en/controllers/components/authentication.html
Code should be like the below code
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login',
'plugin' => null
],
//'authorize' => ['Controller'],
'loginRedirect' => [
'controller' => 'Users',
'action' => 'dashboard'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login',
],
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'password']
]
],
'unauthorizedRedirect' => false,
'authError' => 'Did you really think you are allowed to see that?',
'storage' => 'Session'
]);
2) Add below code to beforeFilter() of usersController
$this->Auth->allow(['login','logout','register']); // these function will be pulic access
3) Here is the login function put it in UserController
public function login()
{
$this->viewBuilder()->layout('adminlogin'); // set the admin login layout
$user = $this->Users->newEntity();
$this->set('user', $user);
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user){
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}else{
$this->Flash->error(__('Invalid username or password, try again'));
}
}
}
Answered By - kantsverma
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.