You are on page 1of 53

Welcome to DX Auth

DX Auth is an authentication library for Code Igniter. It's goal to enable you to easily include secure and easy to use authentication library to your project, while giving you the flexibility to choose from simple authentication system to full fledged authentication system. DX Auth is also build with internationalization in mind, so every string is available in language file. (Except the bundled examples, because that is your code not the library). It's based on CL Auth 0.2.5 beta developed by Jason Ashdown.

What is the feature of DX Auth?


Basic auth (Login, logout, register, change password). Remember me. Login using username or email address or both (depend on config settings). Forgot password. Ban user. Last login IP address and time (optional). Email activation (optional). User Profile (optional). Role based (admin, user, moderator, etc). Inheritance also supported (optional). Restrict page based on URI and role (optional). Custom permission for each role (optional). Login attempt (optional). You can use this to display catpcha after specified try to login to prevent bot. Event feature (For example: You can put your own code like PM welcome message after user activated, etc). Captcha (optional, native and reCAPTCHA is available). Simple admin panel (So you can customize it, include it into your own admin panel, or delete if you don't need it). Most of the feature is optional, means you can turn it off in config file, delete it, or just don't use it.

What is changed since CL Auth 0.2.5


If you are ever using CL Auth before, you might want to know what's changed since CL Auth 0.2.5

Bug fixes. Add and change function. Changed code structure.

Group changed to role. Compatible with CI bundled session without hacking it. Added language file for internationalization. All function named lower_case instead of camelCase. Source code writing following CI User guide. Commented source code so you can follow along. Code Igniter style user guide with detailed explanation. And other that i don't remember :).

Looks good, so where to get started? Read Getting started, or simple example. DX Auth is tested in CI 1.7.0, but should be working for above version.

Table of Contents
Basic Info

General Topics

Examples

License Agreement Change Log Upgrading from previous version Credits

Getting Started Functions Events Config Models Tables anatomy Troubleshooting

Simple example Advanced example Recaptcha example Permission example

Installation

Downloading DX Auth Installation Instructions Database Schema

Change Log
Version 1.0.6
Release Date: January 3, 2008

Added salt option in config. Added case sensitive captcha option in config. Changed encode function, removed encryption key dependency. Fixed bugs in DX Auth. Added allow parameter in check_uri_permissions(). Changed model/dx_auth/permissions.php

Version 1.0.5
Release Date: December 20, 2008

Moved system/plugins to application/plugins. Fixed bug in in model/dx_auth/user_temp.php. Fixed bug in in model/dx_auth/permissions.php.

Version 1.0.4
Release Date: December 15, 2008

Added $check_parent parameter in is_role() function. Changed $use_role_name to TRUE by default, in is_role() function. Added 'DX_' prefix in session userdata used by DX_Auth library. Changed <? to <?php backend views example.

Version 1.0.3
Release Date: December 12, 2008

Fixed typos in function get_catpcha_image, renamed into get_captcha_image. Fixed examples, to reflect function changed above. Added 3 more event in DX_Auth_Event.

Version 1.0.2
Release Date: December 5, 2008

Added parent_id field in roles table to add role inheritance feature. Added permission table, to save custom permission including uri permissions. 'role_uri' table is obsolete. Instead, use permission table. 'DX_role_uri_table' in config is obsolete. Add 'DX_permissions_table' in config. Added check_uri_permission() function. Added get_permission_value() function. Added get_permissions_value() function. check_role_uri() function is obsolete, instead use check_uri_permission() to work with new permission table. Add'permissions' model to work with permission table. 'role_uri' model is now obsolete.

'cpanel' admin panel example now renamed to 'backend'. Added example for custom permissions. Simplified admin panel example. Fixed failed to load DX Auth in some OS because file name is case sensitive. Bug fixed in admin panel example.

Version 1.0.1
Release Date: December 2, 2008

Added files that forgotten to be included in zip folder. It's recommended to download this version. Removed 'english' in load language so DX Auth will use language specified in CI config. Optimized is_admin() function. Optimized is_role() function. Converted all models to use CI AR instead of SQL plain. Added get_role_id() function. Added get_role_name() function. Added get_ban_reason() function. Removed is_captcha_initialized() function. Removed is_recaptcha_initialized() function. Removed unused function in models because of these changes. Revised advanced example in user guide, controllers/auth.php, views/login_form.php example because is_captcha_initialized() and is_recaptcha_initialized() removed. Update user guide.

Version 1.0
Release Date: November 30, 2008 First publicly released version.

From version 1.0.5 to 1.0.6


Add DX_salt and DX_captcha_case_sensitive into config. Since now DX Auth do not use encryption_key in CI config to encode password. If your encryption_key is not blank before this update, you need to change encode function in libraries/DX_Auth.php to DX Auth 1.0.5 version. Overwrite libraries/dx_auth.php with the new one. Overwrite models/dx_auth/permissions.php with the new one.

From version 1.0.4 to 1.0.5


Overwrite models/dx_auth/user_temp.php with the new one. Overwrite models/dx_auth/permissions.php with the new one.

From version 1.0.3 to 1.0.4


If you use is_role() function, be careful because in 1.0.4, $use_role_name parameter default is TRUE. In previous version, $use_role_name parameter is defined as FALSE by default, even tough it was written as TRUE in documentation. So now it's fixed.

From version 1.0.2 to 1.0.3


Change function get_catpcha_image() to get_captcha_image(). Notice the first function is wrongly typed.

From version 1.0.1 to 1.0.2


Step 1: Update your roles table
Add parent_id field (int) not null default is 0, in roles table. To add this column you will run a query similar to this:
ALTER TABLE `roles` ADD `parent_id` int(11) NOT NULL default '0'

See table anatomy to know more about this.

Step 2: Add permissions table


To add this table you will run a query similar to this:
CREATE TABLE `permissions` ( `id` int(11) NOT NULL auto_increment, `role_id` int(11) NOT NULL, `data` text collate utf8_bin, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

See table anatomy to know more about this.

Note: role_uri table will be abandonded, in 1.0.2 it will use this permission table.

Installation Instructions
Installing DX Auth library with bundled examples
1. Unzip the package.

2. Copy captcha folder into your CI folder. Make this folder writable by web server. 3. Copy application folder into your CI application folder. 4. Install DX Auth database schema into your database. 5. Open the application/config/config.php. Change $config['sess_use_database'] to TRUE. Installing only DX Auth library
1. Unzip the package.

2. Copy captcha folder into your CI folder. Make this folder writable by web server. 3. Copy application/plugins/ folder into your CI application/plugins/ folder. 4. Copy application/config/ folder into your CI application/config/ folder. 5. Copy application/libraries/ folder into your CI application/libraries/ folder. 6. Copy application/helpers/ folder into your CI application/helpers/ folder. 7. Copy application/models/ folder into your CI application/models/ folder. 8. Copy application/language/ folder into your CI application/language/ folder. 9. Install DX Auth database schema into your database. 10. Open the application/config/config.php. Change $config['sess_use_database'] to TRUE.
That's it! If you're new to DX Auth, please read the Getting Started section of the User Guide to begin using DX Auth.

Database schema
Below is the database schema needed by DX Auth library, or you can find this schema in 'schema.sql' file after you extract downloaded zip file. This will install:

CI Session table named 'ci_sessions'. You can remove the 'ci_sessions' install script if you already have this table in your database. DX Auth library table. User with admin role, username: admin, password: hello. User with user role, username: user, password: hello.

Default roles in role_table (User and admin).

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */;

-- --------------------------------------------------------

--- Table structure for table `ci_sessions` --

CREATE TABLE IF NOT EXISTS `ci_sessions` ( `session_id` varchar(40) collate utf8_bin NOT NULL default '0', `ip_address` varchar(16) collate utf8_bin NOT NULL default '0', `user_agent` varchar(150) collate utf8_bin NOT NULL, `last_activity` int(10) unsigned NOT NULL default '0', `user_data` text collate utf8_bin NOT NULL, PRIMARY KEY (`session_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- --------------------------------------------------------

--- Table structure for table `login_attempts` --

CREATE TABLE IF NOT EXISTS `login_attempts` ( `id` int(11) NOT NULL auto_increment,

`ip_address` varchar(40) collate utf8_bin NOT NULL, `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--- Table structure for table `roles` --

CREATE TABLE IF NOT EXISTS `roles` ( `id` int(11) NOT NULL auto_increment, `parent_id` int(11) NOT NULL default '0', `name` varchar(30) collate utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=3 ;

--- Dumping data for table `roles` --

INSERT INTO `roles` (`id`, `parent_id`, `name`) VALUES (1, 0, 'User'), (2, 0, 'Admin');

-- --------------------------------------------------------

--- Table structure for table `permissions` --

CREATE TABLE IF NOT EXISTS `permissions` ( `id` int(11) NOT NULL auto_increment, `role_id` int(11) NOT NULL, `data` text collate utf8_bin, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--- Table structure for table `users` --

CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL auto_increment, `role_id` int(11) NOT NULL default '1', `username` varchar(25) collate utf8_bin NOT NULL, `password` varchar(34) collate utf8_bin NOT NULL, `email` varchar(100) collate utf8_bin NOT NULL, `banned` tinyint(1) NOT NULL default '0', `ban_reason` varchar(255) collate utf8_bin default NULL, `newpass` varchar(34) collate utf8_bin default NULL, `newpass_key` varchar(32) collate utf8_bin default NULL, `newpass_time` datetime default NULL, `last_ip` varchar(40) collate utf8_bin NOT NULL, `last_login` datetime NOT NULL default '0000-00-00 00:00:00', `created` datetime NOT NULL default '0000-00-00 00:00:00', `modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=3 ;

--- Dumping data for table `users` --

INSERT INTO `users` (`id`, `role_id`, `username`, `password`, `email`, `banned`, `ban_reason`, `newpass`, `newpass_key`, `newpass_time`, `last_ip`, `last_login`, `created`, `modified`) VALUES (1, 2, 'admin', '$1$i75.Do4.$ROPRZjZzDx/JjqeVtaJLW.', 'admin@localhost.com', 0, NULL, NULL, NULL, NULL, '127.0.0.1', '2008-11-30 04:56:38', '2008-11-30 04:56:32', '2008-11-30 04:56:38'), (2, 1, 'user', '$1$bO..IR4.$CxjJBjKJ5QW2/BaYKDS7f.', 'user@localhost.com', 0, NULL, NULL, NULL, NULL, '127.0.0.1', '2008-12-01 14:04:14', '2008-12-01 14:01:53', '2008-12-01 14:04:14');

-- --------------------------------------------------------

--- Table structure for table `user_autologin` --

CREATE TABLE IF NOT EXISTS `user_autologin` ( `key_id` char(32) collate utf8_bin NOT NULL, `user_id` mediumint(8) NOT NULL default '0', `user_agent` varchar(150) collate utf8_bin NOT NULL, `last_ip` varchar(40) collate utf8_bin NOT NULL, `last_login` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`key_id`,`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- --------------------------------------------------------

--- Table structure for table `user_profile` --

CREATE TABLE IF NOT EXISTS `user_profile` ( `id` int(11) NOT NULL auto_increment,

10

`user_id` int(11) NOT NULL, `country` varchar(20) collate utf8_bin default NULL, `website` varchar(255) collate utf8_bin default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=2 ;

--- Dumping data for table `user_profile` --

INSERT INTO `user_profile` (`id`, `user_id`, `country`, `website`) VALUES (1, 1, NULL, NULL);

-- --------------------------------------------------------

--- Table structure for table `user_temp` --

CREATE TABLE IF NOT EXISTS `user_temp` ( `id` int(11) NOT NULL auto_increment, `username` varchar(255) collate utf8_bin NOT NULL, `password` varchar(34) collate utf8_bin NOT NULL, `email` varchar(100) collate utf8_bin NOT NULL, `activation_key` varchar(50) collate utf8_bin NOT NULL, `last_ip` varchar(40) collate utf8_bin NOT NULL, `created` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;

11

Getting Started
After you follow installation with example and setting DX Auth config file, you might just want to see DX Auth bundled examples live in action, instead of reading the simple example first. To do that you can open:

{your CI url}/auth/login/ to login. {your CI url}/auth/logout/ to logout. {your CI url}/auth/register/ to register. {your CI url}/auth/register_recaptcha/ to register using reCAPTCHA. {your CI url}/auth/forgot_password/ to use forgot password feature. {your CI url}/auth/change_password/ to change password after you logged in. {your CI url}/auth/cancel_account/ to delete account after you logged in.

To access admin control panel (You need to logged in as admin or your user role is granted in permissions table.):

{your CI url}/backend/users/ to manage users. {your CI url}/backend/unactivated_users/ to manage unactivated users. {your CI url}/backend/roles/ to manage roles. {your CI url}/backend/uri_permissions/ to manage URI permissions. {your CI url}/backend/custom_permissions/ to manage custom permissions.

Typically {your CI url} is combination of 'base_url' and 'index_page' in your CI config file.

Main functions
This is the function list you can use in DX Auth library.

login($login, $password, $remember = TRUE)


Login user. If login succeed, returning TRUE, else FALSE. $login is username or email address or both depend on setting in dx_auth config file. $password is user password. $remember is remember user next time they open the website (remember me feature). If function returning FALSE you can use get_auth_error() function to return error string.

logout()
Logout user.

12

register($username, $password,$email)
Register new user. If register succeed, return new user record, else return FALSE. If DX_email_activation value in dx_auth config file is TRUE then it will email activation, and requires user to activate the account. If DX_email_activation is FALSE and DX_email_account_details value in dx_auth config file is TRUE then it will email user account details. This function will automatically set new registered user role_id to 1, so you need to make sure record in roles table which have id = 1, it's name field is 'normal user' or something similar.

forgot_password($login)
Sending an email with a key to reset their password. If succeed return TRUE else return FALSE. $login is username or email. Since password is encrypted in one way in one way, it's not possible to retreive back password. That's why we need to reset it. If function returning FALSE you can use get_auth_error() function to return error string.

reset_password($username, $key = '')


Reset password based on username and key. Usually combined with forgot_password() function. If succeed return TRUE else return FALSE.

activate($username, $key = '')


Activate user based on username and key. It's used to activate user account after registration if DX_email_verification is set to TRUE in dx_auth config file.

change_password($old_pass, $new_pass)
Change password of current logged in user. Make sure you check if user already logged in before calling this function. If succeed return TRUE else return FALSE. If function returning FALSE you can use get_auth_error() function to return error string.

cancel_account($password)
Delete current logged in user from database. Make sure you check if user already logged in before calling this function. If succeed return TRUE else return FALSE.

13

If function returning FALSE you can use get_auth_error() function to return error string.

get_user_id()
Return user id, only if user already logged in.

get_username()
Return username, only if user already logged in.

get_role_id()
Return user role id, only if user already logged in.

get_role_name()
Return user role name, only if user already logged in.

is_admin()
Check if user is admin, only if user already logged in. If user role id is the same value with role_id field which have 'admin' string (case insensitive) in name field in roles table, function will return TRUE.

is_role($roles = array(), $use_role_name = TRUE, $check_parent = TRUE)


Check if user has $roles privilege. If $use_role_name = TRUE then $roles is role name such as 'admin', 'editor', 'etc', else $roles is role_id such as 0, 1, 2. If $check_parent is TRUE means if roles not found in user role, it will check if user role parent has that roles. You can pass an array or a string in $roles parameter. For example: view plaincopy to clipboardprint?

1. if ($this->dx_auth->is_role('admin'))
2. {

3.

// Do something

14

4. } 5.

6. if ($this->dx_auth->is_role(array('admin', 'moderator'))
7. {

8.
9. } 10.

// Do something

11. // Using an Role ID as $roles parameter 12. if ($this->dx_auth->is_role('1', FALSE))


13.{

14.
15.} 16.

// Do something

17. if ($this->dx_auth->is_role(array('1', '2'), FALSE))


18.{

19.
20.}

// Do something

is_logged_in()
Check if user already logged in.

is_banned()
Check if user is a banned user. You should only call this function after you call login() function. So if login() function returning FALSE, you can check if user is banned or not using this function.

get_ban_reason()
Get ban reason of a banned user. You should only call this function after you call login() function. So if login() function returning FALSE, and if user is banned, you can user this function to get the reason.

is_username_available($username)

15

Check if username is available to use, by making sure there is no same username in the database. Typical usage of this function is in form validation callback function.

is_email_available($email)
Check if email is available to use, by making sure there is no same email in the database. Typical usage of this function is in form validation callback function.

get_auth_error()
Get an error message when login(), forgot_password(), change_password(), cancel_account() function is returning FALSE.

is_max_login_attempts_exceeded()
Check if login attempts is more than max login attempts specified in dx_auth config file. Login attempt increase count based on login attempted by IP address.

check_uri_permissions($allow = TRUE)
This will check if current logged in user is allowed to access current URI, based on his role, or his parent role. Here is the detail what happen when you call this function: First, function will check if user is logged in or not, if user haven't login then it will redirect to login URI. But if user is logged in, then it will check if user is admin. If user is admin, then it is allowed to access the URI. But if user is not admin, it will check if user role and parent role is allowed to accesss current URI based on URI rule in permissions table in database. If user is not allowed, it will redirect to deny access URI. You can call check_uri_permissions() in the controller constructor to protect the whole controller. view plaincopy to clipboardprint?

1. class Home extends Controller


2. {

3.
4. 5. 6.

function Home() { parent::Controller();

16

7.
8. 9. } }

$this->dx_auth->check_uri_permissions();

Or use it within a function view plaincopy to clipboardprint?

1. function hello_world()
2. {

3.
4.

$this->dx_auth->check_uri_permissions();

5.
6. }

// Do something

Case example:
There is a user with role_id = 1 (normal user). And then in permissions table, there is a record specify role_id = 1 have permission URI to access '/test/' URI. Now this user want to access uri '/test/hi/'. If you have code like this in Test controller : view plaincopy to clipboardprint?

1. class Test extends Controller


2. {

3.
4. 5. 6.

function Test() { parent::Controller();

7. 8.
9. 10. }

// Secure controller $this->dx_auth->check_uri_permissions();

11.
12.

function hi() { echo 'Hi'; }

13.
14. 15.

16.
17.

function hello() {

17

18.
19. 20.} }

echo 'Hello';

This user will pass the check and access '/test/hi/' URI, and echo 'Hi'. Because if permission URI set to '/test/', it means grant access to class Test and all it's function. If you want to limit role access to function only, you can specify '/class/function/' when setting permission URI. For example, in previous case example if you change role_id = 1 URI permission to '/test/hi/', user will able to access 'test/hi/' URI, but cannot access 'test/hello/' URI. You also can set URI permission to '/' to enable role access all URI. It is possible to reverse all this explanation by specifiying $allow = TRUE when calling check_uri_permissions(). So instead of allowing user to access URI when URI permission found, it will disallow user to access URI when URI permission found. To set URI permission, you have to use function given in permissions model, or make your own. See the example on how to set the permission. For CL Auth user, notice that URI permission now renamed to '/class/function/' instead of '/class/function'.

Inheritance
If user role have parent role, then user also have access to parent role, and so on. To describe this, let's have this URI Permission illustration.
User { '/home/' '/help/' }

Moderator: User { '/moderator/' }

Super_Moderator: Moderator { '/super/'

18

Big_Moderator: Moderator { '/big/' }

This means, Super_Moderator role can access Moderator and User URI, but cannot access Big_Moderator URI. To use this feature, you need to specify parent for each role in parent_id field in roles table. In previous case, here is the illustration of the roles table
id parent_id name ------------------------1 2 3 4 5 0 0 1 3 3 User Admin Moderator Super Moderator Big Moderator

Note Using this function is optional, you might don't want to use it if you pretty comfortable checking the user manually using function like is_admin(), is_role(), is_logged_in(), etc.

get_permission_value($key, $check_parent = TRUE)


Get permission value from specified key. Call this function only when user is logged in already. $key is permission array key (Note: permissions is saved as array in table). If $check_parent is TRUE means if permission value not found in user role, it will try to get permission value from parent role. Returning value if permission found, otherwise returning NULL. To set permission, you have to use function given in permissions model, or make your own. See the example on how to set the permission. Note Using this function is optional, you might don't want to use it if you pretty comfortable checking the user manually, and give permission manually using function like is_admin(), is_role(), etc.

get_permissions_value($key, $array_key = 'default')


19

Get permissions value from specified key. Call this function only when user is logged in already. This function will search key in user permission, and it's parents permissions. $key is permission array key (Note: permissions is saved as array in table). $array_key = 'default'. Retrurning array ordered using 0, 1, 2 as array key. $array_key = 'role_id'. Retrurning array ordered using role_id as array key. $array_key = 'role_name'. Retrurning array ordered using role_name as array key. Returning array of value if permission found, otherwise returning NULL. To set permission, you have to use function given in permissions model, or make your own. See the example on how to set the permission. Note Using this function is optional, you might don't want to use it if you pretty comfortable checking the user manually, and give permission manually using function like is_admin(), is_role(), etc.

deny_access($uri = 'deny')
Calling this function will redirect user depending on $uri variable. Default $uri is 'deny' $uri = 'deny' will redirect user to 'DX_deny_uri' specified in dx_auth config file. $uri = 'login' will redirect user to 'DX_login_uri' specified in dx_auth config file. $uri = 'banned' will redirect user to 'DX_banned_uri' specified in dx_auth config file.

catpcha()
Creating a captcha to be used in form validation.

get_catpcha_image()
Get HTML image of created catpcha. Use this function in view file.

is_captcha_expired()
Check if created captcha already expired or not. Use this in callback form validation function.

is_captcha_match($code)
Check if created catpcha text match with the $code. Use this in callback form validation function.

reCAPTCHA functions
Below is reCAPTCHA function list. Because of name limitation in reCAPTCHA API (everything should have fixed name), reCAPTCHA function is separated from native DX Auth captcha.

20

To use reCAPTCHA function you have to set DX_recaptcha_public_key and DX_recaptcha_private_key in dx_auth config file. To get the key you can register at reCAPTCHA website. You can find an example to use reCAPTCHA in registration here.

get_recaptcha_reload_link($text = 'Get another CAPTCHA')


Get reCAPTCHA reload captcha link, with $text as anchor text. Use this function in view file.

get_recaptcha_switch_image_audio_link($switch_image_text = 'Get an image CAPTCHA', $switch_audio_text = 'Get an audio CAPTCHA')


Get reCAPTCHA switch image or audio link. Use this function in view file.

get_recaptcha_label($image_text = 'Enter the words above', $audio_text = 'Enter the numbers you hear')
Get reCAPTCHA label telling user to input captcha in the inputbox. Use this function in view file.

get_recaptcha_input()
Get reCAPTCHA input box to input captcha. Use this function in view file. You should use this function, otherwise reCAPTCHA image won't show up because reCAPTCHA javascript will try to find this input box.

get_recaptcha_image()
Get reCATPCHA image. Use this function in view file.

get_recaptcha_html()
Get reCAPTCHA javascript and non javasript html. Use this function in view file. This is the main part of reCAPTCHA function. Call this function after you are using some or all get_recaptcha_xxx function above. Meaning this function should be called the last.

is_recaptcha_match()
Check if created reCAPTCHA text match with the text that user inputed in get_recaptcha_input() function. Use this in callback form validation function.

21

check_role_uri()
This function is obsolete in version 1.0.2 above. Use check_uri_permissions() to have same effect with new permission table.

Events
Event are function that triggered when specific function in DX Auth library is called. To use these event you need to open 'libraries/DX_Auth_Event.php', and put your code there. Here is the events that you can use in DX Auth library.

user_activated($user_id)
If 'DX_email_activation' in config is TRUE, this event occurs right after user succesfully activated using specified key in their email. If 'DX_email_activation' in config is FALSE, this event occurs right after user succesfully registered. $user_id is id of user that activated. By default, there is codes here to create user profile. If you don't need user profile, you can delete the codes.

user_logged_in($user_id)
This event occurs right after user login. $user_id is id of user that login.

user_logging_out($user_id)
This event occurs right before user logout. $user_id is id of user that logout.

user_changed_password($user_id, $new_password)
This event occurs right after user change password. $user_id is id of user that change password, $new_password is the new password.

user_canceling_account($user_id)
This event occurs right before user account is canceled. $user_id is id of user that cancel his account. By default, there is codes here to delete user profile. If you don't need user profile, you can delete the codes.

22

checked_uri_permissions($user_id, &$allowed)
This event occurs when check_uri_permissions() function in DX_Auth is called, after checking if user role is allowed or not to access URI, this event will be triggered. $allowed is result of the check before, it's possible to alter the value since it's passed by reference.

got_permission_value($user_id, $key)
This event occurs when get_permission_value() function in DX_Auth is called.

got_permissions_value($user_id, $key)
This event occurs when get_permissions_value() function in DX_Auth is called.

sending_account_email($data, &$content)
This event occurs right before dx auth send email with account details. $data is an array, containing username, password, email, and last_ip. $content is email content, passed by reference. By default there is example code how to create content here. You can change it to fit your needs.

sending_activation_email($data, &$content)
This event occurs right before dx auth send activation email. $data is an array, containing username, password, email, last_ip, activation_key, activate_url. $content is email content, passed by reference. By default there is example code how to create content here. You can change it to fit your needs.

sending_forgot_password_email($data, &$content)
This event occurs right before dx auth send forgot password request email. $data is an array, containing password, key, and reset_password_uri. $content is email content, passed by reference. By default there is example code how to create content here. You can change it to fit your needs.

Config
This is the config in DX Auth library. You can see the explanation is commented in the code.

23

view plaincopy to clipboardprint?

1. /* 2. | ------------------------------------------------------------------3. | DX Auth Config 4. | ------------------------------------------------------------------5. */


6.

7. /* 8. |-------------------------------------------------------------------------9. | Website details 10. |-------------------------------------------------------------------------11. | 12. | These details are used in email sent by DX Auth library. 13. | 14. */
15.

16. $config['DX_website_name'] = 'Your Website'; 17. $config['DX_webmaster_email'] = 'webmaster@yourhost.com';


18.

19. /* 20. |-------------------------------------------------------------------------21. | Database table 22. |-------------------------------------------------------------------------23. | 24. | Determines table that used by DX Auth. 25. | 26. | 'DX_table_prefix' allows you to specify table prefix that will be use by the rest of the table. 27. | 28. | For example specifying 'DX_' in 'DX_table_prefix' and 'users' in 'DX_users_table', 29. | will make DX Auth user 'DX_users' as users table. 30. | 31. */
32.

33. $config['DX_table_prefix'] = ''; 34. $config['DX_users_table'] = 'users'; 24

35. $config['DX_user_profile_table'] = 'user_profile'; 36. $config['DX_user_temp_table'] = 'user_temp'; 37. $config['DX_user_autologin'] = 'user_autologin'; 38. $config['DX_roles_table'] = 'roles'; 39. $config['DX_permissions_table'] = 'permissions'; 40. $config['DX_login_attempts_table'] = 'login_attempts';
41.

42. /* 43. |-------------------------------------------------------------------------44. | Password salt 45. |-------------------------------------------------------------------------46. | 47. | You can add major salt to be hashed with password. 48. | For example, you can get salt from here: https://www.grc.com/passwords.htm 49. | 50. | Note: 51. | 52. | Keep in mind that if you change the salt value after user registered, 53. | user that previously registered cannot login anymore. 54. | 55. */
56.

57. $config['DX_salt'] = '';


58.

59. /* 60. |-------------------------------------------------------------------------61. | Registration related settings 62. |-------------------------------------------------------------------------63. | 64. | 'DX_email_activation' = Requires user to activate their account using email after registration. 65. | 'DX_email_activation_expire' = Time before users who don't activate their account getting del
eted from database. Default is 48 Hours (60*60*24*2).

66. | 'DX_email_account_details' = Email account details after registration, only if 'DX_email_activa


tion' is FALSE.

67. | 68. */ 25

69.

70. $config['DX_email_activation'] = TRUE; 71. $config['DX_email_activation_expire'] = 60*60*24*2; 72. $config['DX_email_account_details'] = TRUE;


73.

74. /* 75. |-------------------------------------------------------------------------76. | Login settings 77. |-------------------------------------------------------------------------78. | 79. | 'DX_login_using_username' = Determine if user can use username in username field to login. 80. | 'DX_login_using_email' = Determine if user can use email in username field to login. 81. | 82. | You have to set at least one of settings above to TRUE. 83. | 84. | 'DX_login_record_ip' = Determine if user IP address should be recorded in database when user
login.

85. | 'DX_login_record_time' = Determine if time should be recorded in database when user login. 86. | 87. */
88.

89. $config['DX_login_using_username'] = TRUE; 90. $config['DX_login_using_email'] = TRUE; 91. $config['DX_login_record_ip'] = TRUE; 92. $config['DX_login_record_time'] = TRUE;
93.

94. /* 95. |-------------------------------------------------------------------------96. | Auto login settings 97. |-------------------------------------------------------------------------98. | 99. | 'DX_autologin_cookie_name' = Determine auto login cookie name. 100. 101. 102.
| 'DX_autologin_cookie_life' = Determine auto login cookie life before expired. Default is 2 months (60*60*24*31*2). | */

26

103.

104. 105.
106.

$config['DX_autologin_cookie_name'] = 'autologin'; $config['DX_autologin_cookie_life'] = 60*60*24*31*2;

107. 108. 109. 110. 111. 112. 113. 114. 115.


116.

/* |-------------------------------------------------------------------------| Login attempts |-------------------------------------------------------------------------|

| 'DX_count_login_attempts' = Determine if DX Auth should count login attempt when us er failed to login. | 'DX_max_login_attempts' = Determine max login attempt before function is_login_atte mpt_exceeded() returning TRUE. | */

117. 118.
119.

$config['DX_count_login_attempts'] = TRUE; $config['DX_max_login_attempts'] = 1;

120. 121. 122. 123. 124. 125. 126. 127.


128.

/* |-------------------------------------------------------------------------| Forgot password settings |-------------------------------------------------------------------------|

| 'DX_forgot_password_expire' = Time before forgot password key become invalid. Defau lt is 15 minutes (900 seconds). | */

129.
130.

$config['DX_forgot_password_expire'] = 900;

131. 132. 133. 134. 135.

/* |-------------------------------------------------------------------------| Captcha |-------------------------------------------------------------------------|

27

136. 137. 138. 139. 140. 141. 142. 143. 144.


145.

| You can set catpcha that created by DX Auth library in here. | 'DX_captcha_directory' = Name of directory where the catpcha will be created. | 'DX_captcha_fonts_path' = Font in this directory will be used when creating captcha.

| 'DX_captcha_font_size' = Font size when writing text to captcha. Leave blank for rando m font size. | 'DX_captcha_grid' = Show grid in created captcha.

| 'DX_captcha_expire' = Life time of created captcha before expired, default is 3 minutes (180 seconds). | 'DX_captcha_expire' = Determine captcha case sensitive or not. | */

146. 147. 148. 149. 150. 151. 152. 153.


154.

$config['DX_captcha_directory'] = 'captcha'; $config['DX_captcha_fonts_path'] = $config['DX_captcha_path'].'fonts'; $config['DX_captcha_width'] = 320; $config['DX_captcha_height'] = 95; $config['DX_captcha_font_size'] = ''; $config['DX_captcha_grid'] = TRUE; $config['DX_captcha_expire'] = 180; $config['DX_captcha_case_sensitive'] = TRUE;

155. 156. 157. 158. 159. 160. 161. 162. 163.


164.

/* |-------------------------------------------------------------------------| reCAPTCHA |-------------------------------------------------------------------------| | If you are planning to use reCAPTCHA function, you have to set reCAPTCHA key here | You can get the key by registering at http://recaptcha.net | */

165. 166.
167. 168.

$config['DX_recaptcha_public_key'] = ''; $config['DX_recaptcha_private_key'] = '';

169.

/*

28

170. 171. 172. 173. 174. 175. 176. 177. 178. 179. 180. 181.
oller.

|-------------------------------------------------------------------------| URI |-------------------------------------------------------------------------| | Determines URI that used for redirecting in DX Auth library. | 'DX_deny_uri' = Forbidden access URI. | 'DX_login_uri' = Login form URI. | 'DX_activate_uri' = Activate user URI. | 'DX_reset_password_uri' = Reset user password URI. | | These value can be accessed from DX Auth library variable, by removing 'DX_' string. | For example you can access 'DX_deny_uri' by using $this->dx_auth->deny_uri in contr | */

182. 183.
184.

185. 186. 187. 188. 189.


190. 191.

$config['DX_deny_uri'] = '/auth/deny/'; $config['DX_login_uri'] = '/auth/login/'; $config['DX_banned_uri'] = '/auth/banned/'; $config['DX_activate_uri'] = '/auth/activate/'; $config['DX_reset_password_uri'] = '/auth/reset_password/';

192. 193. 194. 195. 196. 197. 198. 199. 200. 201. 202.

/* |-------------------------------------------------------------------------| Helper configuration |-------------------------------------------------------------------------| | Configuration below is actually not used in function in DX_Auth library. | | | | However they can be accessed from DX Auth library variable, by removing 'DX_' string. They just used to help you coding more easily in controller. You can set it to blank if you don't need it, or even delete it.

| For example you can access 'DX_register_uri' by using $this->dx_auth->register_uri in controller.

29

203. 204.
205.

| */

206. 207. 208.


209.

// Registration $config['DX_allow_registration'] = TRUE; $config['DX_captcha_registration'] = TRUE;

210. 211.
212.

// Login $config['DX_captcha_login'] = FALSE;

213. 214. 215. 216. 217. 218.


219.

// URI Locations $config['DX_logout_uri'] = '/auth/logout/'; $config['DX_register_uri'] = '/auth/register/'; $config['DX_forgot_password_uri'] = '/auth/forgot_password/'; $config['DX_change_password_uri'] = '/auth/change_password/'; $config['DX_cancel_account_uri'] = '/auth/cancel_account/';

220. 221. 222. 223. 224. 225.


226.

// Forms view $config['DX_login_view'] = 'auth/login_form'; $config['DX_register_view'] = 'auth/register_form'; $config['DX_forgot_password_view'] = 'auth/forgot_password_form'; $config['DX_change_password_view'] = 'auth/change_password_form'; $config['DX_cancel_account_view'] = 'auth/cancel_account_form';

227. 228. 229. 230. 231.


232.

// Pages view $config['DX_deny_view'] = 'auth/general_message'; $config['DX_banned_view'] = 'auth/general_message'; $config['DX_logged_in_view'] = 'auth/general_message'; $config['DX_logout_view'] = 'auth/general_message';

233. 234. 235. 236. 237.

$config['DX_register_success_view'] = 'auth/general_message'; $config['DX_activate_success_view'] = 'auth/general_message'; $config['DX_forgot_password_success_view'] = 'auth/general_message'; $config['DX_reset_password_success_view'] = 'auth/general_message'; $config['DX_change_password_success_view'] = 'auth/general_message';

30

238.

239. 240. 241.

$config['DX_register_disabled_view'] = 'auth/general_message'; $config['DX_activate_failed_view'] = 'auth/general_message'; $config['DX_reset_password_failed_view'] = 'auth/general_message';

Models
DX Auth library ships with few models file, which is located in 'models/dx_auth/' folder. These model contain functions to work with specified table. You can use the function in these model, for example to build your own admin panel. Function name in these model is also self explanatiory so it's easy to use. Here is the list of models included in 'models/dx_auth/' folder:

users.php contain functions to work with 'DX_users_table' table. user_profile.php contain functions to work with 'DX_user_profile_table' table. user_temp.php contain functions to work with 'DX_user_temp_table' table. user_autologin.php contain functions to work with 'DX_user_autologin' table. roles.php contain functions to work with 'DX_roles_table' table. permissions.php contain functions to work with 'DX_permissions_table' table. login_attempts.php contain functions to work with 'DX_login_attempts_table' table.

Tables anatomy
These are the table installed in DX Auth library and here is the explanation for each field.

users table
This is the main table, users are recorded in here.

id = Primary key. role_id = Foreign key to roles table. Default is 1. username = Username. password = User password (encrypted). email = User email. banned = Determine if user is banned or not (1 = banned, 0 = not banned). Default is 0. ban_reason = Reason why user is banned. newpass = New password after user request forgot password. newpass_key = Key to change password. If key is verified by reset_password() function, it will replace 'password' field with 'newpass' field value. newpass_time = Time when forgot password is requested.

31

last_ip = IP address of user when register. Then if 'DX_login_record_ip' is TRUE, every time user login his IP will be recorded here. last_login = if 'DX_login_record_time' is TRUE, login time will be recorded here. created = Time when this record is created, normally you can use this to determine when user is registered. modified = Time when this record is modified.

Username field shoudn't contain space and other vulnerable character. Therefore when you validate username in registration, it's highly recommended you use alpha_dash in your form validation.

user_temp table
This table is for users who haven't activated their account.

id = Primary key. username = Username. password = User password (encrypted). email = User email. activation_key = Key needed to activate user. User who activated will be moved to users table. last_ip = IP address of user when register. created = Date time when this record is created.

If 'DX_email_activation' is TRUE, people who have registered is inserted into this table instead of users table. If they activate their account, the record will be moved into users table.

user_profile table
This table is for user profile.

id = Primary key. user_id = Foreign key to users table. Other field is up to you. You can add or delete to fit your needs.

user_autologin table
This table is to save autologin variable when user login, to verify it with autologin cookies.

key_id = Primary key, key_id was created with unique string when user login using remember TRUE. user_id = Primary key, user id of user when login using remember TRUE. user_agent = User agent of browser when user login using remember TRUE.

32

last_ip = User IP address when user login using remember TRUE. last_login = Time when user login using remember TRUE.

Normally, you won't need to touch with this table.

roles table
This table is records of role name such as registered user, admin, moderator, etc.

id = Primary key. parent_id = Self reference to id. Which mean this role will inherit parent_id role. Default is 0 (No parent). name = Role name.

You need to have minimum 2 records in here. First, record which have id = 1 must be named 'registered user' or something similar, since users table will automatically set role_id = 1 when record is created. And another one must have 'admin' (case insensitive) in name field while it's id is not important. If you don't plan to use permissions feature, you don't need to care about parent_id just leave it as 0. But if you do, you can check function check_uri_permissions() in function guide to know what's the effect of having parent_id.

permissions table

id = Primary key. role_id = Foreign key to roles table. data(text) = Permission data. Permission data is saved as array which converted into string.

check_uri_permission(), get_permission_value(), get_permissions_value() relying on this table. To set the data, you have to use function given in permissions model, or make your own. See the example on how to set the permission.

login_attempts table
This table log login attempted by people.

id = Primary key. ip_address = IP address of someone who try to login. time = Time when someone who try to login.

33

DX Auth will only use this table when 'DX_count_login_attempts' is set to TRUE in config file. And if login attempts for same IP is more than 'DX_max_login_attempts' in config file, it will not count that IP anymore.

role_uri table
Obsolete in 1.0.2 above. Use permissions table.

Troubleshooting
DX Auth library might failed sending email if you didn't set the email setting well. If that's happened, you need to create email.php in application/config/ folder, and paste following code. Edit it to fit your needs.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$config['protocol'] = 'smtp'; $config['smtp_host'] = 'mail.localhost.com'; $config['smtp_user'] = 'username'; $config['smtp_pass'] = 'password'; $config['smtp_port'] = '25';

For more information about this, you can consult Code Igniter email helper.

Simple example
Before trying the example make sure you have follow installation instruction first. Using DX Auth library it's pretty straight forward and simple, for example let's create a class named Auth in Auth controller. view plaincopy to clipboardprint?

1. class Auth extends Controller


2. {

3.
4. 5.

function Auth() { parent::Controller(); // Load library $this->load->library('DX_Auth'); }

6. 7.
8.

34

9.

10.
11.

function login() { // Login using username 'test' and password 'helloworld' $this->dx_auth->login('test', 'helloworld'); }

12. 13.
14. 15.

16.
17.

function logout() { // Logout user $this->dx_auth->logout(); }

18. 19.
20. 21.

22.
23.

function register() { // Register a user with username 'john', password 'johnpassword', and email 'john@yourm ail.com' if ($user = $this->dx_auth->register('john', 'johnpassword', 'john@yourmail.com')) { echo 'Welcome '.$user->username; } else { echo 'Failed to register'; } }

24. 25.
26.

27.
28.

29.
30.

31.
32. 33. 34.

35.
36.

function hello() { // Check if user is logged in or not if ($this->dx_auth->is_logged_in()) { echo 'Hello world'; } else {

37. 38.
39.

40.
41.

42.
43.

35

44.
45. 46. 47.} } }

echo 'Not logged in';

By just looking these example, i think you already get a grip how easy and simple to use DX Auth library. If you are interested, here is the more advanced example.

Advanced example
This is more advanced, and how DX Auth should be implemented. You can see explanation commented in source code. view plaincopy to clipboardprint?

1. class Auth extends Controller


2. {

3. 4. 5. 6. 7.
8.

// Used for registering and changing password form validation var $min_username = 4; var $max_username = 20; var $min_password = 4; var $max_password = 20;

9.
10. 11. 12.

function Auth() { parent::Controller();

13. 14.
15.

$this->load->library('Form_validation'); $this->load->library('DX_Auth');

16. 17.
18. 19. }

$this->load->helper('url'); $this->load->helper('form');

20.
21.

function index() { $this->login(); }

22.
23. 24.

36

25.
26.

/* Callback function */

27.
28.

function username_check($username) { $result = $this->dx_auth->is_username_available($username); if ( ! $result) { $this->form_validation->set_message('username_check', 'Username already exist. Plea se choose another username.'); }

29. 30.
31.

32.
33. 34.

35.
36. 37. }

return $result;

38.
39.

function email_check($email) { $result = $this->dx_auth->is_email_available($email); if ( ! $result) { $this->form_validation->set_message('email_check', 'Email is already used by another user. Please choose another email address.'); }

40. 41.
42.

43.
44. 45.

46.
47. 48. }

return $result;

49.
50.

function captcha_check($code) { $result = TRUE;

51.
52.

53.
54.

if ($this->dx_auth->is_captcha_expired()) { // Will replace this error msg with $lang $this->form_validation->set_message('captcha_check', 'Your confirmation code has ex pired. Please try again.'); $result = FALSE; }

55. 56. 57.


58.

37

59.
60.

elseif ( ! $this->dx_auth->is_captcha_match($code)) { $this->form_validation->set_message('captcha_check', 'Your confirmation code does n ot match the one in the image. Try again.'); $result = FALSE; }

61. 62.
63. 64.

65.
66. 67. }

return $result;

68.
69.

/* End of Callback function */

70.
71.

function login() { if ( ! $this->dx_auth->is_logged_in()) { $val = $this->form_validation;

72.
73.

74.
75.

76. 77. 78. 79.


80.

// Set form validation rules $val->set_rules('username', 'Username', 'trim|required|xss_clean'); $val->set_rules('password', 'Password', 'trim|required|xss_clean'); $val->set_rules('remember', 'Remember me', 'integer');

81. 82.
83.

// Set captcha rules if login attempts exceed max attempts in config if ($this->dx_auth->is_max_login_attempts_exceeded()) { $val->set_rules('captcha', 'Confirmation Code', 'trim|required|xss_clean| callback_captcha_check'); }

84.
85. 86.

87.
88.

if ($val->run() AND $this->dx_auth->login($val->set_value('username'), $val>set_value('password'), $val->set_value('remember'))) { // Redirect to homepage redirect('', 'location'); } else

89. 90.
91.

92.

38

93.

{ // Check if the user is failed logged in because user is banned user or not if ($this->dx_auth->is_banned()) { // Redirect to banned uri $this->dx_auth->deny_access('banned'); } else { // Default is we don't show captcha until max login attempts eceeded $data['show_captcha'] = FALSE;

94. 95.
96.

97. 98.
99.

100.
101.

102. 103.
104.

105. 106.
107.

// Show captcha if login attempts exceed max attempts in config if ($this->dx_auth->is_max_login_attempts_exceeded()) { // Create catpcha $this->dx_auth->captcha();

108. 109.
110.

111. 112.
113. 114. }

// Set view data to show captcha on view file $data['show_captcha'] = TRUE;

115. 116.
117. 118. 119. } else { } }

// Load login page view $this->load->view($this->dx_auth->login_view, $data);

120.
121.

122. 123.
124. 125. 126. } }

$data['auth_message'] = 'You are already logged in.'; $this->load->view($this->dx_auth->logged_in_view, $data);

127.
128.

function logout() {

39

129.
130.

$this->dx_auth->logout();

131. 132.
133. 134. }

$data['auth_message'] = 'You have been logged out.'; $this->load->view($this->dx_auth->logout_view, $data);

135.
136.

function register() { if ( ! $this->dx_auth->is_logged_in() AND $this->dx_auth->allow_registration) { $val = $this->form_validation;

137.
138.

139.
140.

141. 142.

// Set form validation rules

$val->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['. $this->min_username.']|max_length['.$this->max_username.']|callback_username_check| alpha_dash'); $val->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['. $this->min_password.']|max_length['.$this->max_password.']|matches[confirm_password]'); $val->set_rules('confirm_password', 'Confirm Password', 'trim|required|

143.

144.
xss_clean');

145.

$val->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email| callback_email_check');

146.

147.
148.

if ($this->dx_auth->captcha_registration) {

149.

$val->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required| callback_captcha_check'); }

150. 151.

152. 153.

// Run form validation and register user if it's pass the validation

if ($val->run() AND $this->dx_auth->register($val->set_value('username'), $va l->set_value('password'), $val->set_value('email'))) { // Set success message accordingly if ($this->dx_auth->email_activation) {

154.

155. 156.
157.

158.

$data['auth_message'] = 'You have successfully registered. Check your em ail address to activate your account.';

40

159.

} else {

160.
161.

162.

$data['auth_message'] = 'You have successfully registered. '.anchor(site_u rl($this->dx_auth->login_uri), 'Login'); }

163. 164.

165. 166.
167. }

// Load registration success page $this->load->view($this->dx_auth->register_success_view, $data);

168.
169.

else { // Is registration using captcha if ($this->dx_auth->captcha_registration) { $this->dx_auth->captcha(); }

170. 171.
172.

173.
174. 175.

176. 177.
178. 179. } }

// Load registration page $this->load->view($this->dx_auth->register_view);

180.
181.

elseif ( ! $this->dx_auth->allow_registration) { $data['auth_message'] = 'Registration has been disabled.'; $this->load->view($this->dx_auth->register_disabled_view, $data); } else { $data['auth_message'] = 'You have to logout first, before registering.'; $this->load->view($this->dx_auth->logged_in_view, $data); } }

182. 183.
184.

185.
186.

187. 188.
189. 190. 191.

192.
193.

function activate() {

41

194. 195. 196.


197.

// Get username and key $username = $this->uri->segment(3); $key = $this->uri->segment(4);

198. 199.
200.

// Activate user if ($this->dx_auth->activate($username, $key)) {

201. 202.

$data['auth_message'] = 'Your account have been successfully activated. '.ancho r(site_url($this->dx_auth->login_uri), 'Login'); $this->load->view($this->dx_auth->activate_success_view, $data); } else {

203.

204.
205.

206. 207.

$data['auth_message'] = 'The activation code you entered was incorrect. Please check your email again.'; $this->load->view($this->dx_auth->activate_failed_view, $data); } }

208. 209. 210.

211.
212.

function forgot_password() { $val = $this->form_validation;

213.
214.

215. 216.
217.

// Set form validation rules $val->set_rules('login', 'Username or Email address', 'trim|required|xss_clean');

218. 219.
220.

// Validate rules and call forgot password function if ($val->run() AND $this->dx_auth->forgot_password($val->set_value('login'))) {

221. 222.

$data['auth_message'] = 'An email has been sent to your email with instructions with how to activate your new password.'; $this->load->view($this->dx_auth->forgot_password_success_view, $data); } else { $this->load->view($this->dx_auth->forgot_password_view);

223.

224.
225.

226.

42

227. 228. 229. }

230.
231.

function reset_password() { // Get username and key $username = $this->uri->segment(3); $key = $this->uri->segment(4);

232. 233. 234.


235.

236. 237.
238.

// Reset password if ($this->dx_auth->reset_password($username, $key)) {

239. 240.

$data['auth_message'] = 'You have successfully reset you password, '.anchor(sit e_url($this->dx_auth->login_uri), 'Login'); $this->load->view($this->dx_auth->reset_password_success_view, $data); } else {

241.

242.
243.

244. 245.

$data['auth_message'] = 'Reset failed. Your username and key are incorrect. Ple ase check your email again and follow the instructions.'; $this->load->view($this->dx_auth->reset_password_failed_view, $data); } }

246. 247. 248.

249.
250.

function change_password() { // Check if user logged in or not if ($this->dx_auth->is_logged_in()) { $val = $this->form_validation;

251. 252.
253.

254.
255.

256. 257. 258.

// Set form validation

$val->set_rules('old_password', 'Old Password', 'trim|required|xss_clean| min_length['.$this->min_password.']|max_length['.$this->max_password.']'); $val->set_rules('new_password', 'New Password', 'trim|required|xss_clean| min_length['.$this->min_password.']|max_length['.$this->max_password.']| matches[confirm_new_password]');

43

259.

$val->set_rules('confirm_new_password', 'Confirm new Password', 'trim| required|xss_clean');

260.

261. 262.

// Validate rules and change password

if ($val->run() AND $this->dx_auth->change_password($val>set_value('old_password'), $val->set_value('new_password'))) { $data['auth_message'] = 'Your password has successfully been changed.'; $this->load->view($this->dx_auth->change_password_success_view, $dat } else { $this->load->view($this->dx_auth->change_password_view); } } else { // Redirect to login page $this->dx_auth->deny_access('login'); } }

263.

264. 265.
a);

266.

267.
268.

269.
270. 271.

272.
273.

274. 275.
276. 277. 278.

279.
280.

function cancel_account() { // Check if user logged in or not if ($this->dx_auth->is_logged_in()) { $val = $this->form_validation;

281. 282.
283.

284.
285.

286. 287.
288.

// Set form validation rules $val->set_rules('password', 'Password', "trim|required|xss_clean");

289. 290.

// Validate rules and change password

if ($val->run() AND $this->dx_auth->cancel_account($val>set_value('password'))) {

291.

44

292. 293.
294. }

// Redirect to homepage redirect('', 'location');

295.
296.

else { $this->load->view($this->dx_auth->cancel_account_view); } } else { // Redirect to login page $this->dx_auth->deny_access('login'); } } }

297.
298. 299.

300.
301.

302. 303.
304. 305. 306.

You can find this example in controllers/auth.php that included in DX Auth library download.

Recatpcha example
This is an advanced example how to use reCAPTCHA in registration. Make sure you already insert reCAPTCHA key in config file, if not the example wouldn't work. Here is the controller part. view plaincopy to clipboardprint?

1. class Auth extends Controller


2. {

3. 4. 5. 6. 7.
8.

// Used for registering and changing password form validation var $min_username = 4; var $max_username = 20; var $min_password = 6; var $max_password = 10;

9.
10. 11. 12.

function Auth() { parent::Controller();

13.

$this->load->library('Form_validation');

45

14.
15. 16. }

$this->load->library('DX_auth');

17.
18.

function index() { $this->login(); }

19.
20. 21.

22.
23.

/* Callback function */

24.
25.

function username_check($username) { $result = $this->dx_auth->is_username_available($username); if ( ! $result) { $this->form_validation->set_message('username_check', 'Username already exist. Plea se choose another username.'); }

26. 27.
28.

29.
30. 31.

32.
33. 34. }

return $result;

35.
36.

function email_check($email) { $result = $this->dx_auth->is_email_available($email); if ( ! $result) { $this->form_validation->set_message('email_check', 'Email is already used by another user. Please choose another email address.'); }

37. 38.
39.

40.
41. 42.

43.
44. 45. }

return $result;

46.
47.

function recaptcha_check() {

46

48. 49.
50.

$result = $this->dx_auth->is_recaptcha_match(); if ( ! $result) { $this->form_validation->set_message('recaptcha_check', 'Your confirmation code does not match the one in the image. Try again.'); }

51.
52. 53.

54.
55. 56. }

return $result;

57.
58.

/* End of Callback function */

59.
60.

function register_recaptcha() { if ( ! $this->dx_auth->is_logged_in() AND $this->dx_auth->allow_registration) { $val = $this->form_validation;

61.
62.

63.
64.

65. 66.

// Set form validation rules $val->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this>min_username.']|max_length['.$this->max_username.']|callback_username_check| alpha_dash'); $val->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this>min_password.']|max_length['.$this->max_password.']|matches[confirm_password]'); $val->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean'); $val->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email| callback_email_check');

67. 68. 69.


70.

71. 72.
73.

// Is registration using captcha if ($this->dx_auth->captcha_registration) { // Set recaptcha rules. // IMPORTANT: Do not change 'recaptcha_response_field' because it's used by reCAP TCHA API, // This is because the limitation of reCAPTCHA, not DX Auth library $val->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean| required|callback_recaptcha_check'); }

74. 75. 76. 77.


78.

47

79.

80. 81.
82.

// Run form validation and register user if it's pass the validation if ($val->run() AND $this->dx_auth->register($val->set_value('username'), $val>set_value('password'), $val->set_value('email'))) { // Set success message accordingly if ($this->dx_auth->email_activation) { $data['auth_message'] = 'You have successfully registered. Check your email add ress to activate your account.'; } else { $data['auth_message'] = 'You have successfully registered. '.anchor(site_url($this ->dx_auth->login_uri), 'Login'); }

83. 84.
85.

86.
87.

88.
89.

90.
91. 92.

93. 94.
95. }

// Load registration success page $this->load->view($this->dx_auth->register_success_view, $data);

96.
97.

else { // Load registration page $this->load->view('auth/register_recaptcha_form'); } } elseif ( ! $this->dx_auth->allow_registration) { $data['auth_message'] = 'Registration has been disabled.'; $this->load->view($this->dx_auth->register_disabled_view, $data); } else { $data['auth_message'] = 'You have to logout first, before registering.'; $this->load->view($this->dx_auth->logged_in_view, $data); } }

98. 99.
100. 101.

102.
103.

104. 105.
106.

107.
108.

109. 110.
111. 112.

48

113.

Here is the view part (auth/register_recaptcha_form). view plaincopy to clipboardprint? 1. <?php

2. $username = array( 3. 4. 5. 6.
7. ); 8. 'name' => 'username', 'id' => 'username',

'size' => 30, 'value' => set_value('username')

9. $password = array( 10. 11. 12. 13.


14.); 15. 'name' => 'password', 'id' => 'password',

'size' => 30, 'value' => set_value('password')

16. $confirm_password = array( 17. 18. 19. 20.


21.); 22. 'name' => 'confirm_password', 'id' => 'confirm_password',

'size' => 30, 'value' => set_value('confirm_password')

23. $email = array( 24. 25. 26. 27. 28.


29.); 30.?> 31. 32.<html> 'name' => 'email', 'id' => 'email',

'maxlength' => 80, 'size' => 30, 'value' => set_value('email')

49

33.<body> 34. 35.<fieldset><legend>Register</legend>

36. <?php echo form_open($this->uri->uri_string())?>


37. 38.<dl>

39.
40.

<dt><?php echo form_label('Username', $username['id']);?></dt> <dd> <?php echo form_input($username)?> <?php echo form_error($username['name']); ?>

41. 42.
43. 44. 45.

</dd>

46.
47.

<dt><?php echo form_label('Password', $password['id']);?></dt> <dd> <?php echo form_password($password)?> <?php echo form_error($password['name']); ?>

48. 49.
50. 51. 52.

</dd>

53.
54.

<dt><?php echo form_label('Confirm Password', $confirm_password['id']);?></dt> <dd> <?php echo form_password($confirm_password);?> <?php echo form_error($confirm_password['name']); ?>

55. 56.
57. 58. 59.

</dd>

60.
61.

<dt><?php echo form_label('Email Address', $email['id']);?></dt> <dd> <?php echo form_input($email);?> <?php echo form_error($email['name']); ?>

62. 63.
64. 65. 66.

</dd>

67. <?php if ($this->dx_auth->captcha_registration): ?>


68.

50

69. 70. 71.

<dt></dt> <dd> <?php // Show recaptcha imgage echo $this->dx_auth->get_recaptcha_image(); // Show reload captcha link echo $this->dx_auth->get_recaptcha_reload_link(); // Show switch to image captcha or audio link echo $this->dx_auth->get_recaptcha_switch_image_audio_link(); ?>

72. 73. 74. 75. 76. 77.


78. 79. 80. 81.

</dd>

82.
83.

<dt><?php echo $this->dx_auth->get_recaptcha_label(); ?></dt> <dd> <?php echo $this->dx_auth->get_recaptcha_input(); ?>

84.
85.

86.
87. 88. 89.

<?php echo form_error('recaptcha_response_field'); ?> </dd>

<?php // Get recaptcha javascript and non javasript html echo $this->dx_auth->get_recaptcha_html(); ?>

90. 91.
92.

93. <?php endif; ?>


94. 95. 96. 97. 98. <dt></dt>

99.
100. 101.

<dd><?php echo form_submit('register','Register');?></dd> </dl>

102.
103. 104.

<?php echo form_close()?> </fieldset> </body>

51

105.

</html>

You can find this example in controllers/auth.php and views/auth/register_recaptcha_form.php that included in DX Auth library download.
Top of Page

Permission example
This is an example how to set permission using model. Simple set permission view plaincopy to clipboardprint?

1. // Load model 2. $this->load->model('dx_auth/permissions', 'permissions');


3.

4. // Set permission 'edit' permission to TRUE for role_id = 1. 5. $this->permissions->set_permission_value(1, 'edit', TRUE);
Set permission value at once. view plaincopy to clipboardprint?

1. // Load model 2. $this->load->model('dx_auth/permissions', 'permissions');


3.

4. // Get role_id = 1 permission data first. 5. // So the previously set permission array key won't be overwritten with new array with key $key
only,

6. // when calling set_permission_data later. 7. $permission_data = $this->permissions->get_permission_data(1);


8.

9. // Set value in permission data array 10. $permission_data['edit'] = TRUE; 11. $permission_data['delete'] = FALSE;
12.

13. // Set permission data for role_id = 1 14. $this->permissions->set_permission_data(1, $permission_data);


This is an example how to get the permission using DX Auth, after user already logged in. view plaincopy to clipboardprint?

52

1. if ($this->dx_auth->get_permission_value('edit') != NULL AND $this->dx_auth>get_permission_value('edit')) 2. {

3.
4. }

echo 'Editing is allowed in your role';

5. else
6. {

7.
8. }

echo 'Editing is not allowed in your role';

You can see more of the example, in controllers/backend.php in uri_permissions and custom_permissions function.

53