Basic user authentication
January 3, 2009 – 4:00 pmToday 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' => 'login'));?> input('username');?> input('password');?> submit('Login');?> end(); ?></div>
Register View
<div class="login"> <h2>Login</h2> create('User', array('action' => 'register'));?> input('email');?> input('username');?> input('password');?> submit('Register');?> end(); ?></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->Session->check('User') == false) { $this->redirect('/users/login'); $this->Session->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.