Home > Recipe Manager > Basic user authentication

Basic user authentication

Today I got the basic user authentication going for the Recipe Manager using this tutorial.

Users Controller

class UsersController extends AppController
{
	var $name = "Users";
	//var $helpers = array('Html', 'Form');
 
	function index()
	{
 
	}
 
	function beforeFilter()
	{
		$this->__validateLoginStatus();
	}
 
	function login()
	{
		if(empty($this->data) == false)
		{
			if(($user = $this->User->validateLogin($this->data['User'])) == true)
			{
				$this->Session->write('User', $user);
				$this->Session->setFlash('You\'ve successfully logged in.');
				$this->redirect('/recipes/');
				exit();
			}
			else
			{
				$this->Session->setFlash('Sorry, the information you\'ve entered is incorrect.');
				exit();
			}
		}
	}
 
	function register()
	{
		if (!empty($this->data))
		{
			//Sanitize::clean($this->data);
			$this->data['User']['password'] = md5($this->data['User']['password']);
			$this->User->create(); // create the model
 
			if ($this->User->save($this->data))
			{
				$this->Session->write('User', $this->User->findByUsername($this->data['User']['username']));
				$this->Session->setFlash('Thank you for registering.');
				$this->redirect('login/');
			}
			else
			{
				$this->Session->setFlash('The User could not be saved. Please, try again.');
			}
		}
	}
 
	function logout()
	{
		$this->Session->destroy('user');
		$this->Session->setFlash('You\'ve successfully logged out.', 2);
		$this->redirect('login');
	}
 
	function __validateLoginStatus()
	{
		if($this->action != 'login' && $this->action != 'logout')
		{
			if($this->Session->check('User') == false)
			{
				$this->redirect('login');
				$this->Session->setFlash('The URL you\'ve followed requires you login.');
			}
		}
	}
 
}

Login View

<div class="login">
<h2>Login</h2>
create('User', array('action' =&gt; 'login'));?&gt;
        input('username');?&gt;
        input('password');?&gt;
        submit('Login');?&gt;
    end(); ?&gt;</div>

Register View

<div class="login">
<h2>Login</h2>
create('User', array('action' =&gt; 'register'));?&gt;
        input('email');?&gt;
        input('username');?&gt;
        input('password');?&gt;
        submit('Register');?&gt;
    end(); ?&gt;</div>

Adding this to the app_controller causes each view to authenticate the user.

class AppController extends Controller {
 
	var $helpers = array('Html', 'Javascript', 'Ajax');
 
	function beforeFilter()
	{
            if($this-&gt;Session-&gt;check('User') == false)
            {
                $this-&gt;redirect('/users/login');
                $this-&gt;Session-&gt;setFlash('The URL you\'ve followed requires you login.');
            }
    }
}

I still have to work on showing user messages and sanitizing the data but this is a good start.

Leave a Reply

Trackbacks:0

Listed below are links to weblogs that reference
Basic user authentication from rhythmicalmedia.com
TOP