{"id":199,"date":"2009-12-14T10:59:33","date_gmt":"2009-12-14T18:59:33","guid":{"rendered":"http:\/\/blog.boogly.net\/?p=199"},"modified":"2009-12-14T10:59:33","modified_gmt":"2009-12-14T18:59:33","slug":"cakephp-login-form-with-password-confirmation-using-auth-component","status":"publish","type":"post","link":"http:\/\/otherchin.com\/blog\/2009\/12\/cakephp-login-form-with-password-confirmation-using-auth-component\/","title":{"rendered":"CakePHP login form with password confirmation using Auth component"},"content":{"rendered":"<p>Every time I start CakePHP project, I find that I&#8217;ve forgotten how to set up the user auth system of logins, creating accounts, etc.  There seems to be only a few examples of it on the internet, so I thought I&#8217;d post up my solution.  It uses the <a href=\"http:\/\/api.cakephp.org\/class\/auth-component\">Auth component<\/a> and follows normal user creation convention.  By &#8220;normal user creation convention,&#8221; I mean that you require an email address that&#8217;s used as the login name, a password field, a confirm-password field, and checks to make sure the passwords match.<!--more--><\/p>\n<p>First, create your db table:<\/p>\n<pre><code>CREATE TABLE `users` (\n  `id` int(11) unsigned NOT NULL auto_increment,\n  `email` varchar(60) default NULL,\n  `firstname` varchar(30) default NULL,\n  `lastname` varchar(30) default NULL,\n  `password` varchar(40) default NULL,\n  PRIMARY KEY  (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8<\/code><\/pre>\n<p>Next, create models\/user.php and add validation definitions.  Modify the validation parameters as neede.  You&#8217;ll also need a function that checks whether the two password fields match.<\/p>\n<pre><code>class User extends AppModel {\n  var $name = 'User';\n  var $useTable = 'users';\n\n\n  var $validate = array(\n    'email' => array(\n      'kosher' => array(\n        'rule' => 'email',\n        'message' => 'Please make sure your email is entered correctly.'\n      ),\n      'unique' => array(\n        'rule' => 'isUnique',\n        'message' => 'An account with that email already exists.'\n      ),\n      'required' => array(\n        'rule' => 'notEmpty',\n        'message' => 'Please Enter your email.'\n      )\n    ),\n    'passwd' => array(\n      'min' => array(\n        'rule' => array('minLength', 6),\n        'message' => 'Usernames must be at least 6 characters.'\n      ),\n      'required' => array(\n        'rule' => 'notEmpty',\n        'message'=>'Please enter a password.'\n      ),\n    ),\n    'passwd_confirm' => array(\n      'required'=>'notEmpty',\n      'match'=>array(\n        'rule' => 'validatePasswdConfirm',\n        'message' => 'Passwords do not match'\n      )\n    ),\n    'firstname' => array(\n      'required' => array(\n        'rule' => 'notEmpty',\n        'message'=>'Please enter your first name.'\n      ),\n      'max' => array(\n        'rule' => array('maxLength', 30),\n        'message' => 'First name must be fewer than 30 characters'\n      )\n    ),\n    'lastname' => array(\n      'required' => array(\n        'rule' => 'notEmpty',\n        'message' => 'Please enter your last name.'\n      ),\n      'max' => array(\n        'rule' => array('maxLength', 30),\n        'message' => 'Last name must be fewer than 30 characters'\n      )\n    )\n  );\n\n  function validatePasswdConfirm($data)\n  {\n    if ($this->data['User']['passwd'] !== $data['passwd_confirm'])\n    {\n      return false;\n    }\n    return true;\n  }\n\n  function beforeSave()\n  {\n    if (isset($this->data['User']['passwd']))\n    {\n      $this->data['User']['password'] = Security::hash($this->data['User']['passwd'], null, true);\n      unset($this->data['User']['passwd']);\n    }\n\n    if (isset($this->data['User']['passwd_confirm']))\n    {\n      unset($this->data['User']['passwd_confirm']);\n    }\n\n    return true;\n}\n\n}<\/code><\/pre>\n<p>Create the controllers\/user_controller.php file:<\/p>\n<pre><code>class UsersController extends AppController {\n  var $name = 'Users';\n  var $helpers = array('Html', 'Form');\n  var $components = array('Auth');\n\n  function beforeFilter() {\n    $this->Auth->fields = array(\n        'username' => 'email',\n        'password' => 'password'\n    );\n\n    $this->Auth->allow('register');\n  }\n\n  function index() {\n\n  }\n\n  function login() {\n\n  }\n\n  function logout() {\n    $this->redirect($this->Auth->logout());\n  }\n\n  function register() {\n    if (!empty($this->data)) {\n      $this->User->create();\n      if($this->User->save($this->data))\n      {\n        $this->Session->setFlash(\"Account created!\");\n        $this->redirect('\/');\n      }\n    }\n  }\n\n}<\/code><\/pre>\n<p>Create the login.ctp view:<\/p>\n<pre><code>$session->flash('auth');\necho $form->create('User', array('action' => 'login'));\necho $form->input('email');\necho $form->input('password');\necho $form->end('Login');\necho $html->link('Sign up', array('controller'=>'users', 'action'=>'register'));<\/code><\/pre>\n<p>Create the register.ctp view:<\/p>\n<pre><code>echo $form->create('User', array('action' => 'register'));\necho $form->input('email');\necho $form->input('firstname');\necho $form->input('lastname');\necho $form->input('passwd');\necho $form->input('passwd_confirm', array('type' => 'password'));\necho $form->submit();\necho $form->end();<\/code><\/pre>\n<p>Notice that we named the field &#8220;passwd&#8221; and not &#8220;password&#8221;?  This is because Cake recognizes it as being a password and automatically hashes it.  Although you could set up your app this way, it makes it complicated to do validation on it.  Instead, we just use &#8220;passwd&#8221; and assign the value to &#8220;password&#8221; in our beforeSave function.<\/p>\n<p>That&#8217;s it!  Your basic user login\/registration should be working now.  Customize it according to your app&#8217;s needs.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Every time I start CakePHP project, I find that I&#8217;ve forgotten how to set up the user auth system of logins, creating accounts, etc. There seems to be only a few examples of it on the internet, so I thought I&#8217;d post up my solution. It uses the Auth component and follows normal user creation [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[3],"tags":[17,28],"class_list":["post-199","post","type-post","status-publish","format-standard","hentry","category-development","tag-auth","tag-cakephp"],"_links":{"self":[{"href":"http:\/\/otherchin.com\/blog\/wp-json\/wp\/v2\/posts\/199","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/otherchin.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/otherchin.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/otherchin.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/otherchin.com\/blog\/wp-json\/wp\/v2\/comments?post=199"}],"version-history":[{"count":0,"href":"http:\/\/otherchin.com\/blog\/wp-json\/wp\/v2\/posts\/199\/revisions"}],"wp:attachment":[{"href":"http:\/\/otherchin.com\/blog\/wp-json\/wp\/v2\/media?parent=199"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/otherchin.com\/blog\/wp-json\/wp\/v2\/categories?post=199"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/otherchin.com\/blog\/wp-json\/wp\/v2\/tags?post=199"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}