A user, group, role and permission management for Codeigniter 4

Overview

CI4-Auth

PHP Bootstrap 5 Font Awesome Maintained

CI4-Auth is a user, group, role and permission management library for Codeigniter 4.

CI4-Auth is based on the great Myth-Auth library for Codeigniter 4. Due credits go to its author Lonnie Ezell and the team for this awesome work.

I started customizing Myth-Auth to meet my specific requirements but after a while I noticed that my changes got quite large. I decided to build CI4-Auth based on Myth-Auth, changing and adding features I needed for my projects.

Requirements

  • PHP 7.3+, 8.0+ (Attention: PHP 8.1 not supported yet by CI 4 as of 2022-01-01)
  • CodeIgniter 4.0.4+

Features

  • Core Myth-Auth features
  • Role objects are consistently called "role" in the code (e.g. tables, variables, classes)
  • Added "Groups" as an addl. object, functioning just like roles
  • Separated user controller functions from the Auth Controller
  • Added views to manage users, groups, roles and permissions
  • Added Bootstrap 5 and Font Awesome 5 support
  • Added database seeders to create sample data
  • Removed all languages but English and German (I don't speak anything else :-) )

Installation

Install Codeigniter

Install an appstarter project with Codigniter 4 as described here.

Make sure your app and database is configured right and runs fine showing the Codigniter 4 welcome page.

Download CI4-Auth

Download the CI4-Auth archive from this repo here.

Copy CI4-Auth to your ThirdParty folder

Note: CI4-Auth is not available as a Composer package yet. It works from your ThirdParty folder.

Unzip the CI4-Auth archive and copy the 'lewe' directory to your \app\ThirdParty folder in your Codeigniter project. You should see this tree section then:

project-root
- app
  - ThirdParty
    - lewe
      - ci4-auth
        - src

Configuration

  1. Add the Psr4 path in your app/Config/Autoload.php file as follows:
public $psr4 = [
    APP_NAMESPACE  => APPPATH, // For custom app namespace
    'Config'       => APPPATH . 'Config',
    'CI4\Auth'     => APPPATH . 'ThirdParty/lewe/ci4-auth/src',
];
  1. Edit app/Config/Validation.php and add the following value to the ruleSets array:
public $ruleSets = [
    Rules::class,
    FormatRules::class,
    FileRules::class,
    CreditCardRules::class,
    \CI4\Auth\Authentication\Passwords\ValidationRules::class
];
  1. The "Remember Me" functionality is turned off by default. It can be turned on by setting the $allowRemembering variable to true in lewe/ci4-auth/src/Config/Auth.php.

  2. Edit app/Config/Email.php and verify that fromName and fromEmail are set as they are used when sending emails for password resets, etc.

Routes

The CI4-Auth routes are defined in lewe/ci4-auth/src/Config/Routes.php. Copy the routes group from there to your app/Config/Routes.php file, right after the 'Route Definitions' header comment.

/*
* --------------------------------------------------------------------
* Route Definitions
* --------------------------------------------------------------------
*/
//
// CI4-Auth Routes
//
$routes->group('', ['namespace' => 'CI4\Auth\Src\Controllers'], function ($routes) {

    // Sample route with role filter
    // $routes->match(['get', 'post'], 'roles', 'RoleController::index', ['filter' => 'role:Administrator']);

    $routes->get('/', 'AuthController::welcome');
    
    ...

});

Views

The views that come with CI4-Auth are based on Bootstrap 5 and Font Awesome 5.

If you like to use your own view you can override them editing the $views array in lewe/ci4-auth/src/Config/Auth.php:

public $views = [

    // Welcome page
    'welcome'            => 'CI4\Auth\Views\welcome',

    // Auth
    'login'              => 'CI4\Auth\Views\auth\login',
    'register'           => 'CI4\Auth\Views\auth\register',
    'forgot'             => 'CI4\Auth\Views\auth\forgot',
    'reset'              => 'CI4\Auth\Views\auth\reset',

    // Groups
    'groups'             => 'CI4\Auth\Views\groups\list',
    'groupsCreate'       => 'CI4\Auth\Views\groups\create',
    'groupsEdit'         => 'CI4\Auth\Views\groups\edit',

    // Permissions
    'permissions'        => 'CI4\Auth\Views\permissions\list',
    'permissionsCreate'  => 'CI4\Auth\Views\permissions\create',
    'permissionsEdit'    => 'CI4\Auth\Views\permissions\edit',

    // Roles
    'roles'              => 'CI4\Auth\Views\roles\list',
    'rolesCreate'        => 'CI4\Auth\Views\roles\create',
    'rolesEdit'          => 'CI4\Auth\Views\roles\edit',

    // Users
    'users'              => 'CI4\Auth\Views\users\list',
    'usersCreate'        => 'CI4\Auth\Views\users\create',
    'usersEdit'          => 'CI4\Auth\Views\users\edit',

    // Emails
    'emailForgot'        => 'CI4\Auth\Views\emails\forgot',
    'emailActivation'    => 'CI4\Auth\Views\emails\activation',
];

Database Migration

Assuming that your database is setup correctly but still empty you need to run the migrations now.

Copy the file lewe/ci4-auth/src/Database/Migrations/2021-12-14-000000_create_auth_tables.php to app/Database/Migrations. Then run the command:

> php spark migrate

Database Seeding

Assuming that the migrations have been completed successfully, you can run the seeders now to create the CI4-Auth sample data.

Copy the files lewe/ci4-auth/src/Database/Seeds/*.php to app/Database/Seeds. Then run the following command:

> php spark db:seed CI4AuthSeeder

Run Application

Start your browser and navigate to your public directory. Use the menu to check out the views that come with CI4-Auth.

Services

The Services did not change and are from the Myth-Auth core. See there for their documentation.

Helper Functions (Auth)

In addition to the helper functions that come with Myth-Auth, CI4-Auth provides these:

dnd()

  • Function: Dump'n'Die. Returns a preformatted output of objects and variables.
  • Parameters: Variable/Object, Switch to die after output or not
  • Returns: Preformatted output

in_groups()

  • Function: Ensures that the current user is in at least one of the passed in groups.
  • Parameters: Group IDs or names (single item or array of items)
  • Returns: true or false Note: This is not the same helper as in Myth-Auth since Myth-Auth is inconcistent in using the terms 'group' and 'role'.

in_roles()

  • Function: Ensures that the current user is in at least one of the passed in roles.
  • Parameters: Role IDs or names (single item or array of items).
  • Returns: true or false Note: This is comparable to the in_groups() helper function in Myth-Auth.

Helper Functions (Bootstrap 5)

In order to create Bootstrap objects quicker and to avoid duplicating code in views, these helper functions are provided:

bs5_alert()

  • Function: Creates a Bootstrap 5 alert box.
  • Parameters: Array with alert box details.
  • Returns: HTML

bs5_cardheader()

  • Function: Creates a Bootstrap card header.
  • Parameters: Array with card header details.
  • Returns: HTML

bs5_formrow()

  • Function: Creates a two-column form field div (text, email, select, password).
  • Parameters: Array with form field details.
  • Returns: HTML

bs5_modal()

  • Function: Creates a modal dialog.
  • Parameters: Array with modal dialog details.
  • Returns: HTML

bs5_searchform()

  • Function: Creates a search form field.
  • Parameters: Array with search form details.
  • Returns: HTML

Disclaimer

The CI4-Auth library is not perfect. It may very well contain bugs or things that can be done better. If you stumble upon such things, let me know. Otherwise I hope the library will help you. Feel free to change anything to meet the requirements in your environment.

Enjoy, George Lewe

Comments
  • Creating a new user

    Creating a new user

    Dear sir, Thankyou for your Authentication software CI4-Auth I have started to use it and it is very helpful. It would be great if when I create a new user through the website itself as an administrator could force a reset password when the new user logs in the first time.

    opened by stezam 8
  • Resend Activation Email

    Resend Activation Email

    Sorry to be a pest again. There seem to be a problem when one asks to resend the activation email. It seems that is not posting the token so it is always returning the error that account is not found.

    Thanks Good Day

    opened by stezam 6
  • Problem running first database migration against SQLServer

    Problem running first database migration against SQLServer

    Hi I'm having some trouble while running first database migrations, therefore I cannot execute database seed I'm using latest CI4 with SQLServer Express 2019

    php spark migrate

    CodeIgniter v4.1.9 Command Line Tool - Server Time: 2022-04-19 11:41:34 UTC-03:00
    Running all new migrations...
    [Exception]
    [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Foreign key 'auth_tokensuser_id_foreign' references invalid table 'users'.
    at SYSTEMPATH/Database/SQLSRV/Connection.php:459
    

    The only 2 tables that are created (and I guess partially) are auth_logins and users

    Thanks in advance for any advise

    opened by kabeza 4
  • Passwords cannot contain re-hashed personal information

    Passwords cannot contain re-hashed personal information

    Getting this error on my first user registration and cannot figure out why. From what I can read into the code, it should not be triggering. Suggestions?

    Email: [email protected] UserName: Marc Password: 2ijkU0LJB5dB705!DFlvo$I <-- I am not using this obviously (since I just posted it) but it is one that fails.

    What in that password is "Personal"?

    opened by MarcPinnell 3
  • Error using Filter

    Error using Filter

    When I use The filters of CI4 Keep getting the wrong uri and therefore error 403 cannot figure ou why. Can you hel me please?

    CONFIG/Routes

    $routes->group('', ['filter'=>'roleFilter:1'], ['namespace' => 'CI4\Auth\Controllers'], function ($routes) {
    
        // Sample route with role filter
        // $routes->match(['get', 'post'], 'roles', 'RoleController::roles', ['filter' => 'roleFilter:Administrator']);
        // Authentication
    
        // Groups
        $routes->match(['get', 'post'], 'groups',  'GroupController::groups', ['as' => 'groups']);
        $routes->get('groups/create', 'GroupController::groupsCreate', ['as' => 'groupsCreate']);
        $routes->post('groups/create',  'GroupController::groupsCreateDo');
        $routes->get('groups/edit/(:num)', 'GroupController::groupsEdit/$1', ['as' => 'groupsEdit']);
        $routes->post('groups/edit/(:num)', 'GroupController::groupsEditDo/$1');
    
    -------------------------------------------------------------------------------------------------------------------------------
    **RoleFilter**
    
        public function before(RequestInterface $request, $params = null)
        {
            if (!function_exists('logged_in')) helper('auth');
    
    
            if (empty($params)) return;
    
            $authenticate = service('authentication');
    
            // if no user is logged in then send to the login form
            if (!$authenticate->check()) {
                session()->set('redirect_url', current_url());
                return redirect('login')->with('t_warning' ,'You need to be logged in to perform this operation!');
            }
    
            $authorize = service('authorization');
    
            // Check each requested permission
            foreach ($params as $role) {
                if ($authorize->inRole($role, $authenticate->id())) return;
            }
    
            if ($authenticate->silent()) {
                $redirectURL = session('redirect_url') ?? '/';
                unset($_SESSION['redirect_url']);
                return redirect()->to($redirectURL)->with('error', lang('Auth.exception.insufficient_permissions'));
    
            } else {
                throw new PermissionException(lang('Auth.exception.insufficient_permissions'));
            }
        }
    
    -------------------------------------------------------------------------------------------------------------------------------------
    **Config Filters**
    
    namespace Config;
    use CodeIgniter\Config\BaseConfig;
    use CodeIgniter\Filters\CSRF;
    use CodeIgniter\Filters\DebugToolbar;
    use CodeIgniter\Filters\Honeypot;
    use CodeIgniter\Filters\InvalidChars;
    use CodeIgniter\Filters\SecureHeaders;
    use \CI4\Auth\Filters\GroupFilter;
    use \CI4\Auth\Filters\LoginFilter;
    use \CI4\Auth\Filters\PermissionFilter;
    use \CI4\Auth\Filters\RoleFilter;
    
    
    class Filters extends BaseConfig
    {
        /**
         * Configures aliases for Filter classes to
         * make reading things nicer and simpler.
         *
         * @var array
         */
        public $aliases = [
            'csrf'              => CSRF::class,
            'toolbar'           => DebugToolbar::class,
            'honeypot'          => Honeypot::class,
            'invalidchars'      => InvalidChars::class,
            'secureheaders'     => SecureHeaders::class,
            'loginFilter'       => LoginFilter::class,
            'groupFilter'       => GroupFilter::class,
            'roleFilter'        => RoleFilter::class,
            'permissionFilter'  => PermissionFilter::class,
    
        ];
    
    ----------------------------------------------------------------------------------------------------------------------------------------
    

    ** The Error I get ** 404 - File Not Found Controller or its method is not found: \App\Controllers\GroupController::groups

    opened by stezam 2
  • Bootstrap 5 Helper load

    Bootstrap 5 Helper load

    Hi, For the Authorization part views to work ok with bootstrap 5, you need to call bs5 helper. Otherwise views do not renders ok. I did it including this line on every construct function of the Groups, Permissions, Roles and Users controllers: helper('bs5_helper');

    Thanks for the good job with CI4-Auth

    opened by treborin 1
  • Install instructions

    Install instructions

    Install instructions

    Oops $routes->group('', ['namespace' => 'CI4\Auth\Src\Controllers'], function ($routes) {

    This works :-) $routes->group('', ['namespace' => 'CI4\Auth\Controllers'], function ($routes) {

    Typo!

    regard JvdSl1

    documentation 
    opened by janvandersleen 1
Releases(v1.5.0)
Owner
George Lewe
George Lewe
Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system.

Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system. Built on Bootstrap 4.

Jeremy Kenedy 2.8k Dec 31, 2022
GUI manager for RBAC (Role Base Access Control) Yii2. Easy to manage authorization of user

RBAC Manager for Yii 2 GUI manager for RBAC (Role Base Access Control) Yii2. Easy to manage authorization of user ?? . Documentation Important: If you

MDMunir Software 1.2k Jan 7, 2023
The easiest and most intuitive way to add access management to your Filament Resource Models through `spatie/laravel-permission`

Filament Shield The easiest and most intuitive way to add access management to your Filament Resource Models (more coming soon ?? ) One Plugin to rule

Bezhan Salleh 329 Jan 2, 2023
Yet another asynchronous permission management plugin for PocketMine-MP.

GroupsAPI Yet another asynchronous permission management plugin for PocketMine-MP. Features Developer-friendly API Temporary rank/group support Multip

null 19 Nov 28, 2022
Role-based Permissions for Laravel 5

ENTRUST (Laravel 5 Package) Entrust is a succinct and flexible way to add Role-based Permissions to Laravel 5. If you are looking for the Laravel 4 ve

Zizaco 6.1k Jan 5, 2023
Light-weight role-based permissions system for Laravel 6+ built in Auth system.

Kodeine/Laravel-ACL Laravel ACL adds role based permissions to built in Auth System of Laravel 8.0+. ACL middleware protects routes and even crud cont

Kodeine 781 Dec 15, 2022
Manage authorization with granular role-based permissions in your Laravel Apps.

Governor For Laravel Manage authorization with granular role-based permissions in your Laravel apps. Goal Provide a simple method of managing ACL in a

GeneaLabs, LLC 149 Dec 23, 2022
This package helps you to associate users with permissions and permission groups with laravel framework

Laravel ACL This package allows you to manage user permissions and groups in a database, and is compatible with Laravel v5.8 or higher. Please check t

Mateus Junges 537 Dec 28, 2022
Tools for checking malware, permission of file php and any on website

webtools Tools for checking malware, permission of file php and any on website You can use the webtools.php file directly. All features can be accesse

ForDeveloperTools 3 Jun 14, 2022
permission generation for all your declared routes with corresponding controller action

Permissions Generator This package add some artisan command to help generating permissions for your declared routes. Each route should have an alias (

Diagana Mouhamed Fadel 4 Nov 30, 2022
Nginx FastCGI Fix Permission

Nginx FastCGI Fix Permission Table of Contents About How it works Installation Changelog Contributing License About This library was born with the obj

Ejetar 3 Mar 14, 2022
Hierarchical Rol-Permission Based Laravel Auth Package with Limitless Hierarchical Level of Organizations

AAuth for Laravel Hierarchical Rol-Permission Based Laravel Auth Package with Limitless Hierarchical Level of Organizations Features Organization Base

Aurora Web Software Team 23 Dec 27, 2022
UserFrosting is a secure, modern user management system written in PHP and built on top of the Slim Microframework, Twig templating engine, and Eloquent ORM.

UserFrosting is a secure, modern user management system written in PHP and built on top of the Slim Microframework, Twig templating engine, and Eloquent ORM.

UserFrosting 1.6k Jan 1, 2023
Tech-Admin is Laravel + Bootstrap Admin Panel With User Management And Access Control based on Roles and Permissions.

Tech-Admin | Laravel 8 + Bootstrap 4 Tech-Admin is Admin Panel With Preset of Roles, Permissions, ACL, User Management, Profile Management. Features M

TechTool India 39 Dec 23, 2022
Authentication and authorization library for Codeigniter 4

Authentication and Authorization Library for CodeIgniter 4. This library provides an easy and simple way to create login, logout, and user registratio

Rizky Kurniawan 12 Oct 10, 2022
Armor - User and Session Management

User and session management. Provides solid base foundation for development of custom user management system.

Matt Dizak 3 Apr 13, 2022
Mock authentication for CodeIgniter 4

Tatter\Imposter Mock authentication for CodeIgniter

Tatter Software 3 Feb 16, 2022
Multi captcha package for CodeIgniter 4.x

Multi captcha package for CodeIgniter 4.x. Support Arcaptcha(a free and professional Iranian product),Bibot(a free Iranian product),Recaptcha(an googel product) and hCaptcha.

Pooya Parsa Dadashi 14 Dec 13, 2022
Painless OAuth 2.0 Server for CodeIgniter 4 🔥

Inspired from the Norse mythology, Heimdallr, modernly anglicized as Heimdall is the gatekeeper of Bifröst, the rainbow road connecting Midgard, realm

Ezra Lazuardy 37 Nov 12, 2022