Ion Auth  ›  Documentation

Documentation

Author: Ben Edmunds

Ion Auth

Ion Auth is a simple and lightweight authentication library for the CodeIgniter framework

License

Ion Auth is released under the Apache License v2.0. You can read the license here: http://www.apache.org/licenses/LICENSE-2.0

Server requirements

Ion Auth 4 needs CodeIgniter 4 and PHP 7.2.

Installation

  1. Download the latest version: https://github.com/benedmunds/CodeIgniter-Ion-Auth/zipball/4
  2. Copy the files from this package to the correspoding folder in your application folder. For example, copy IonAuth/Config/IonAuth.php to app/Config/IonAuth.php.
  3. You can also copy the entire directory structure into your ThirdParty/ folder. For example, copy everything to app/ThirdParty/IonAuth/
  4. Use the migration file (in Database/Migrations/)
    $ php spark migrate:latest -n IonAuth
  5. Insert default datas (Don't forget to set Config\Migrations:enabled to true.) Windows :
    $ php spark db:seed IonAuth\Database\Seeds\IonAuthSeeder
    Linux :
    $ php spark db:seed IonAuth\\Database\\Seeds\\IonAuthSeeder

The default login is:

Upgrading

  1. Download the latest version: https://github.com/benedmunds/CodeIgniter-Ion-Auth/zipball/4
  2. Overwrite Libraries/IonAuth.php and Models/IonAuthModel.php with the new versions.
  3. Overwrite Languages/* with the news versions.
  4. Check Config/IonAuth.php for evolution.

Upgrading from Ion Auth 2? Check the UPGRADING.md file in the package.

Loading Ion Auth

You load Ion Auth just like any other library:

$ionAuth = new \IonAuth\Libraries\IonAuth();

You can also autoload the library.

Configuration Options

Ion Auth is extremely configurable.

To change configuration options simply edit the Config/IonAuth.php file or pass an array when loading the library.

Tables

Hash method

Authentication options

Cookie options

Email options

Templates options

Errors and Messages Templates


Class Function Reference

NOTE: Methods available in the model are called through the controller using PHP5 magic. You should never use IonAuthModel->method() in your applications.

login()

login(string $identity, string $password, bool $remember=false): bool

Logs the user into the system.

Parameters

  1. identity - string REQUIRED. Username, email or any unique value in your users table, depending on your configuration.
  2. password - string REQUIRED.
  3. remember - boolean OPTIONAL. TRUE sets the user to be remembered if enabled in the configuration.

Return

Usage


    $identity = 'ben.edmunds@gmail.com';
    $password = '12345678';
    $remember = TRUE; // remember the user
    $this->ionAuth->login($identity, $password, $remember);
    

logout()

logout(): bool

Logs the user out of the system.

Usage


    $this->ionAuth->logout();
    

register()

register(string $identity, string $password, string $email, array $additionalData=[], array $groups=[])

Register (create) a new user.

Parameters

  1. identity - string REQUIRED. This must be the value that uniquely identifies the user when he is registered. If you chose "email" as $config['identity'] in the configuration file, you must put the email of the new user.
  2. password - string REQUIRED.
  3. email - string REQUIRED.
  4. additionalData - multidimensional array OPTIONAL.
  5. groups - array OPTIONAL. If not passed the default group name set in the config will be used.

Return

Usage


    $username = 'benedmunds';
    $password = '12345678';
    $email = 'ben.edmunds@gmail.com';
    $additional_data = array(
        'first_name' => 'Ben',
        'last_name' => 'Edmunds',
    );
    $group = array('1'); // Sets user to admin.

    $this->ionAuth->register($username, $password, $email, $additional_data, $group);
    

createUser()

createUser()

createUser is an alternate method for register() method.


update()

update(int $id, array $data): bool

Update a user.

Parameters

  1. id - integer REQUIRED.
  2. data - multidimensional array REQUIRED.

Return

Usage


    $id = 12;
    $data = array(
        'first_name' => 'Ben',
        'last_name' => 'Edmunds',
        'password' => '123456789',
     );

    $this->ionAuth->update($id, $data);
    

updateUser()

updateUser(): bool

updateUser() is an alternate method for update() method.


deleteUser()

deleteUser(int $id): bool

Delete a user.

Parameters

  1. id - integer REQUIRED.

Return

Usage


    $id = 12;
    $this->ionAuth->deleteUser($id);
    

forgottenPassword()

forgottenPassword(string $identity)

Resets a users password by emailing the user a reset code.

Parameters

  1. identity - string REQUIRED. (as defined in Config/IonAuth.php)

Return

Usage

- This example assumes you have 'email' selected as the identity in Config/IonAuth.php


    //Working code for this example is in the example Auth controller in the github repo
    function forgot_password()
    {
        $this->validation->setRule('email', 'Email Address', 'required');

        if ($this->validation->run() == false) {
            //setup the input
            $this->data['email'] = array(
                'name'    => 'email',
                'id'      => 'email',
            );

            //set any errors and display the form
            $this->data['message'] = ($this->validation->listErrors()) ? $this->validation->listErrors() : $this->session->flashdata('message');
            return view('auth/forgot_password', $this->data);
        }
        else {
            //run the forgotten password method to email an activation code to the user
            $forgotten = $this->ionAuth->forgottenPassword($this->request->getPost('email'));

            if ($forgotten)
            {
                //if there were no errors
                $this->session->setFlashdata('message', $this->ionAuth->messages());
                return redirect()->to("auth/login"); //we should display a confirmation page here instead of the login page
            }
            else
            {
                $this->session->setFlashdata('message', $this->ionAuth->errors());
                return redirect()->to("auth/forgot_password");
            }
        }
    }
    

forgottenPasswordCheck()

forgottenPasswordCheck(string $code)

Check to see if the forgotten password code is valid.

Parameters

  1. code - string REQUIRED.

Return

Usage


    $user = $this->ionAuth->forgottenPasswordCheck($code);
    if ($user)
    {
        //display the password reset form
    }
    

loggedIn()

loggedIn(): bool

Check to see if a user is logged in.

Return

Usage


    if (!$this->ionAuth->loggedIn())
    {
        return redirect()->to('auth/login');
    }
    

isAdmin()

isAdmin(int $id=0): bool

Check to see if the currently logged in user is an admin.

Parameters

  1. id - integer OPTIONAL. If a user id is not passed the id of the currently logged in user will be used.

Return

Usage


    if (!$this->ionAuth->isAdmin())
    {
        $this->session->markAsFlashdata('message', 'You must be an admin to view this page');
        redirect()->to('welcome/index');
    }
    

inGroup()

inGroup($checkGroup, int $id=0, bool $checkAll=false): bool

Check to see if a user is in a group(s).

Parameters

  1. checkGroup - string REQUIRED. Integer or array of strings and integers.
  2. id - integer OPTIONAL. If a user id is not passed the id of the currently logged in user will be used.
  3. checkAll - boolean OPTIONAL. Whether to check if user is in all groups, or in any group.

Return

Usage


    # single group (by name)
    $group = 'gangstas';
    if (!$this->ionAuth->inGroup($group))
    {
        $this->session->markAsFlashdata('message', 'You must be a gangsta to view this page');
        redirect()->to('welcome/index');
    }

    # single group (by id)
    $group = 1;
    if (!$this->ionAuth->inGroup($group))
    {
        $this->session->markAsFlashdata('message', 'You must be part of the group 1 to view this page');
        redirect()->to('welcome/index');
    }

    # multiple groups (by name)
    $group = array('gangstas', 'hoodrats');
    if (!$this->ionAuth->inGroup($group))
    {
        $this->session->markAsFlashdata('message', 'You must be a gangsta OR a hoodrat to view this page');
        redirect()->to('welcome/index');
    }

    # multiple groups (by id)
    $group = array(1, 2);
    if (!$this->ionAuth->inGroup($group))
    {
        $this->session->markAsFlashdata('message', 'You must be a part of group 1 or 2 to view this page');
        redirect()->to('welcome/index');
    }

    # multiple groups (by id and name)
    $group = array('gangstas', 2);
    if (!$this->ionAuth->inGroup($group))
    {
        $this->session->markAsFlashdata('message', 'You must be a part of the gangstas or group 2');
        redirect()->to('welcome/index');
    }

    # multiple groups (by id) and check if all exist
    $group = array(1, 2);
    if (!$this->ionAuth->inGroup($group, false, true))
    {
        $this->session->markAsFlashdata('message', 'You must be a part of group 1 and 2 to view this page');
        redirect()->to('welcome/index');
    }

    

usernameCheck()

usernameCheck(string $username): bool

Check to see if the username is already registered.

Parameters

  1. username - string REQUIRED.

Return

Usage


    //This is a lame example but it works.  Usually you would use this method with form_validation.
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $email = $this->input->post('email');
    $additional_data = array(
        'first_name' => $this->input->post('first_name'),
        'last_name' => $this->input->post('last_name'),
    );

    if (!$this->ionAuth->usernameCheck($username))
    {
        $group_name = 'users';
        $this->ionAuth->register($username, $password, $email, $additional_data, $group_name);
    }
    

emailCheck()

emailCheck(string $email=''): bool

Check to see if the email is already registered.

Parameters

  1. email - string REQUIRED.

Return

Usage


    //This is a lame example but it works.  Usually you would use this method with form_validation.
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $email = $this->input->post('email');
    $additional_data = array(
        'first_name' => $this->input->post('first_name'),
        'last_name' => $this->input->post('last_name'),
    );

    if (!$this->ionAuth->emailCheck($email))
    {
        $group_name = 'users';
        $this->ionAuth->register($username, $password, $email, $additional_data, $group_name);
    }
    

identityCheck()

identityCheck(string $identity=''): bool

Check to see if the identity is already registered.

Parameters

  1. identity - string REQUIRED.

Return

Usage


    //This is a lame example but it works.
    $user = $this->ionAuth->user();
    $data = array(
        'identity' => $this->input->post('identity'),
        'first_name' => $this->input->post('first_name'),
        'last_name' => $this->input->post('last_name'),
    );

    if ($data['identity'] === $user->username || $data['identity'] === $user->email || $this->ionAuth->identityCheck($data['identity']) === FALSE)
    {
        $this->ionAuth->updateUser($user->id, $data)
    }
    

isMaxLoginAttemptsExceeded()

isMaxLoginAttemptsExceeded(string $identity, $ipAddress=null): bool

If login attempt tracking is enabled, checks to see if the number of failed login attempts for this identity or ip address has been exceeded. The controller must call this method and take any necessary actions. Login attempt limits are not enforced in the library.

Parameters

  1. identity - string REQUIRED.
  2. ipAddress - OPTIONAL.

Return

Usage


    $identity = 'ben.edmunds@gmail.com';
    if ($this->ionAuth->isMaxLoginAttemptsExceeded($identity))
    {
        $this->session->markAsFlashdata('message', 'You have too many login attempts');
        redirect()->to('welcome/index');
    }
    

getAttemptsNum()

getAttemptsNum(string $identity, $ipAddress=null): int

Returns the number of failed login attempts for this identity or ip address.

Parameters

  1. identity - string REQUIRED.

Return

Usage


    $identity = 'ben.edmunds@gmail.com';
    $num_attempts = $this->ionAuth->getAttemptsNum($identity);
    

increaseLoginAttempts()

increaseLoginAttempts(string $identity): bool

If login attempt tracking is enabled, records another failed login attempt for this identity or ip address. This method is automatically called during the login() method if the login failed.

Parameters

  1. identity - string REQUIRED.

Return

Usage


    $identity = 'ben.edmunds@gmail.com';
    $password = '12345678';
    if ($this->ionAuth->login($identity, $password) == FALSE)
    {
        $this->ionAuth->increaseLoginAttempts($identity);
    }
    

clearLoginAttempts()

clearLoginAttempts(string $identity, int $oldAttemptsAxpirePeriod=86400, $ipAddress = null): bool

Clears all failed login attempt records for this identity or this ip address. This method is automatically called during the login() method if the login succeded.

Parameters

  1. identity - string REQUIRED.
  2. oldAttemptsAxpirePeriod - integer. OPTIONAL.
  3. ipAddress - OPTIONAL.

Usage


    $identity = 'ben.edmunds@gmail.com';
    $password = '12345678';

    if ($this->ionAuth->login($identity, $password) == TRUE)
    {
        $this->ionAuth->clearLoginAttempts($identity);
    }
    

user()

user(int $id=0): self

Get a user.

Parameters

  1. id - integer OPTIONAL. If a user id is not passed the id of the currently logged in user will be used.

Return

Usage


    $user = $this->ionAuth->user()->row();
    echo $user->email;
    

Output

    stdClass Object (
        [id] => 1
        [ip_address] => 127.0.0.1
        [username] => administrator
        [password] => 59beecdf7fc966e2f17fd8f65a4a9aeb09d4a3d4
        [email] => admin@admin.com
        [activation_code] => 19e181f2ccc2a7ea58a2c0aa2b69f4355e636ef4
        [forgotten_password_code] => 81dce1d0bc2c10fbdec7a87f1ff299ed7e4c9e4a
        [remember_code] => 9d029802e28cd9c768e8e62277c0df49ec65c48c
        [created_on] => 1268889823
        [last_login] => 1279464628
        [active] => 0
        [first_name] => Admin
        [last_name] => Account
        [company] => Some Corporation
        [phone] => (123)456-7890
    )
    

users()

users($groups=null): self

Get the users.

Parameters

  1. groups - array OPTIONAL. Group names, or group IDs and names. If an array of group ids, of group names, or of group ids and names are passed (or a single group id or name) this will return the users in those groups.

Return

Usage


    // get all users
    $users = $this->ionAuth->users()->result();
    


    // get users from group with id of '1'
    $users = $this->ionAuth->users(1)->result();
    


    // get users from 'members' group
    $users = $this->ionAuth->users('members')->result();
    


    // get users from 'admin' and 'members' group
    $users = $this->ionAuth->users(array('admin', 'members'))->result();
    


    // get users from 'admin' group, 'members' group and group with id '4'
    $users = $this->ionAuth->users(array('admin', 4, 'members'))->result();
    


    // get users from group with id of '1'
    $users = $this->ionAuth->users(1)->result();
    


    // get users from 'members' group
    $users = $this->ionAuth->users('members')->result();
    


    // get users from 'admin' and 'members' group
    $users = $this->ionAuth->users(array('admin', 'members'))->result();
    


    // get users from 'admin' group, 'members' group and group with id '4'
    $users = $this->ionAuth->users(array('admin', 4 ,'members'))->result();
    

group()

group(int $id=0)

Get a group.

Parameters

  1. id - integer REQUIRED.

Return

Usage


    $groupId = 2;
    $group = $this->ionAuth->group($groupId)->result();
    

groups()

groups()

Get the groups.

Return

Usage


    $groups = $this->ionAuth->groups()->result();
    

messages()

messages(): string

Get messages.

Return

Usage


    $id = 12;
    $data = array(
        'first_name' => 'Ben',
        'last_name' => 'Edmunds',
    );

    if ($this->ionAuth->updateUser($id, $data))
    {
        $messages = $this->ionAuth->messages();
        echo $messages;
    }
    else
    {
        $errors = $this->ionAuth->errors();
        echo $errors;
    }
    

messagesArray()

messagesArray(bool $langify=true): array

Get messages as an array.

Parameters

  1. langify - boolean OPTIONAL. TRUE means that the messages will be langified.

Return

Usage


    $id = 12;
    $data = array(
        'first_name' => 'Ben',
        'last_name' => 'Edmunds',
    );

    if ($this->ionAuth->updateUser($id, $data))
    {
        $messages = $this->ionAuth->messagesArray();
        foreach ($messages as $message)
        {
            echo $message;
        }
    }
    else
    {
        $errors = $this->ionAuth->errorsArray();
        foreach ($errors as $error)
        {
            echo $error;
        }
    }
    

getUsersGroups()

getUsersGroups(int $id=0)

Get all groups a user is part of.

Parameters

  1. id - integer OPTIONAL. If a user id is not passed the id of the currently logged in user will be used.

Return

    stdClass Object (
        [id] => 1
        [name] => admins
        [description] => Administrator
    )
    

Usage


    $user_groups = $this->ionAuth->getUsersGroups($user->id)->result();
    

addToGroup()

addToGroup($groupIds, int $userId=0): int

Add user to group

Parameters

  1. groupIds - integer or array REQUIRED.
  2. userId - integer REQUIRED.

Return

Usage


    // pass an array of group ID's and user ID
    $this->ionAuth->addToGroup(array('1', '3', '6'), $userId);

    // pass a single ID and user ID
    $this->ionAuth->addToGroup(1, $userId);
    

removeFromGroup()

removeFromGroup($groupIds=0, int $userId=0): bool

Remove user from group(s)

Parameters

  1. groupIds - NULL, integer or array REQUIRED. NULL will remove the user from all groups.
  2. userId - integer REQUIRED.

Return

Usage


    // pass an array of group ID's and user ID
    $groupIds = array('1', '3', '6');
    $this->ionAuth->removeFromGroup($groupIds, $userId);

    // pass a single ID and user ID
    $this->ionAuth->removeFromGroup(1, $userId);

    // pass NULL to remove user from all groups
    $this->ionAuth->removeFromGroup(NULL, $userId);
    

createGroup()

createGroup(string $groupName='', string $groupDescription='', array $additionalData=[])

Create a group

Parameters

  1. groupName - string REQUIRED.
  2. groupDescription - string.
  3. additionalData - array.

Return

Usage


    // pass the right arguments and it's done
    $group = $this->ionAuth->createGroup('new_test_group', 'This is a test description');

    if (! $group)
    {
        $viewErrors = $this->ionAuth->messages();
    }
    else
    {
        $newGroupId = $group;
        // do more cool stuff
    }
    

updateGroup()

updateGroup(int $groupId, string $groupName='', array $additionalData=[]): bool

Update details of a group

Parameters

  1. groupId - integer REQUIRED.
  2. groupName - string REQUIRED.
  3. additionalData - array.

Return

Usage


    // source these things from anywhere you like (eg., a form)
    $groupId = 2;
    $groupName = 'test_group_changed_name';
    $additionalData = array(
        'description' => 'New Description'
    );

    // pass the right arguments and it's done
    $group_update = $this->ionAuth->updateGroup($groupId, $groupName, $additionalData);

    if(!$group_update)
    {
        $view_errors = $this->ionAuth->messages();
    }
    else
    {
        // do more cool stuff
    }
    

deleteGroup()

deleteGroup(int $groupId): bool

Remove a group. Removes the group details from the configured 'groups' table. Users belonging to the group are stripped of this status (references to this group are removed from users_groups), but user data itself remains untouched.

Parameters

  1. groupId - integer REQUIRED.

Return

Usage


    // source this from anywhere you like (eg., a form)
    $groupId = 2;

    // pass the right arguments and it's done
    $groupDelete = $this->ionAuth->deleteGroup($groupId);

    if (! $groupDelete)
    {
        $viewErrors = $this->ionAuth->messages();
    }
    else
    {
        // do more cool stuff
    }
    

setMessageTemplate()

setMessageTemplate(string $single='', string $list=''): bool

Set the message templates.

Parameters

  1. single - string OPTIONAL. Single template.
  2. list - string OPTIONAL. List template.

Usage


    $id = 12;
    $data = array(
        'first_name' => 'Ben',
        'last_name' => 'Edmunds',
    );

    if ($this->ionAuth->updateUser($id, $data))
    {
        $this->ionAuth->setMessageTemplate('', 'list_message');
        $messages = $this->ionAuth->messages();
        echo $messages;
    }
    else
    {
        $errors = $this->ionAuth->errors();
        echo $errors;
    }
    

errors()

errors(string $template='list'): string

Get the errors.

Parameters

  1. list - string OPTIONAL. List template.

Return

Usage


    $id = 12;
    $data = array(
        'first_name' => 'Ben',
        'last_name' => 'Edmunds',
    );

    if ($this->ionAuth->updateUser($id, $data))
    {
        $messages = $this->ionAuth->messages();
        echo $messages;
    }
    else
    {
        $errors = $this->ionAuth->errors();
        echo $errors;
    }
    

errorsArray()

errorsArray(bool $langify=true): array

Get error messages as an array.

Return

Parameters

  1. langify - boolean OPTIONAL. TRUE means that the error messages will be langified (default TRUE).

Usage


    $id = 12;
    $data = array(
        'first_name' => 'Ben',
        'last_name' => 'Edmunds',
     );

    if ($this->ionAuth->updateUser($id, $data))
    {
        $messages = $this->ionAuth->messagesArray();
        foreach ($messages as $message)
        {
            echo $message;
        }
    }
    else
    {
        $errors = $this->ionAuth->errorsArray();
        foreach ($errors as $error)
        {
            echo $error;
        }
    }
    

setHook()

setHook(string $event, string $name, string $class, string $method, array $arguments=[]): self

Set a single or multiple functions to be called when trigged by triggerEvents(). See an example here: https://gist.github.com/657de89b26decda2b2fa

Parameters

  1. event - string REQUIRED.
  2. name - string REQUIRED.
  3. class - string REQUIRED.
  4. method - string REQUIRED.
  5. arguments - array OPTIONAL.

Usage


    <?php

    use CodeIgniter\Controller;
    use IonAuth\Libraries\IonAuth;

    class Accounts extends Controller {

        protected $ionAuth;

        public function __construct()
        {
            $this->ionAuth = new IonAuth();
            // ....

            /**
            *
            * make sure we loaded IonAuth
            * The following does not need to go in __construct() it just needs to be set before
            * you triggerEvents().
            */
            $event = 'socialpush';
            $class = 'Accounts';
            $args = array('this is the content of the message', 'billy');

            $name = 'activate_sendmail';
            $method = 'email';
            $this->ionAuth->setHook($event, $name, $class, $method, $args);

            $name = 'call_Twitter';
            $method = 'twitter';
            $this->ionAuth->setHook($event, $name, $class, $method, $args);

            $name = 'call_MailChimp_API';
            $method = 'mailchimp';
            $this->ionAuth->setHook($event, $name, $class, $method, $args);

            $name = 'call_Facebook_API';
            $method = 'facebook';
            $this->ionAuth->setHook($event, $name, $class, $method, $args);

            $name = 'call_gPlus_API';
            $method = 'gplus';
            $this->ionAuth->setHook($event, $name, $class, $method, $args);
        }

        public function postMessage($one)
        {
            $this->ionAuth->triggerEvents('socialpush');
        }
        public function email($content, $who)
        {
            return true;
        }
        public function twitter($content, $who)
        {
            return true;
        }
        public function mailchimp($content, $who)
        {
            return true;
        }
        public function facebook($content, $who)
        {
            return true;
        }
        public function gplus($content, $who)
        {
            return true;
        }
    }
    

triggerEvents()

triggerEvents($events): void

Call Additional functions to run that were registered with setHook().

Parameters

  1. events - string or array REQUIRED. Event(s) name.

Usage


    $this->ionAuth->triggerEvents('socialpush');