Using EzAuth 0.6
Note: The EzAuth core has changed. You will need to change some things in your database in order to upgrade to 0.6. DO NOT replace the old model with the new one without performing the necessary database changes first! Your users will not be able to login if you replace the model before making the database changes.
To upgrade your existing database tables, run these MySQL commands:
alter table ez_auth add cookie_hash varchar(255), add activation_code varchar(255); alter table ez_users add register_date datetime not null; update ez_users, ez_auth, ez_access_keys set ez_auth.activation_code = md5(concat(md5(ez_users.username), md5(ez_users.email), md5(ez_users.register_date))) where ez_access_keys.access = 'user' and ez_access_keys.user_id = ez_users.id and ez_auth.user_id = ez_users.id;
EzAuth is a simple access control list, user authentication, and user session management system. EzAuth is built as one model. EzAuth lets you use access keys which gives you a lot of flexibility with your domain. Your users can possess an access key or universal key for particular programs you may have running on your site.
Say you have a user named John that is registered with EzAuth as username john_doe and e-mail address, john_doe@mail.com. If your website has a message board, classifieds, e-commerce store, and a members only area, you can give John a different access key for each separate part of your website. If you want John to manage products in your online store, but don't want to give him administrative access to your message board, you can give him two separate keys: one with program name mystore and access_key admin. To restrict his access to the message board, use program name funkyforums and access_key user.
The website developer (you) defines the program names. A user can have an unlimited number of access keys on a website, and you can specify your own keys if you like. EzAuth has two built in access privileges: administrators who have typically have unlimited access to the program and users who have to register with EzAuth and login before they can view the protected pages you specify. If you do specify other kinds of users, you will have to define their access rights in your controller. In other words, authentication will be outside of the EzAuth model that you will define in your controller.
If you like, EzAuth can verify each registrant's e-mail address, acting as a spam filter and creating a wall for bots.

In order to understand how the programs and access keys work, here is a simple site map:

A user will have an access key for each program on your website. This can be a default (user or administrator), or key defined by you. For example, when a user signs up, you can give him access to the "blog" and "store" programs, but maybe the message boards you want to keep to private members of your website. The user will be able to access the two programs he is given keys, but not the private message boards.
You can give users access keys after they have already signed up or on the fly if you need to. Say a user purchases a subscription to your private message boards, you can give them an access key (using the new_access_key function) after their purchase is complete. Or, if you want to create a new public message board, you can give existing users keys automatically (in the authorize method) when they try to access that particular program on your site.
Configuration
EzAuth utilizes CodeIgniter session and database class to manage your website visitors. To start, you must load CodeIgniter's session and database libraries either in your autoload configuration or your controller.
$this->load->library('session');
$this->load->library('database');
Note: Enable cookie encryption and set an encryption key in CodeIgniter's config file if you don't want hackers logging in when they aren't supposed to!
Installation
Setting up the Database Tables
EzAuth requires three database tables: ez_users, ez_auth, and ez_user_access.
- ez_auth stores passwords and its rows shouldn't be retrieved in normal EzAuth use.
- ez_users stores the user ID, username and e-mail address. More columns can be added to ez_users like address, city, state, zip, phone, etc.
- ez_access_keys stores a user's access keys to particular programs.
MySQL Table Descriptions describe ez_auth; +-----------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------+--------------+------+-----+---------+-------+ | user_id | int(11) | NO | PRI | 0 | | | password | varchar(255) | YES | | NULL | | | reset_code | varchar(255) | YES | | NULL | | | cookie_hash | varchar(255) | YES | | NULL | | | activation_code | varchar(255) | YES | | NULL | | +-----------------+--------------+------+-----+---------+-------+ 5 rows in set (0.01 sec) describe ez_access_keys; +---------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | user_id | int(11) | YES | | NULL | | | program | varchar(255) | YES | | NULL | | | access | varchar(255) | YES | | NULL | | +---------+--------------+------+-----+---------+----------------+ 4 rows in set (0.01 sec) describe ez_users; +-------------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | username | varchar(50) | YES | | NULL | | | email | varchar(255) | YES | | NULL | | | register_date | datetime | YES | | NULL | | +-------------------------+--------------+------+-----+---------+----------------+ 4 rows in set (0.01 sec)
Here are the MySQL create table statements for a new installation of EzAuth:
create table ez_auth (user_id int not null primary key, password varchar(255), reset_code varchar(255), cookie_hash varchar(255), activation_code varchar(255)); create table ez_access_keys (id int not null primary key auto_increment, user_id int, program varchar(255), access varchar (255)); create table ez_users (id int not null primary key auto_increment, username varchar (50), email varchar(255), register_date datetime);
Configuring Your Controller
Now we can instantiate the EzAuth model in our controller's constructor. If we have a shopping cart controller and want to keep track of our customers, we can call our program name mystore. Then we are going to define which pages we want EzAuth to protect. By default, EzAuth allows visitors pages that aren't defined as a protected page.
EzAuth 0.5 added two new features:
- A program name is not required in the controller anymore if you only have one application on your website.
- If you want to protect an entire controller's methods, add protected page 'all' and specify an access type.
class MyStore extends Controller {
function MyStore() {
parent::Controller();
$this->load->model('EzAuth_Model', 'ezauth');
$this->ezauth->program = 'mystore';
$this->ezauth->protected_pages = array(
'checkout' => 'user', // user must be logged in to view page
'user_profile' => 'user', // user must be logged in to view page
'edit_products' => 'admin', // user must be administrator to view page
'custom_page' => 'store_manager' // user defined value
);
$this->ezauth->auto_login(); // automatically login if user has cookie hash saved
}
}
If you want to protect all of the methods in your controller use:
$this->ezauth->protected_pages = array('all' => 'user'); // or admin or custom defined
In order to protect the pages we defined, we must install a _remap function in our controller to redirect page calls to EzAuth's authorization function.
function _remap($method) {
$auth = $this->ezauth->authorize($method, true);
if ($auth['authorize'] == 'yes') {
$segments = array_slice($this->uri->segment_array(),2); //redirect with method arguments by marlar on CodeIgniter forums
call_user_func_array(array(&$this, $method), $segments);
} else {
// user login information incorrect, so show login screen again
$this->login();
}
}
New Functions in 0.6
$this->ezauth->auto_login()
Attempts to login user from saved md5 cookie hash.
$this->ezauth->cleanup_pending_registrations($days = 30)
Drops all unverified user data which is older than $days specified.
$this->ezauth->new_access_key($user_id, $program, $access = 'user')
Gives the user a new access key for specified program on website.
$this->ezauth->update_session($ez_array)
Updates $this->user variable and current session with $ez_array variable.
Functions
$this->ezauth->authorize($method, $give_new_key = false)
This method is used to authorize a specific function for the current logged in user. If the user is not logged in and the page requires the user to be logged in, authorize will return false with an error message. The example _remap functions above shows its usage.
Changes in 0.6:
- You can give users new access keys on the fly! If a user is registered on your site and does not have access to a particular area, you can give them a key automatically when they try to navigate to the page. In your _remap function, just set $give_new_key to true.
$this->ezauth->login($un = null, $pw = null, $give_new_key = false, $cookie_hash = '', $get_all_user_info = true)
Establishes EzAuth user session using user defined user name and password or default $this->input->post('username') and $this->input->post('password'). Function returns an array with authorize = true or false. If authorize is false, an error message is given.
Changes in 0.6:
- If a user already has an active account on your website, you can set $give_new_key to true to automatically give them a new access key to that section in the website.
- A user can now login by a md5 cookie hash, saved on the user's computer. This is used for auto-login. You can disable logging in by cookie hash by not remembering the user when logging in, and not allowing users to auto-login.
The example below shows an example login function used in a controller.
function login() {
// set required fields for validation
$rules['username'] = "required";
$this->validation->set_rules($rules);
$fields['username'] = "Username";
$this->validation->set_fields($fields);
// if post variables are set, run validation
if ($this->validation->run()) {
$login_ok = $this->ezauth->login(); // $login_ok returns authorize = true or false depending on user login information
if ($login_ok['authorize'] == true) {
$this->ezauth->remember_user(); // store md5 cookie hash for auto-login
redirect('mystore'); // if user logs in successfully, redirect to main page
} else {
$this->data['error_string'] = $login_ok['error'];
}
}
$this->load->view('login_view',$this->data);
}
$this->ezauth->register($inp, $verify = true, $remember_user = false, $login_after_register = true)
Registers user with EzAuth. EzAuth requires a unique username and unique e-mail if e-mail verification is specified. Below is an example of a registration function used in a controller.
Changes in 0.6:
- You can save the user's info in a cookie hash by setting $remember_user to true. Next time they visit the site, they can automatically login if you call the auto_login function in your controller constructor.
- If you aren't verifying the user's email address, you can set $login_after_register to true to automatically log the user in after registering.
function register() {
$inp = array(
'ez_users' => array(
'username' => $this->input->post('username'), // ** required field!!
'first_name' => $this->input->post('first_name'), // ** not a default ezauth field!
'last_name' => $this->input->post('last_name'), // ** not a default ezauth field!
'email' => $this->input->post('email') // ** only required if using verification
),
'ez_access_keys' => array( // new in 0.6 - multiple access keys can be given now during registration
'mystore' => 'user',
'ezboard' => 'user',
'ezblog' => 'user',
),
'password' => $this->input->post('password'), // ** required field
);
$user_reg = $this->ezauth->register($inp, true, true, false);
// verify parameter set to true, so verification code will be returned, which can be sent to user.
// Remember user set to true, so cookie hash will be saved and user can automatically login next visit.
// Since we are going to verify the user's email address, we can't set login_after_register to true because they must verify first.
// If login_after_register is set and verification is true also, it will try to login, but fail because the user is not verified.
if ($user_reg['reg_ok'] == 'yes') {
$v_code = $user_reg['code'];
// code to send user e-mail with verification code.
$this->load->library('email');
$config['mailtype'] = 'html';
$config['protocol'] = 'sendmail';
$this->email->initialize($config);
$this->email->from('admin+noreply@mydomain.com', 'Friendly Website Bot');
$this->email->to($inp['ez_users']['email']);
$this->email->subject('Verify your e-mail address!');
$this->email->message('<p>This e-mail address was used to sign up on {My Website}. To begin using {My Website}, you must verify your e-mail
address by clicking the link below or copying it and pasting it into your browser.</p><p>{unwrap}<a href="http://mydomain.com/verify/'.$v_code.'"
title="Verify your e-mail address">http://mydomain.com/verify/'.$v_code.'{/unwrap}</a></p>');
$this->email->send();
}
$this->ezauth->verify_email($code, $login_after_verify = false)
Verifies e-mail address using verification code provided via e-mail. Below is an example of a verify function used in a controller. The verification code is the third argument in the URL. For example: http://mydomain.com/mystore/verify/3f2710f36bd0edd76867b06cd9a9845b
Changes in 0.6:
- You can automatically log the user in after they verify their e-mail address by setting $login_after_verify = true.
function verify() {
if ($this->ezauth->verify_email($this->uri->segment(3)) == true) {
// e-mail address verified, can login now
print 'verification ok!! login now';
} else {
// if user tries to visit verify page manually, redirect to main page
redirect('mystore');
}
}
$this->ezauth->logout($drop_cookie = true)
Destroys the EzAuth user session.
Changes in 0.6:
- You can drop the user's saved cookie hash when logging out so they can't automatically login next time. Good for users on public computers.
Lost/Forgotten Passwords
EzAuth has a built-in account retrieval process to assist you, the web developer. Since passwords are stored using MD5 encryption, there is no password retrieval, but instead a password reset process. For each step along the way, you will send the account owner an e-mail with the verification codes provided by EzAuth. When the user clicks the links in the e-mail you send them, it should advance them to the next step in the three step process.
- First, a user provides a valid username or e-mail address. An e-mail should be sent to the account owner providing a link to reset the account password.
- Clicking the link in the e-mail should reset the account password and the new password will be e-mailed to the user.
- The user can login with the temporary password to regain access to the account.
$this->ezauth->get_userid($username = '', $email = '')
Returns array with user_id = user id from username or e-mail address entered and active = active status (verified or unverified).
$this->ezauth->get_reset_code($user_id)
Returns an array with a reset code and email. Send the reset code to the e-mail address provided.
$reset_code = $this->ezauth->get_reset_code($user_id);
$this->ezauth->reset_password($code)
Returns an array with temp_pw = temporary password for user, username = the username and email = the user's email address.
$temporary_pw = $this->ezauth->reset_password($reset_code);
Other Functions
$this->ezauth->change_pw($user_id, $old_pw, $new_pw)
Changes user password, user id and old password must be provided. Returns number of affected rows.
$this->ezauth->change_pw($user_id, $old_password, $new_password);
$this->ezauth->remember_user($user = null, $reset_cookie = false)
Saves a md5 cookie hash with the user's information for automatic login next visit.
$this->ezauth->fetch_userinfo()
Returns user data from cookie hash.
$this->ezauth->delete_userinfo()
Deletes user info.