119764860 dx-auth

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. 1

description

dx_auth (codeigniter authentication plugin) user guide

Transcript of 119764860 dx-auth

Page 1: 119764860 dx-auth

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.

1

Page 2: 119764860 dx-auth

• 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

• License Agreement

• Change Log

• Upgrading from previous version

• Credits

Installation

• Downloading DX Auth

• Installation Instructions

• Database Schema

General Topics

• Getting Started

• Functions

• Events

• Config

• Models

• Tables anatomy

• Troubleshooting

Examples

• Simple example

• Advanced example

• Recaptcha example

• Permission example

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

2

Page 3: 119764860 dx-auth

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.

3

Page 4: 119764860 dx-auth

• '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.

4

Page 5: 119764860 dx-auth

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.

5

Page 6: 119764860 dx-auth

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.

6

Page 7: 119764860 dx-auth

• 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,

7

Page 8: 119764860 dx-auth

`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`

--

8

Page 9: 119764860 dx-auth

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 ;

9

Page 10: 119764860 dx-auth

--

-- 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.', '[email protected]', 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.', '[email protected]', 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

Page 11: 119764860 dx-auth

`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

Page 12: 119764860 dx-auth

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

Page 13: 119764860 dx-auth

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

Page 14: 119764860 dx-auth

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

Page 15: 119764860 dx-auth

4. }

5.

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

7. {

8. // Do something

9. }

10.

11. // Using an Role ID as $roles parameter

12. if ($this->dx_auth->is_role('1', FALSE))

13.{

14. // Do something

15.}

16.

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

18.{

19. // Do something

20.}

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

Page 16: 119764860 dx-auth

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. function Home()

4. {

5. parent::Controller();

6.

16

Page 17: 119764860 dx-auth

7. $this->dx_auth->check_uri_permissions();

8. }

9. }

Or use it within a functionview plaincopy to clipboardprint?

1. function hello_world()

2. {

3. $this->dx_auth->check_uri_permissions();

4.

5. // Do something

6. }

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. function Test()

4. {

5. parent::Controller();

6.

7. // Secure controller

8. $this->dx_auth->check_uri_permissions();

9. }

10.

11. function hi()

12. {

13. echo 'Hi';

14. }

15.

16. function hello()

17. {

17

Page 18: 119764860 dx-auth

18. echo 'Hello';

19. }

20.}

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

Page 19: 119764860 dx-auth

}

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 0 User

2 0 Admin

3 1 Moderator

4 3 Super Moderator

5 3 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

Page 20: 119764860 dx-auth

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

Page 21: 119764860 dx-auth

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

Page 22: 119764860 dx-auth

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

Page 23: 119764860 dx-auth

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

Page 24: 119764860 dx-auth

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'] = '[email protected]';

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

Page 25: 119764860 dx-auth

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 deleted from database. Default is 48 Hours (60*60*24*2).

66. | 'DX_email_account_details' = Email account details after registration, only if 'DX_email_activation' is FALSE.

67. |

68. */ 25

Page 26: 119764860 dx-auth

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. | 'DX_autologin_cookie_life' = Determine auto login cookie life before expired. Default is 2 months (60*60*24*31*2).

101. |

102. */

26

Page 27: 119764860 dx-auth

103.

104. $config['DX_autologin_cookie_name'] = 'autologin';

105. $config['DX_autologin_cookie_life'] = 60*60*24*31*2;

106.

107. /*

108. |--------------------------------------------------------------------------

109. | Login attempts

110. |--------------------------------------------------------------------------

111. |

112. | 'DX_count_login_attempts' = Determine if DX Auth should count login attempt when user failed to login.

113. | 'DX_max_login_attempts' = Determine max login attempt before function is_login_attempt_exceeded() returning TRUE.

114. |

115. */

116.

117. $config['DX_count_login_attempts'] = TRUE;

118. $config['DX_max_login_attempts'] = 1;

119.

120. /*

121. |--------------------------------------------------------------------------

122. | Forgot password settings

123. |--------------------------------------------------------------------------

124. |

125. | 'DX_forgot_password_expire' = Time before forgot password key become invalid. Default is 15 minutes (900 seconds).

126. |

127. */

128.

129. $config['DX_forgot_password_expire'] = 900;

130.

131. /*

132. |--------------------------------------------------------------------------

133. | Captcha

134. |--------------------------------------------------------------------------

135. |

27

Page 28: 119764860 dx-auth

136. | You can set catpcha that created by DX Auth library in here.

137. | 'DX_captcha_directory' = Name of directory where the catpcha will be created.

138. | 'DX_captcha_fonts_path' = Font in this directory will be used when creating captcha.

139. | 'DX_captcha_font_size' = Font size when writing text to captcha. Leave blank for random font size.

140. | 'DX_captcha_grid' = Show grid in created captcha.

141. | 'DX_captcha_expire' = Life time of created captcha before expired, default is 3 minutes (180 seconds).

142. | 'DX_captcha_expire' = Determine captcha case sensitive or not.

143. |

144. */

145.

146. $config['DX_captcha_directory'] = 'captcha';

147. $config['DX_captcha_fonts_path'] = $config['DX_captcha_path'].'fonts';

148. $config['DX_captcha_width'] = 320;

149. $config['DX_captcha_height'] = 95;

150. $config['DX_captcha_font_size'] = '';

151. $config['DX_captcha_grid'] = TRUE;

152. $config['DX_captcha_expire'] = 180;

153. $config['DX_captcha_case_sensitive'] = TRUE;

154.

155. /*

156. |--------------------------------------------------------------------------

157. | reCAPTCHA

158. |--------------------------------------------------------------------------

159. |

160. | If you are planning to use reCAPTCHA function, you have to set reCAPTCHA key here

161. | You can get the key by registering at http://recaptcha.net

162. |

163. */

164.

165. $config['DX_recaptcha_public_key'] = '';

166. $config['DX_recaptcha_private_key'] = '';

167.

168.

169. /*

28

Page 29: 119764860 dx-auth

170. |--------------------------------------------------------------------------

171. | URI

172. |--------------------------------------------------------------------------

173. |

174. | Determines URI that used for redirecting in DX Auth library.

175. | 'DX_deny_uri' = Forbidden access URI.

176. | 'DX_login_uri' = Login form URI.

177. | 'DX_activate_uri' = Activate user URI.

178. | 'DX_reset_password_uri' = Reset user password URI.

179. |

180. | These value can be accessed from DX Auth library variable, by removing 'DX_' string.

181. | For example you can access 'DX_deny_uri' by using $this->dx_auth->deny_uri in controller.

182. |

183. */

184.

185. $config['DX_deny_uri'] = '/auth/deny/';

186. $config['DX_login_uri'] = '/auth/login/';

187. $config['DX_banned_uri'] = '/auth/banned/';

188. $config['DX_activate_uri'] = '/auth/activate/';

189. $config['DX_reset_password_uri'] = '/auth/reset_password/';

190.

191.

192. /*

193. |--------------------------------------------------------------------------

194. | Helper configuration

195. |--------------------------------------------------------------------------

196. |

197. | Configuration below is actually not used in function in DX_Auth library.

198. | They just used to help you coding more easily in controller.

199. | You can set it to blank if you don't need it, or even delete it.

200. |

201. | However they can be accessed from DX Auth library variable, by removing 'DX_' string.

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

29

Page 30: 119764860 dx-auth

203. |

204. */

205.

206. // Registration

207. $config['DX_allow_registration'] = TRUE;

208. $config['DX_captcha_registration'] = TRUE;

209.

210. // Login

211. $config['DX_captcha_login'] = FALSE;

212.

213. // URI Locations

214. $config['DX_logout_uri'] = '/auth/logout/';

215. $config['DX_register_uri'] = '/auth/register/';

216. $config['DX_forgot_password_uri'] = '/auth/forgot_password/';

217. $config['DX_change_password_uri'] = '/auth/change_password/';

218. $config['DX_cancel_account_uri'] = '/auth/cancel_account/';

219.

220. // Forms view

221. $config['DX_login_view'] = 'auth/login_form';

222. $config['DX_register_view'] = 'auth/register_form';

223. $config['DX_forgot_password_view'] = 'auth/forgot_password_form';

224. $config['DX_change_password_view'] = 'auth/change_password_form';

225. $config['DX_cancel_account_view'] = 'auth/cancel_account_form';

226.

227. // Pages view

228. $config['DX_deny_view'] = 'auth/general_message';

229. $config['DX_banned_view'] = 'auth/general_message';

230. $config['DX_logged_in_view'] = 'auth/general_message';

231. $config['DX_logout_view'] = 'auth/general_message';

232.

233. $config['DX_register_success_view'] = 'auth/general_message';

234. $config['DX_activate_success_view'] = 'auth/general_message';

235. $config['DX_forgot_password_success_view'] = 'auth/general_message';

236. $config['DX_reset_password_success_view'] = 'auth/general_message';

237. $config['DX_change_password_success_view'] = 'auth/general_message';

30

Page 31: 119764860 dx-auth

238.

239. $config['DX_register_disabled_view'] = 'auth/general_message';

240. $config['DX_activate_failed_view'] = 'auth/general_message';

241. $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

Page 32: 119764860 dx-auth

• 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

Page 33: 119764860 dx-auth

• 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

Page 34: 119764860 dx-auth

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. function Auth()

4. {

5. parent::Controller();

6. // Load library

7. $this->load->library('DX_Auth');

8. } 34

Page 35: 119764860 dx-auth

9.

10. function login()

11. {

12. // Login using username 'test' and password 'helloworld'

13. $this->dx_auth->login('test', 'helloworld');

14. }

15.

16. function logout()

17. {

18. // Logout user

19. $this->dx_auth->logout();

20. }

21.

22. function register()

23. {

24. // Register a user with username 'john', password 'johnpassword', and email '[email protected]'

25. if ($user = $this->dx_auth->register('john', 'johnpassword', '[email protected]'))

26. {

27. echo 'Welcome '.$user->username;

28. }

29. else

30. {

31. echo 'Failed to register';

32. }

33. }

34.

35. function hello()

36. {

37. // Check if user is logged in or not

38. if ($this->dx_auth->is_logged_in())

39. {

40. echo 'Hello world';

41. }

42. else

43. {

35

Page 36: 119764860 dx-auth

44. echo 'Not logged in';

45. }

46. }

47.}

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. // Used for registering and changing password form validation

4. var $min_username = 4;

5. var $max_username = 20;

6. var $min_password = 4;

7. var $max_password = 20;

8.

9. function Auth()

10. {

11. parent::Controller();

12.

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

14. $this->load->library('DX_Auth');

15.

16. $this->load->helper('url');

17. $this->load->helper('form');

18. }

19.

20. function index()

21. {

22. $this->login();

23. }

24.

36

Page 37: 119764860 dx-auth

25. /* Callback function */

26.

27. function username_check($username)

28. {

29. $result = $this->dx_auth->is_username_available($username);

30. if ( ! $result)

31. {

32. $this->form_validation->set_message('username_check', 'Username already exist. Please choose another username.');

33. }

34.

35. return $result;

36. }

37.

38. function email_check($email)

39. {

40. $result = $this->dx_auth->is_email_available($email);

41. if ( ! $result)

42. {

43. $this->form_validation->set_message('email_check', 'Email is already used by another user. Please choose another email address.');

44. }

45.

46. return $result;

47. }

48.

49. function captcha_check($code)

50. {

51. $result = TRUE;

52.

53. if ($this->dx_auth->is_captcha_expired())

54. {

55. // Will replace this error msg with $lang

56. $this->form_validation->set_message('captcha_check', 'Your confirmation code has expired. Please try again.');

57. $result = FALSE;

58. }

37

Page 38: 119764860 dx-auth

59. elseif ( ! $this->dx_auth->is_captcha_match($code))

60. {

61. $this->form_validation->set_message('captcha_check', 'Your confirmation code does not match the one in the image. Try again.');

62. $result = FALSE;

63. }

64.

65. return $result;

66. }

67.

68. /* End of Callback function */

69.

70. function login()

71. {

72. if ( ! $this->dx_auth->is_logged_in())

73. {

74. $val = $this->form_validation;

75.

76. // Set form validation rules

77. $val->set_rules('username', 'Username', 'trim|required|xss_clean');

78. $val->set_rules('password', 'Password', 'trim|required|xss_clean');

79. $val->set_rules('remember', 'Remember me', 'integer');

80.

81. // Set captcha rules if login attempts exceed max attempts in config

82. if ($this->dx_auth->is_max_login_attempts_exceeded())

83. {

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

85. }

86.

87. if ($val->run() AND $this->dx_auth->login($val->set_value('username'), $val->set_value('password'), $val->set_value('remember')))

88. {

89. // Redirect to homepage

90. redirect('', 'location');

91. }

92. else 38

Page 39: 119764860 dx-auth

93. {

94. // Check if the user is failed logged in because user is banned user or not

95. if ($this->dx_auth->is_banned())

96. {

97. // Redirect to banned uri

98. $this->dx_auth->deny_access('banned');

99. }

100. else

101. {

102. // Default is we don't show captcha until max login attempts eceeded

103. $data['show_captcha'] = FALSE;

104.

105. // Show captcha if login attempts exceed max attempts in config

106. if ($this->dx_auth->is_max_login_attempts_exceeded())

107. {

108. // Create catpcha

109. $this->dx_auth->captcha();

110.

111. // Set view data to show captcha on view file

112. $data['show_captcha'] = TRUE;

113. }

114.

115. // Load login page view

116. $this->load->view($this->dx_auth->login_view, $data);

117. }

118. }

119. }

120. else

121. {

122. $data['auth_message'] = 'You are already logged in.';

123. $this->load->view($this->dx_auth->logged_in_view, $data);

124. }

125. }

126.

127. function logout()

128. { 39

Page 40: 119764860 dx-auth

129. $this->dx_auth->logout();

130.

131. $data['auth_message'] = 'You have been logged out.';

132. $this->load->view($this->dx_auth->logout_view, $data);

133. }

134.

135. function register()

136. {

137. if ( ! $this->dx_auth->is_logged_in() AND $this->dx_auth->allow_registration)

138. {

139. $val = $this->form_validation;

140.

141. // Set form validation rules

142. $val->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->min_username.']|max_length['.$this->max_username.']|callback_username_check|alpha_dash');

143. $val->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->min_password.']|max_length['.$this->max_password.']|matches[confirm_password]');

144. $val->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean');

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

146.

147. if ($this->dx_auth->captcha_registration)

148. {

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

150. }

151.

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

153. if ($val->run() AND $this->dx_auth->register($val->set_value('username'), $val->set_value('password'), $val->set_value('email')))

154. {

155. // Set success message accordingly

156. if ($this->dx_auth->email_activation)

157. {

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

40

Page 41: 119764860 dx-auth

159. }

160. else

161. {

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

163. }

164.

165. // Load registration success page

166. $this->load->view($this->dx_auth->register_success_view, $data);

167. }

168. else

169. {

170. // Is registration using captcha

171. if ($this->dx_auth->captcha_registration)

172. {

173. $this->dx_auth->captcha();

174. }

175.

176. // Load registration page

177. $this->load->view($this->dx_auth->register_view);

178. }

179. }

180. elseif ( ! $this->dx_auth->allow_registration)

181. {

182. $data['auth_message'] = 'Registration has been disabled.';

183. $this->load->view($this->dx_auth->register_disabled_view, $data);

184. }

185. else

186. {

187. $data['auth_message'] = 'You have to logout first, before registering.';

188. $this->load->view($this->dx_auth->logged_in_view, $data);

189. }

190. }

191.

192. function activate()

193. {

41

Page 42: 119764860 dx-auth

194. // Get username and key

195. $username = $this->uri->segment(3);

196. $key = $this->uri->segment(4);

197.

198. // Activate user

199. if ($this->dx_auth->activate($username, $key))

200. {

201. $data['auth_message'] = 'Your account have been successfully activated. '.anchor(site_url($this->dx_auth->login_uri), 'Login');

202. $this->load->view($this->dx_auth->activate_success_view, $data);

203. }

204. else

205. {

206. $data['auth_message'] = 'The activation code you entered was incorrect. Please check your email again.';

207. $this->load->view($this->dx_auth->activate_failed_view, $data);

208. }

209. }

210.

211. function forgot_password()

212. {

213. $val = $this->form_validation;

214.

215. // Set form validation rules

216. $val->set_rules('login', 'Username or Email address', 'trim|required|xss_clean');

217.

218. // Validate rules and call forgot password function

219. if ($val->run() AND $this->dx_auth->forgot_password($val->set_value('login')))

220. {

221. $data['auth_message'] = 'An email has been sent to your email with instructions with how to activate your new password.';

222. $this->load->view($this->dx_auth->forgot_password_success_view, $data);

223. }

224. else

225. {

226. $this->load->view($this->dx_auth->forgot_password_view);

42

Page 43: 119764860 dx-auth

227. }

228. }

229.

230. function reset_password()

231. {

232. // Get username and key

233. $username = $this->uri->segment(3);

234. $key = $this->uri->segment(4);

235.

236. // Reset password

237. if ($this->dx_auth->reset_password($username, $key))

238. {

239. $data['auth_message'] = 'You have successfully reset you password, '.anchor(site_url($this->dx_auth->login_uri), 'Login');

240. $this->load->view($this->dx_auth->reset_password_success_view, $data);

241. }

242. else

243. {

244. $data['auth_message'] = 'Reset failed. Your username and key are incorrect. Please check your email again and follow the instructions.';

245. $this->load->view($this->dx_auth->reset_password_failed_view, $data);

246. }

247. }

248.

249. function change_password()

250. {

251. // Check if user logged in or not

252. if ($this->dx_auth->is_logged_in())

253. {

254. $val = $this->form_validation;

255.

256. // Set form validation

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

258. $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

Page 44: 119764860 dx-auth

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

260.

261. // Validate rules and change password

262. if ($val->run() AND $this->dx_auth->change_password($val->set_value('old_password'), $val->set_value('new_password')))

263. {

264. $data['auth_message'] = 'Your password has successfully been changed.';

265. $this->load->view($this->dx_auth->change_password_success_view, $data);

266. }

267. else

268. {

269. $this->load->view($this->dx_auth->change_password_view);

270. }

271. }

272. else

273. {

274. // Redirect to login page

275. $this->dx_auth->deny_access('login');

276. }

277. }

278.

279. function cancel_account()

280. {

281. // Check if user logged in or not

282. if ($this->dx_auth->is_logged_in())

283. {

284. $val = $this->form_validation;

285.

286. // Set form validation rules

287. $val->set_rules('password', 'Password', "trim|required|xss_clean");

288.

289. // Validate rules and change password

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

291. {

44

Page 45: 119764860 dx-auth

292. // Redirect to homepage

293. redirect('', 'location');

294. }

295. else

296. {

297. $this->load->view($this->dx_auth->cancel_account_view);

298. }

299. }

300. else

301. {

302. // Redirect to login page

303. $this->dx_auth->deny_access('login');

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. // Used for registering and changing password form validation

4. var $min_username = 4;

5. var $max_username = 20;

6. var $min_password = 6;

7. var $max_password = 10;

8.

9. function Auth()

10. {

11. parent::Controller();

12.

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

45

Page 46: 119764860 dx-auth

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

15. }

16.

17. function index()

18. {

19. $this->login();

20. }

21.

22. /* Callback function */

23.

24. function username_check($username)

25. {

26. $result = $this->dx_auth->is_username_available($username);

27. if ( ! $result)

28. {

29. $this->form_validation->set_message('username_check', 'Username already exist. Please choose another username.');

30. }

31.

32. return $result;

33. }

34.

35. function email_check($email)

36. {

37. $result = $this->dx_auth->is_email_available($email);

38. if ( ! $result)

39. {

40. $this->form_validation->set_message('email_check', 'Email is already used by another user. Please choose another email address.');

41. }

42.

43. return $result;

44. }

45.

46. function recaptcha_check()

47. {

46

Page 47: 119764860 dx-auth

48. $result = $this->dx_auth->is_recaptcha_match();

49. if ( ! $result)

50. {

51. $this->form_validation->set_message('recaptcha_check', 'Your confirmation code does not match the one in the image. Try again.');

52. }

53.

54. return $result;

55. }

56.

57. /* End of Callback function */

58.

59. function register_recaptcha()

60. {

61. if ( ! $this->dx_auth->is_logged_in() AND $this->dx_auth->allow_registration)

62. {

63. $val = $this->form_validation;

64.

65. // Set form validation rules

66. $val->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->min_username.']|max_length['.$this->max_username.']|callback_username_check|alpha_dash');

67. $val->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->min_password.']|max_length['.$this->max_password.']|matches[confirm_password]');

68. $val->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean');

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

70.

71. // Is registration using captcha

72. if ($this->dx_auth->captcha_registration)

73. {

74. // Set recaptcha rules.

75. // IMPORTANT: Do not change 'recaptcha_response_field' because it's used by reCAPTCHA API,

76. // This is because the limitation of reCAPTCHA, not DX Auth library

77. $val->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback_recaptcha_check');

78. }

47

Page 48: 119764860 dx-auth

79.

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

81. if ($val->run() AND $this->dx_auth->register($val->set_value('username'), $val->set_value('password'), $val->set_value('email')))

82. {

83. // Set success message accordingly

84. if ($this->dx_auth->email_activation)

85. {

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

87. }

88. else

89. {

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

91. }

92.

93. // Load registration success page

94. $this->load->view($this->dx_auth->register_success_view, $data);

95. }

96. else

97. {

98. // Load registration page

99. $this->load->view('auth/register_recaptcha_form');

100. }

101. }

102. elseif ( ! $this->dx_auth->allow_registration)

103. {

104. $data['auth_message'] = 'Registration has been disabled.';

105. $this->load->view($this->dx_auth->register_disabled_view, $data);

106. }

107. else

108. {

109. $data['auth_message'] = 'You have to logout first, before registering.';

110. $this->load->view($this->dx_auth->logged_in_view, $data);

111. }

112. } 48

Page 49: 119764860 dx-auth

113. }

Here is the view part (auth/register_recaptcha_form).

view plaincopy to clipboardprint?

1. <?php

2. $username = array(

3. 'name' => 'username',

4. 'id' => 'username',

5. 'size' => 30,

6. 'value' => set_value('username')

7. );

8.

9. $password = array(

10. 'name' => 'password',

11. 'id' => 'password',

12. 'size' => 30,

13. 'value' => set_value('password')

14.);

15.

16. $confirm_password = array(

17. 'name' => 'confirm_password',

18. 'id' => 'confirm_password',

19. 'size' => 30,

20. 'value' => set_value('confirm_password')

21.);

22.

23. $email = array(

24. 'name' => 'email',

25. 'id' => 'email',

26. 'maxlength' => 80,

27. 'size' => 30,

28. 'value' => set_value('email')

29.);

30.?>

31.

32.<html> 49

Page 50: 119764860 dx-auth

33.<body>

34.

35.<fieldset><legend>Register</legend>

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

37.

38.<dl>

39. <dt><?php echo form_label('Username', $username['id']);?></dt>

40. <dd>

41. <?php echo form_input($username)?>

42. <?php echo form_error($username['name']); ?>

43.

44. </dd>

45.

46. <dt><?php echo form_label('Password', $password['id']);?></dt>

47. <dd>

48. <?php echo form_password($password)?>

49. <?php echo form_error($password['name']); ?>

50.

51. </dd>

52.

53. <dt><?php echo form_label('Confirm Password', $confirm_password['id']);?></dt>

54. <dd>

55. <?php echo form_password($confirm_password);?>

56. <?php echo form_error($confirm_password['name']); ?>

57.

58. </dd>

59.

60. <dt><?php echo form_label('Email Address', $email['id']);?></dt>

61. <dd>

62. <?php echo form_input($email);?>

63. <?php echo form_error($email['name']); ?>

64.

65. </dd>

66.

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

68.

50

Page 51: 119764860 dx-auth

69. <dt></dt>

70. <dd>

71. <?php

72. // Show recaptcha imgage

73. echo $this->dx_auth->get_recaptcha_image();

74. // Show reload captcha link

75. echo $this->dx_auth->get_recaptcha_reload_link();

76. // Show switch to image captcha or audio link

77. echo $this->dx_auth->get_recaptcha_switch_image_audio_link();

78. ?>

79.

80. </dd>

81.

82. <dt><?php echo $this->dx_auth->get_recaptcha_label(); ?></dt>

83. <dd>

84. <?php echo $this->dx_auth->get_recaptcha_input(); ?>

85.

86. <?php echo form_error('recaptcha_response_field'); ?>

87. </dd>

88.

89. <?php

90. // Get recaptcha javascript and non javasript html

91. echo $this->dx_auth->get_recaptcha_html();

92. ?>

93. <?php endif; ?>

94.

95.

96.

97. <dt></dt>

98.

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

100. </dl>

101.

102. <?php echo form_close()?>

103. </fieldset>

104. </body>

51

Page 52: 119764860 dx-auth

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

Page 53: 119764860 dx-auth

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

2. {

3. echo 'Editing is allowed in your role';

4. }

5. else

6. {

7. echo 'Editing is not allowed in your role';

8. }

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

53