dvivier/smarticops

Permission-based Authorization package for Laravel 5.2, includes Authentication, developed on behalf of smartic.ca

0.1.0 2016-05-13 19:40 UTC

This package is auto-updated.

Last update: 2024-10-29 04:25:33 UTC


README

Latest Version on Packagist Software License Total Downloads

Smarticops is a Laravel package allowing the administrator to manage users, roles, and permissions.

I - Features

  • Registering Users, Authentication
  • Email confirmation and Password Reset
  • Access Control List : Roles & Permissions
  • Logging Access & Administration operations

II - Requirements

  • Smarticops currently needs exactly Laravel version 5.2.x
  • It is not guaranteed that the package will work with other minor and major versions of Laravel.

III - Installation

Overview

  • Smarticops and Laravel

    Smarticops is intended to be installed right after Laravel. It uses and replaces the built-in authentication features provided by Laravel.
    Especially, since the package already contains Laravel authentication, you will not need to type $ php artisan make:auth.

  • The SuperAdmin

    There is one user which will always exist in the database (system record) called the SuperAdmin. It has the ID 1. It is associated with a permission named "sa" which is also a system record and will be permanent in the database.
    By default the SuperAdmin is the only user allowed to access the administration interface and to manage users, permissions and roles.

  • Dependencies

    The package requires "laravelcollective/html" for HTML forms, and "guzzlehttp/guzzle" for email API drivers.

Laravel

First, you need a fresh Laravel 5.2 installation.

$ composer create-project --prefer-dist laravel/laravel=5.2.* <project-name> 

Smarticops

The package installation is simply done via Composer. First, go to your new project directory. Then, ask Composer to install the package.

$ cd <project-name>
$ composer require dvivier/smarticops

IV - Configuration

Artisan command

There is an artisan command defined by Smarticops intended to make the configuration easier.

To be able to use this command, add the following provider in your config/app.php file :

    // file : config/app.php
    
    'providers' => [
        /* ... */
        
        Dvivier\Smarticops\Providers\SmarticopsServiceProvider::class,
    
    ],

Now that the Smarticops Service Provider is registered, the command is available.

The command will prompt you the necessary data and will modify some files. It will automatically do what is described to do in the rest of this section. Each command-line instruction is printed before being executed.

If you want to know precisely what this command does, you can look at the src/Console/Commands/SmarticopsSetupCommand file.

Note : This command has to be executed only once. It doesn't have to be executed when updating the package, except if it's clearly asked.

Before running the command, make sure you have correctly configured your database access in the .env file and your database server is running.

Type :

$ php artisan smarticops:setup

and follow the instructions.

  • When the command has successfully ended with the message 'Smarticops setup finished', you can now jump to the V - Usage section.

  • Otherwise, or if you don't want to use the automated process, continue reading this section for manual instructions.

Laravel

  • Add the following providers and aliases in your config/app.php file :
    // file : config/app.php
    
    'providers' => [
        /* ... */
        
        Collective\Html\HtmlServiceProvider::class,
        
        Dvivier\Smarticops\Providers\SmarticopsServiceProvider::class,
    
    ],
    
    'aliases' => [
        /* ... */
        
        'Form' => Collective\Html\FormFacade::class,
        'Html' => Collective\Html\HtmlFacade::class,
    ]

Form and Html components from the Laravel Collective community organisation are needed for forms in the administration panel.

  • Ask your app to register Smarticops' event listener in the app/Providers/EventServiceProvider file :
    class EventServiceProvider extends ServiceProvider
    {
    
        /**
         * The subscriber classes to register.
         *
         * @var array
         */
        protected $subscribe = [
            'Dvivier\Smarticops\Listeners\AuthEventListener',
        ];

The User Model

The basic Laravel installation provides a User class located at app/User.php :

    class User extends Authenticatable
    {

This class extends the Illuminate\Foundation\Auth\User class, and (indirectly) the Eloquent Model.

You have to make this class extend the Dvivier\Smarticops\User model, instead of the Auth\User class :

    use Dvivier\Smarticops\User as SmarticopsUser;
    class User extends SmarticopsUser
    {

Don't worry, Smarticops' User class already extends the Illuminate\Foundation\Auth\User class and consequently the Eloquent Model.

When you will need a user class for your application, use this App\User class.

Please note that even if your application doesn't need to manage users, you still have to do this manipulation in order for the authentication to work properly.

Smarticops

Smarticops adds a configuration file at config/smarticops.php. But you have to add additional config variables in your .env file :

// file : .env
APP_NAME=

SUPERADMIN_FIRSTNAME=
SUPERADMIN_LASTNAME=
SUPERADMIN_EMAIL=
SUPERADMIN_PASSWORD=

You MUST set the password, otherwise there will be a security issue because the default password (not secret) would be used.

To be considered, the SuperAdmin password has to be changed before running migrations in the next section.

The application name will be used in views and emails.

In the config/smarticops.php file you'll find the following configuration options :

  • Log path

    Smarticops will produce a different log file each day. You can configure the base filename and location for logs :

      'log_path' => 'logs/smarticops/smarticops',  
    
  • Email confirmation timeout

    For security reasons, the token sent to the user to confirm his email must have a timeout which is of 1 hour by default. This duration in minutes can be set here :

      'confirm_expire' => 60,
    
  • Password length

    You can adjust the minimum number of characters for passwords according to your security policy.
    Remember that the shorter a password is, the weaker.

      'password' => [
              // minimum number of characters for passwords
              'min' => 8,
              ],
    
  • Password reset view

    Smarticops provides another view for the password reset email. If you want to use it, change this line in your config/auth.php file :

      //file : config/auth.php
        
      'passwords' => [
          'users' => [
              'provider' => 'users',
              //'email' => 'auth.emails.password',            // change this line
              'email' => 'smarticops::auth.emails.password',  // into this one
              'table' => 'password_resets',
              'expire' => 60,
          ],
    

    ],

Migrations and Seeding

  • Prepare

After package installation, the migrations Smarticops need are added to database/migrations, and a seeder class is added at database/seeds/SmarticopsSeeder.php. The migrations will create the tables, and the seeder will insert the system records (SuperAdmin related records).

In order to do this, call the seeder in the base database/seeds/DatabaseSeeder file :

    public function run()
    {
        /* ... */
        $this->call(SmarticopsSeeder::class);
    }

Adapt if necessary the migrations code (especially for the users table) according to your application needs. You must change the superadmin password before running migrations, see the Configuration section above.

Before running the migrations, remove the two original migration files if present since they are replaced by smarticops' ones :

$ rm database/migrations/2014_10_12_000000_create_users_table.php
$ rm database/migrations/2014_10_12_100000_create_password_resets_table.php
  • Run

To run migrations and seed system records, in your project directory type :

$ php artisan migrate --seed

You must use the --seed option : it will insert the system records in the database.

In case of error or if you change something in these migration files, you can drop & re-create the tables (all existing data will be erased !) :

$ php artisan migrate:refresh --seed

Again, don't forget the --seed option.

V - Usage

About Permission Names

Constraints

Each permission has a unique name which describes itself. Example :

create.company

The permission name can only contain letters, numbers, dashes "-", periods "." and unserscores "_".
The permission name is case sensitive.

Convention

The package does not require the use of a specific format for permission names.
However, it is recommended to choose a convention and to use the same format for each permission in the application.
The recommended format is <action>.<object>.

Building Webpages

When building webpages, there are information and controls which are restricted to users with a given permission or role.

To check if the logged in user has a specific permission, use :

Auth::user()->hasPermission('code')

And to check if he has a specific role :

Auth::user()->hasRole('RoleName')
// You can also use the alias :
Auth::user()->is('RoleName')

An example with Laravel's Blade directives, to narrow the access to an information/control to users having a specific permission :

@if (Auth::user()->hasPermission('view.company.name'))
    <span>Company Name</span>
@endif

Administration Panel

Once the server is running, the administration interface is available for the SuperAdmin at <domain>/admin.

  • Permissions

See section About Permissions above for information about permission naming and convention. A permission has to be created before being given to users & roles.
Each permission has a description text precising its purpose.

  • Roles

Roles can be assigned to Users to precise their role in the application.
A user can be assigned zero, one or multiple roles.
The role name can only contain letters, numbers and underscores "_" and is case sensitive. Each role has a description text precising its purpose.

You can then assign some permissions to this role.
The checked permissions will be then be proposed when assigning this role to a user.

Please note that changing a role's permissions has no impact on users having this role.

  • Users

The user editing form allows the administrator to assign roles and permissions to the user.

Auto-filling Permissions by roles checking

Check the boxes of the roles you want to give to the user.
Each time you check a role, all the permissions corresponding to this role are automatically checked.

After choosing roles, you can then choose and adjust the specific permissions for this user.

Locale

Switching locale is possible by accessing url <domain>/<locale>, for example :

http://example.com/fr

Additionally, the header of the package pages (based on Laravel default pages) contains links to easily change the locale.

VI - Documentation

The documentation is generated from the DockBlocks by phpDocumentor.
You can make it accessible by creating a symbolic link in your public directory :

$ cd public
$ ln -s ../vendor/dvivier/smarticops/doc smarticops-doc

Then you can access the Smarticops documentation at <domain>/smarticops-doc/index.html

VII - Changelog

You'll find it here.

VIII - Contributions

Contributions are welcome !
Feel free to report bugs and suggest corrections and improvements. Use Bitbucket's issue tracker and pull requests.
I will appreciate feedback on my work, especially concerning the making of a Laravel package since it's my first one.

You can translate the package in other languages in the directory src/lang/<locale>/<file>.
In case you find a security issue, please contact me at d.vivier@smartic.ca.
Contributions are ruled and protected by the Contributor Covenant and will be fully credited.

IX - Miscellaneous

  • This package is currently available in English and French.
  • Test Classes for users, permissions and roles (models and controllers) are available to be run with phpunit in ./tests
  • This package follows the Semantic Versioning 2.0.0 specification described at semver.org.

X - License

The MIT License (MIT). Please see LICENSE for more information.

XI - Credits