### PHP Example: Registering and Triggering IonAuth Event Hooks Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md Comprehensive PHP example demonstrating the setup of multiple event hooks using `setHook` within a CodeIgniter controller's constructor. It shows how to associate different methods (email, twitter, mailchimp, facebook, gplus) with a 'socialpush' event and subsequently trigger them using `triggerEvents`. ```php 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; } } ``` -------------------------------- ### Install Ion Auth 4.x with Composer for New Projects Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/INSTALLING.md This snippet outlines the Composer commands to initialize a new project and then add Ion Auth 4.x as a dependency. It sets minimum stability and adds the Ion Auth repository. ```shell $ composer init $ composer config minimum-stability dev $ composer config repositories.ionAuth vcs git@github.com:benedmunds/CodeIgniter-Ion-Auth.git $ composer require benedmunds/codeigniter-ion-auth:4.x-dev ``` -------------------------------- ### PHP: Create Group Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md Example demonstrating how to create a new group and handle the success or failure of the operation. ```PHP // 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 } ``` -------------------------------- ### PHP Example: Calling IonAuth `triggerEvents` Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md A concise PHP example illustrating how to invoke the `triggerEvents` method with a specific event name, 'socialpush', to trigger all associated registered functions. ```php $this->ionAuth->triggerEvents('socialpush'); ``` -------------------------------- ### PHP: Get Errors Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md Example demonstrating how to retrieve and display error messages after an unsuccessful user update operation. ```PHP $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; } ``` -------------------------------- ### Install Ion Auth 4.x with Composer for Existing Projects Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/INSTALLING.md This snippet provides the Composer commands to add Ion Auth 4.x as a dependency to an existing CodeIgniter project. It configures minimum stability and adds the Ion Auth repository before requiring the package. ```shell $ composer config minimum-stability dev $ composer config repositories.ionAuth vcs git@github.com:benedmunds/CodeIgniter-Ion-Auth.git $ composer require benedmunds/codeigniter-ion-auth:4.x-dev ``` -------------------------------- ### Run Ion Auth Database Migrations Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/INSTALLING.md This snippet provides the CodeIgniter `spark` command to run the necessary database migrations for Ion Auth. It ensures the database schema is set up correctly for the library. ```shell $ php spark migrate -n IonAuth ``` -------------------------------- ### Example: Register User if Username Not Taken (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This PHP example demonstrates how to use `usernameCheck` to determine if a username is available before registering a new user. It integrates with typical form validation concepts, preventing duplicate usernames. ```php //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); } ``` -------------------------------- ### Create New Group (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example demonstrating how to use the `createGroup` method to create a new group, including basic error handling. ```PHP // 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 } ``` -------------------------------- ### Example: Get Number of Failed Login Attempts (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This PHP example demonstrates how to use `getAttemptsNum` to retrieve the count of failed login attempts for a given identity. This value can be used for display or further conditional logic, such as locking an account. ```php $identity = 'ben.edmunds@gmail.com'; $num_attempts = $this->ionAuth->getAttemptsNum($identity); ``` -------------------------------- ### PHP: Get All Groups with ionAuth->groups() Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example demonstrating how to retrieve all user groups using the `ionAuth->groups()` method. ```PHP $groups = $this->ionAuth->groups()->result(); ``` -------------------------------- ### Ion Auth login() Method and Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Logs a user into the system. This snippet includes the method signature, parameters, return type, and a PHP usage example demonstrating how to authenticate a user with identity, password, and remember me option. ```APIDOC login(string $identity, string $password, bool $remember=false): bool identity: REQUIRED. Username, email or any unique value in your users table, depending on your configuration. password: REQUIRED. remember: OPTIONAL. TRUE sets the user to be remembered if enabled in the configuration. Returns: boolean. TRUE if the user was successfully logged in FALSE if the user was not logged in. ``` ```PHP $identity = 'ben.edmunds@gmail.com'; $password = '12345678'; $remember = TRUE; // remember the user $this->ionAuth->login($identity, $password, $remember); ``` -------------------------------- ### Clone Ion Auth 4.x for Development Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/INSTALLING.md This snippet shows how to clone the Ion Auth 4.x repository directly using Git for development purposes. It includes commands to navigate into the directory and checkout the 4.x branch. ```shell my-project$ git clone https://github.com/benedmunds/CodeIgniter-Ion-Auth.git my-project$ cd CodeIgniter-Ion-Auth CodeIgniter-Ion-Auth$ git checkout 4 ``` -------------------------------- ### Example: Handle Exceeded Login Attempts (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This PHP example shows how to use `isMaxLoginAttemptsExceeded` to check if a user has exceeded their allowed login attempts. If so, it redirects the user with a flash message, preventing further login attempts. ```php $identity = 'ben.edmunds@gmail.com'; if ($this->ionAuth->isMaxLoginAttemptsExceeded($identity)) { $this->session->markAsFlashdata('message', 'You have too many login attempts'); redirect()->to('welcome/index'); } ``` -------------------------------- ### PHP: Retrieve Users with ionAuth->users() Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Examples demonstrating various ways to retrieve users using the `ionAuth->users()` method, including getting all users, users by single group ID/name, and users by multiple group IDs/names. ```PHP // get all users $users = $this->ionAuth->users()->result(); ``` ```PHP // get users from group with id of '1' $users = $this->ionAuth->users(1)->result(); ``` ```PHP // get users from 'members' group $users = $this->ionAuth->users('members')->result(); ``` ```PHP // get users from 'admin' and 'members' group $users = $this->ionAuth->users(array('admin', 'members'))->result(); ``` ```PHP // get users from 'admin' group, 'members' group and group with id '4' $users = $this->ionAuth->users(array('admin', 4, 'members'))->result(); ``` -------------------------------- ### PHP: Get Errors as Array Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md Example demonstrating how to retrieve error messages as an array and iterate through them for display. ```PHP $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; } } ``` -------------------------------- ### Example: Manually Increase Login Attempts (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This PHP example shows how to manually call `increaseLoginAttempts` after a failed login attempt. This is useful for custom login flows or when the automatic call by `login()` is not sufficient, ensuring accurate tracking. ```php $identity = 'ben.edmunds@gmail.com'; $password = '12345678'; if ($this->ionAuth->login($identity, $password) == FALSE) { $this->ionAuth->increaseLoginAttempts($identity); } ``` -------------------------------- ### Registering Event Hooks with IonAuth setHook() in PHP Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html This comprehensive PHP example demonstrates how to integrate `setHook()` within a CodeIgniter controller. It shows the setup of multiple hooks (e.g., for email, Twitter, MailChimp, Facebook, Google Plus) to respond to a 'socialpush' event, illustrating how different methods can be registered to the same event. It also includes the `triggerEvents()` call to activate these hooks. ```PHP 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; } } ``` -------------------------------- ### PHP: Get User's Groups with ionAuth Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example demonstrating how to retrieve all groups a specific user belongs to using the `ionAuth->getUsersGroups()` method. ```PHP $user_groups = $this->ionAuth->getUsersGroups($user->id)->result(); ``` -------------------------------- ### Seed Ion Auth Database with Default Data Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/INSTALLING.md These snippets provide the CodeIgniter `spark` commands to populate the Ion Auth database with default data using the provided seeder. One variant is for Windows, and the other for Linux, differing in backslash escaping for the namespace. ```shell $ php spark db:seed IonAuth\Database\Seeds\IonAuthSeeder ``` ```shell $ php spark db:seed IonAuth\\Database\\Seeds\\IonAuthSeeder ``` -------------------------------- ### Example: Register User if Email Not Taken (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This PHP example demonstrates how to use `emailCheck` to determine if an email is available before registering a new user. It integrates with typical form validation concepts, ensuring unique email addresses. ```php //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); } ``` -------------------------------- ### PHP: Update Group Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md Example demonstrating how to update an existing group's name and description, and check for success or failure. ```PHP // 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 } ``` -------------------------------- ### Ion Auth register() Method and Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Registers a new user in the system. This snippet details the method signature, required and optional parameters (identity, password, email, additional data, groups), return type, and a PHP example for creating a user with extended profile information and group assignment. ```APIDOC register(string $identity, string $password, string $email, array $additionalData=[], array $groups=[]): mixed identity: 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. password: REQUIRED. email: REQUIRED. additionalData: OPTIONAL. Multidimensional array of additional user data. groups: OPTIONAL. Array of group IDs. If not passed the default group name set in the config will be used. Returns: mixed. The ID of the user if the user was successfully created, FALSE if the user was not created. ``` ```PHP $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); ``` -------------------------------- ### Extend Ion Auth Controller for Customization Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/INSTALLING.md This PHP snippet demonstrates how to create a custom authentication controller in your application by extending the `IonAuth\Controllers\Auth` class. It also shows how to optionally override the views folder for custom authentication views. ```php 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); } ``` -------------------------------- ### IonAuth `user()` Method API and Usage in PHP Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This section documents the `user()` method of the IonAuth library, which retrieves user information. It details the method signature, parameters (optional user ID), return type (model object), and provides a PHP example to fetch and display a user's email. ```APIDOC user(int $id=0): self Parameters: id: integer OPTIONAL. If a user id is not passed the id of the currently logged in user will be used. Return: model object ``` ```php $user = $this->ionAuth->user()->row(); echo $user->email; ``` ```php 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 ) ``` -------------------------------- ### PHP: Set Message Template Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md Example showing how to update a user and then set a custom message template before displaying messages or errors. ```PHP $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; } ``` -------------------------------- ### Configure Ion Auth Routes in CodeIgniter Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/INSTALLING.md This PHP snippet illustrates how to define a group of routes for Ion Auth within CodeIgniter's `Config\Routes.php` file. It maps common authentication actions like login, logout, and password reset to the Ion Auth controller methods. ```php $routes->group('auth', ['namespace' => 'IonAuth\Controllers'], function ($routes) { $routes->add('login', 'Auth::login'); $routes->get('logout', 'Auth::logout'); $routes->add('forgot_password', 'Auth::forgot_password'); // $routes->get('/', 'Auth::index'); // $routes->add('create_user', 'Auth::create_user'); // $routes->add('edit_user/(:num)', 'Auth::edit_user/$1'); // $routes->add('create_group', 'Auth::create_group'); // $routes->get('activate/(:num)', 'Auth::activate/$1'); // $routes->get('activate/(:num)/(:hash)', 'Auth::activate/$1/$2'); // $routes->add('deactivate/(:num)', 'Auth::deactivate/$1'); // $routes->get('reset_password/(:hash)', 'Auth::reset_password/$1'); // $routes->post('reset_password/(:hash)', 'Auth::reset_password/$1'); // ... }); ``` -------------------------------- ### PHP: Delete Group Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md Example demonstrating how to delete a group by its ID and handle the outcome. ```PHP // 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 } ``` -------------------------------- ### API Reference: ionAuth->addToGroup() Method Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Documents the `addToGroup()` method, which adds a user to one or more specified groups. Returns TRUE if the user was successfully added, FALSE otherwise. No usage example provided in the source text. ```APIDOC addToGroup($groupIds, int $userId=0): int Parameters: groupIds: integer or array REQUIRED. userId: integer REQUIRED. Return: boolean. TRUE if the user was added to group(s) FALSE if the user is not added to group(s). ``` -------------------------------- ### Configure PSR-4 Autoloading for Ion Auth Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/INSTALLING.md This PHP snippet demonstrates how to add the IonAuth namespace to the PSR-4 autoload configuration in CodeIgniter's `Config/Autoload.php` file, allowing the framework to locate Ion Auth classes. ```php public $psr4 = [ ... 'IonAuth' => ROOTPATH . 'CodeIgniter-Ion-Auth', ... ]; ``` -------------------------------- ### Ion Auth logout() Method and Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Logs the currently authenticated user out of the system. This snippet provides the method signature, return type, and a simple PHP usage example. ```APIDOC logout(): bool Returns: boolean. ``` ```PHP $this->ionAuth->logout(); ``` -------------------------------- ### Using Ion Auth `emailCheck()` for User Registration Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example demonstrating the usage of `emailCheck()` to prevent duplicate email registrations. It shows how to check if an email exists before proceeding with user registration. ```php //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); } ``` -------------------------------- ### Seed Default Ion Auth Data Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md These commands insert default user data into the database for Ion Auth. This is typically used for initial setup or testing. Ensure CodeIgniter's `Config\Migrations:enabled` is set to `true` before running. ```console $ php spark db:seed IonAuth\Database\Seeds\IonAuthSeeder ``` ```console $ php spark db:seed IonAuth\\Database\\Seeds\\IonAuthSeeder ``` -------------------------------- ### Retrieving Failed Login Attempt Count with Ion Auth Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example showing how to retrieve the number of failed login attempts for a given identity using `getAttemptsNum()`. ```php $identity = 'ben.edmunds@gmail.com'; $num_attempts = $this->ionAuth->getAttemptsNum($identity); ``` -------------------------------- ### Delete Group (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example demonstrating how to use the `deleteGroup` method to remove a group, including error handling. ```PHP // 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 } ``` -------------------------------- ### Ion Auth: Check User Group Membership Usage (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Comprehensive examples demonstrating how to use `inGroup()` to verify a user's membership in single or multiple groups. It covers checking by group name, ID, and the 'check all' functionality for multiple groups. ```PHP # 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'); } ``` -------------------------------- ### IonAuth `groups()` Method API and Usage in PHP Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This section describes the `groups()` method of the IonAuth library, which retrieves all available groups. It outlines the method signature, return type (array of objects), and provides a PHP example for fetching and processing the list of groups. ```APIDOC groups() Return: array of objects ``` ```php $groups = $this->ionAuth->groups()->result(); ``` -------------------------------- ### Clearing Login Attempts on Successful Login with Ion Auth Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example showing how to use `clearLoginAttempts()` to reset failed login attempt counts after a successful user login. ```php $identity = 'ben.edmunds@gmail.com'; $password = '12345678'; if ($this->ionAuth->login($identity, $password) == TRUE) { $this->ionAuth->clearLoginAttempts($identity); } ``` -------------------------------- ### Update Existing Group (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Usage example for the `updateGroup` method, showing how to update a group's name and additional data, with error checking. ```PHP // 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 } ``` -------------------------------- ### Ion Auth: Check Username Availability Usage (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html A simple example demonstrating the use of `usernameCheck()` to determine if a username is already taken. This method is typically integrated with form validation processes. ```PHP //This is a lame example but it works. Usually you would use this method with form_validation. $username = $this->input->post('username'); ``` -------------------------------- ### Add User to Group (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Demonstrates how to add a user to one or multiple groups using the `addToGroup` method of the Ion Auth library. Examples show adding to an array of group IDs or a single group ID. ```PHP // 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); ``` -------------------------------- ### IonAuth `users()` Method API and Usage in PHP Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This section details the `users()` method for retrieving multiple users from the IonAuth library. It explains how to filter users by groups using optional parameters and provides various PHP examples for fetching all users or users belonging to specific groups by ID or name. ```APIDOC users($groups=null): self Parameters: 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: model object ``` ```php // get all users $users = $this->ionAuth->users()->result(); ``` ```php // get users from group with id of '1' $users = $this->ionAuth->users(1)->result(); ``` ```php // get users from 'members' group $users = $this->ionAuth->users('members')->result(); ``` ```php // get users from 'admin' and 'members' group $users = $this->ionAuth->users(array('admin', 'members'))->result(); ``` ```php // get users from 'admin' group, 'members' group and group with id '4' $users = $this->ionAuth->users(array('admin', 4, 'members'))->result(); ``` -------------------------------- ### Ion Auth: Check User Admin Status Usage (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example of using `isAdmin()` to restrict access to certain pages. If the user is not an administrator, a flash message is set, and they are redirected. ```PHP if (!$this->ionAuth->isAdmin()) { $this->session->markAsFlashdata('message', 'You must be an admin to view this page'); redirect()->to('welcome/index'); } ``` -------------------------------- ### Ion Auth deleteUser() Method and Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Deletes a user from the system. This snippet provides the method signature, parameters (user ID), return type, and a PHP example for deleting a user by their ID. ```APIDOC deleteUser(int $id): bool id: REQUIRED. User ID. Returns: boolean. TRUE if the user was successfully deleted FALSE if the user was not deleted. ``` ```PHP $id = 12; $this->ionAuth->deleteUser($id); ``` -------------------------------- ### Extend Ion Auth Configuration Class Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/INSTALLING.md This PHP snippet illustrates how to create a custom `IonAuth.php` configuration file in your application's `Config` directory. It extends the base IonAuth configuration class, allowing you to override default settings like site title, admin email, and email templates. ```php 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'); ``` -------------------------------- ### Ion Auth: Check Forgotten Password Code Usage (PHP) Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example demonstrating how to use `forgottenPasswordCheck()` to verify a password reset code. If the code is valid, it allows displaying a password reset form. ```PHP $user = $this->ionAuth->forgottenPasswordCheck($code); if ($user) { //display the password reset form } ``` -------------------------------- ### Using Ion Auth `identityCheck()` for User Update Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example demonstrating the usage of `identityCheck()` when updating user information. It checks if the new identity is unique or matches the current user's identity before updating. ```php //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); } ``` -------------------------------- ### Ion Auth update() Method and Usage Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Updates an existing user's information. This snippet includes the method signature, parameters (user ID, data array), return type, and a PHP example demonstrating how to modify user details like first name, last name, and password. ```APIDOC update(int $id, array $data): bool id: REQUIRED. User ID. data: REQUIRED. Multidimensional array of user data to update. Returns: boolean. TRUE if the user was successfully updated FALSE if the user was not updated. ``` ```PHP $id = 12; $data = array( 'first_name' => 'Ben', 'last_name' => 'Edmunds', 'password' => '123456789' ); $this->ionAuth->update($id, $data); ``` -------------------------------- ### PHP: Get a Specific Group by ID with ionAuth Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example demonstrating how to retrieve a specific user group using its ID with the `ionAuth->group()` method. ```PHP $groupId = 2; $group = $this->ionAuth->group($groupId)->result(); ``` -------------------------------- ### IonAuth `messages()` Method API and Usage in PHP Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This section documents the `messages()` method of the IonAuth library, used to retrieve success messages as a string after an operation. It details the method signature, string return type, and provides a PHP example demonstrating how to display messages or errors after updating a user. ```APIDOC messages(): string Return: string ``` ```php $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; } ``` -------------------------------- ### Registering a New User with Ion Auth Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Demonstrates how to register a new user using the `ionAuth` library, including collecting user input for password, email, first name, and last name, and checking for existing usernames before registration. ```php $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); } ``` -------------------------------- ### PHP: Get Current User Email with ionAuth Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Example demonstrating how to retrieve the currently logged-in user's object and access their email property using the `ionAuth->user()` method. ```PHP $user = $this->ionAuth->user()->row(); echo $user->email; ``` -------------------------------- ### Ion Auth Configuration Reference Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md Detailed configuration options for the CodeIgniter Ion Auth library, covering authentication, cookie, email, and template settings. Each option includes its purpose, default value, and any important notes or considerations. ```APIDOC Authentication options: siteTitle: description: The title of your site, used for email. adminEmail: defaultValue: 'admin@example.com' description: Your administrator email address. defaultGroup: defaultValue: 'members' description: Name of the default user group. adminGroup: defaultValue: 'admin' description: Name of the admin group. identity: defaultValue: 'email' description: Column to use for uniquely identifing user/logging in/etc. Usual choices are 'email' OR 'username', but any unique key from your table can be used as identity. notes: IMPORTANT: If you are changing it from the default (email), update the UNIQUE constraint in your DB. minPasswordLength: defaultValue: '8' description: Minimum length of passwords. This minimum is not enforced directly by the library. The controller should define a validation rule to enforce it. See the Auth controller for an example implementation. notes: Additional note: the library will fail for empty password or password size above 4096 bytes. This is an arbitrary (long) value to protect against DOS attack. emailActivation: defaultValue: 'false' description: TRUE or FALSE. Sets whether to require email activation or not. manualActivation: defaultValue: 'false' description: TRUE or FALSE. Sets whether to require manual activation (probably by an admin user) or not. rememberUsers: defaultValue: 'true' description: true or false. Sets whether to enable 'remember me' functionality or not. userExpire: defaultValue: '86500' description: Sets how long to remember the user for in seconds. Set to zero for no expiration. userExtendonLogin: defaultValue: 'false' description: TRUE or FALSE. Extend the users session expiration on login. trackLoginAttempts: defaultValue: 'false' description: Track the number of failed login attempts for each user or ip (see trackLoginIpAddress option). trackLoginIpAddress: defaultValue: 'true' description: Track login attempts by IP Address, if FALSE will track based on identity. maximumLoginAttempts: defaultValue: 3 description: Set the maximum number of failed login attempts. This maximum is not enforced by the library, but is used by $this->ionAuth->isMaxLoginAttemptsExceeded(). The controller should check this function and act appropriately. If set to 0, there is no maximum. forgotPasswordExpiration: defaultValue: 1800 description: Number of seconds before a forgot password request expires. If set to 0, requests will not expire. 30 minutes to 1 hour are good values (enough for a user to receive the email and reset its password). notes: You should not set a value too high (or 0), as it could lead to security issue! recheckTimer: defaultValue: 0 description: The number of seconds after which the session is checked again against database to see if the user still exists and is active. notes: Leave 0 if you don't want session recheck. if you really think you need to recheck the session against database, we would recommend a higher value, as this would affect performance. Cookie options: rememberCookieName: defaultValue: 'remember_code' description: Cookie name for the "Remember me" feature. Email options: emailType: defaultValue: 'html' description: Email content type. Templates options: emailTemplates: defaultValue: 'auth/email/' description: Folder where the email view templates are stored. emailActivate: defaultValue: 'activate.tpl.php' description: Filname of the email activation view template. emailForgotPassword: defaultValue: 'forgot_password.tpl.php' description: Filname of the forgot password email view template. ``` -------------------------------- ### CodeIgniter Ion Auth Configuration Parameters Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md Comprehensive documentation for configuring database table names, join columns, and password hashing methods (bcrypt and Argon2) including their specific parameters and security recommendations within the CodeIgniter Ion Auth library. ```APIDOC tables: groups: default: 'groups' description: The table name to use for the groups table. users: default: 'users' description: The table name to use for the users table. users_groups: default: 'users_groups' description: The table name to use for the users groups table. login_attempts: default: 'login_attempts' description: The table name to use for the login attempts table. join: users: default: 'user_id' description: Users table column you want to join WITH. groups: default: 'group_id' description: Group table column you want to join WITH. hashMethod: default: 'bcrypt' description: The method to hash the password before storing in database. Options: 'bcrypt' (PHP 5.3+) or 'argon2' (PHP 7.2+). Argon2 is recommended. Passwords are automatically salted. bcryptSpecificOptions: bcryptDefaultCost: default: 10 description: Defines encryption strength for default users. Higher cost increases CPU usage. Adjust based on server hardware. Recommended to benchmark. Not recommended to use a value less than 10 (in 2018). bcryptAdminCost: default: 12 description: Same as bcryptDefaultCost, but for users in the admin group. Recommended to have stronger hashing for administrators. argon2SpecificOptions: argon2DefaultParams: default: "['memory_cost' => 1 << 12, 'time_cost' => 2, 'threads' => 2]" description: Array containing the options for the Argon2 algorithm for default users. parameters: memory_cost: Maximum memory (in kBytes) that may be used to compute the Argon2 hash. Spec recommends setting to a power of 2. time_cost: Number of iterations (used to tune the running time independently of the memory size). Defines encryption strength. threads: Number of threads to use for computing the Argon2 hash. Spec recommends setting to a power of 2. argon2AdminParams: default: "['memory_cost' => 1 << 14, 'time_cost' => 4, 'threads' => 2]" description: Same as argon2DefaultParams, but for users in the admin group. Recommended to have stronger hashing for administrators. ``` -------------------------------- ### Run Ion Auth Database Migrations Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/userguide/index.html Executes the latest database migrations for the Ion Auth library using CodeIgniter's `spark` command-line tool. This ensures the necessary database tables are created or updated. ```Shell $ php spark migrate:latest -n IonAuth ``` -------------------------------- ### Load Ion Auth Library in CodeIgniter Source: https://github.com/benedmunds/codeigniter-ion-auth/blob/4/USERGUIDE.md This PHP code demonstrates how to instantiate the Ion Auth library in a CodeIgniter application. The library can also be autoloaded for convenience by configuring CodeIgniter's autoload settings. ```php $ionAuth = new \IonAuth\Libraries\IonAuth(); ```