I've built a very simple login system using CakePHP but now I have some questions:
1.) How do I show a setFlash message when the user logs in? I tried adding one to the login method but then it will just show it all the time when visiting the login page and does not show it when successfully logging in? But works with the logout method?
2.) When a users login they are ALWAYS taken to the home page because of the loginRedirect, but how do I send them to the page they are currently on? As the login form is in the header of public pages so when they login I want them to be sent back to that same page.
Here is the code I have in place at the moment in my app_controller.php
var $components = array('Auth','Session');
function beforeFilter()
{
$this->Auth->authorize = 'actions';
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'home', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => 'home', 'action' => 'index');
}
and here is my users_controller.php
/**
* Log in
*/
function login ()
{
$this->Session->setFlash('You\'re now logged in');
$this->layout = 'login';
$this->set('title_for_layout', 'Log in');
}
/**
* Log out
*/
function logout ()
{
$this->Session->setFlash('<div class="content"><h2>Pow</h2><p>Moo</p></div>');
$this->redirect($this->Auth->logout());
}
and here is the login form that is in the header of every public page (note that I also have a dedicated login page as well that contains the same form):
<?php echo $this->Form->create('User', array('id' => 'loginform', 'type' => 'post',
'url' => array('controller' => 'users', 'action' => 'login'))); ?>
<fieldset id="login">
<ul class="clearfix">
<li id="li-username">
<?php echo $this->Form->input('username', array('label'=>false,'placeholder'=>'Username or email address')); ?>
</li>
<li id="li-password">
<?php echo $this->Form->input('password', array('type'=>'password','label'=>false,'placeholder'=>'Password')); ?>
<span id="iforgot"><?php echo $this->Html->link('?',
array('controller' => 'users', 'action' => 'forgotpassword'), array('title' => 'Forgot your password?')); ?></span>
</li>
<li id="li-submit">
<button type="submit" title="Log in">Log in ►</button>
</li>
</ul>
</fieldset>
<?php echo $this->Form->end(); ?>