After last weeks Auth component, it is now time to go into the full Authentication of a user. In order to use the full power of the Auth component, the table should be named “users”. In the table I created, there were a few different things put in, but for the sake of this, I will limit those.
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL auto_increment,
`username` varchar(25) NOT NULL,
`password` varchar(250) NOT NULL,
`full_name` varchar(250) NOT NULL,
`email` varchar(250) NOT NULL,
`remote_address` varchar(16) NOT NULL,
`last_login` datetime default NULL,
`last_login_ip` varchar(16) default NULL,
`created` datetime NOT NULL,
`modified` datetime default NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
In this table, there is a lot you really do not need, but here is the breakdown: ‘user_id’ is needed for my purposes, ‘username’ and ‘password’ are named as such to be able to use the Auth component methods. The other fields are for personalization (full_name and email). The next three are just for simplistic CYA that should always be good practice, grap the registered IP address, date the user last logged in and the IP they logged in from. Is this a foolproof way of CYA? No. But it starts you out on the right track. The last two I always put in all of my tables, as CakePHP updates those automatically, so this also helps to track when created and when changed.
Now that the table is done, we need to provide some quick validation for registration and such. In the model, the code should look similar to this:
var $name = 'User';
var $primaryKey = 'user_id';
var $validate = array(
'username' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'on' => 'create',
'message' => 'Username must be only letters and numbers, no special characters'
),
'between' => array(
'rule' => array('between', 5, 20),
'on' => 'create',
'message' => 'Username must be between 5 and 20 characters',
),
'isUnique' => array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This username is already taken. Please choose a different one.'
)
),
'email' => array(
'rule' => array('email', true),
'required' => true,
'message' => 'Please provide a valid email address'
),
);
(more…)