A Laravel 9 package that allows you enforce security of your artisan commands by authenticating users before running.

Overview

Introduction

This package allows you as a developer to restrict who can and cannot run artisan commands, especially in a production environment. For example, a user (admin) should be allowed to run commands only if he has the right role/permission.

How it works ?

An artisan user will be provided with a token in order to use it as an option when running commands. This token has a configurable size and lifetime. The user can use this token as much as he wants until it expires or is revoked.

In order to get this token, an artisan user must first perform an authentication within the console, if the authentication is successful, the user will be prompted with the token, otherwise, a warning message will be displayed.

The logic of authentication is customizable, the developer can put in place his own validation rules. For exemple, one would want to authorize a user only if he has an "admin" role, an other one would check if he has the right permissions, another one would fetch an active directory or external authentication service, etc.

How to implement it !

A few steps to put this in place.

Install the package

composer require yooslim/legit-artisan-commands

Publish the vendor configuration file

php artisan vendor:publish --provider="YOoSlim\LegitArtisanCommands\Providers\LegitCommandsServiceProvider"

Edit configuration file

  • Token lifetime: The console token lifetime in seconds.
  • Token size: The number of caracters to be generated (must be less than 255).
  • Environments to be ignored: No need to waste our time with authentication in local environments, so it possible to ignore a set of environments.
  • User model relationship: The model name (namespace included) of the user entity.

Run migrations

php artisan migrate

Add the ArtisanUserInterface to the user model

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use YOoSlim\LegitArtisanCommands\Contracts\ArtisanUserInterface;

class User extends Authenticatable implements ArtisanUserInterface
{
    /**
     * Returns the user ID (the one used as a primary key)
     * 
     * @return int|string
     */
    public function getUserId(): int|string
    {
        return $this->id;
    }
}

Customize your authentication logic in AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use YOoSlim\LegitArtisanCommands\Utils\ArtisanAuthenticationHandler;
use YOoSlim\LegitArtisanCommands\Contracts\ArtisanUserInterface;
use App\Models\User;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        ArtisanAuthenticationHandler::localUserAuthentication(function(string $username, string $password): ?ArtisanUserInterface {
            $user = User::where('email', $username)->first();

            if ($user && Hash::check($password, $user->password) && $user->hasRole('admin')) return $user;

            return null;
        });
    }
}

Finally, edit your artisan command

There are two main things to edit in your command :

  1. Add the LegitArtisanCommandSignature trait, it will edit your command signature by appending the --token option part.
  2. Wrap your original command inside the isAuthorized callback function.
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use YOoSlim\LegitArtisanCommands\Utils\Traits\LegitArtisanCommandSignature;
use YOoSlim\LegitArtisanCommands\Facades\LegitArtisanCommand;
use YOoSlim\LegitArtisanCommands\Models\ConsoleToken;

class FilesPurgeCommand extends Command
{
    use LegitArtisanCommandSignature;

    /* ------- */

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        LegitArtisanCommand::authentify($this->option('token'))
            ->isAuthorized(function (?ConsoleToken $token) {
                // The rest of your command
            })->isNotAuthorized(fn ($exception) => $this->error($exception->getMessage()));
    }

How to use it !

  1. First, request a token by providing your credentials.

php artisan console:authentication --username="[email protected]"

This will prompt a random token.

  1. Then, whenever you use a protected artisan command, include the --token option.

php artisan MyCommand:MyAction --token="*"

Enjoy :D

Please, let me know if something is ambiguous, incomprehensible or wrong. I would be glad to clarify or fix it.

You might also like...
A multi-purpose web-shell that simplifies running shell commands on webserver
A multi-purpose web-shell that simplifies running shell commands on webserver

This webshell can be used for multi-purposed especially most if you want to manage your web server but you are in an emergency , so why not use a webshell:)

The swiss army knife for Magento developers, sysadmins and devops. The tool provides a huge set of well tested command line commands which save hours of work time. All commands are extendable by a module API.

netz98 magerun CLI tools for Magento 2 The n98 magerun cli tools provides some handy tools to work with Magento from command line. Build Status Latest

Exploiting and fixing security vulnerabilities of an old version of E-Class. Project implemented as part of the class YS13 Cyber-Security.

Open eClass 2.3 Development of XSS, CSRF, SQLi, RFI attacks/defences of an older,vulnerable version of eclass. Project implemented as part of the clas

A plugin to make life easier for users who need to edit specific functions of a world and also create, rename and delete worlds quickly using commands or the world management menu.
A plugin to make life easier for users who need to edit specific functions of a world and also create, rename and delete worlds quickly using commands or the world management menu.

A plugin to make life easier for users who need to edit specific functions of a world and also create, rename and delete worlds quickly using commands or the world management menu.

Silverstripe-masquerade - SilverStripe module to allow users to "masquerade" as other users

SilverStripe Masquerade Module About This module is designed to allow an Administrator to "login" as another "Member" without changing their password

Greyhole uses Samba to create a storage pool of all your available hard drives, and allows you to create redundant copies of the files you store.

Greyhole Greyhole is an application that uses Samba to create a storage pool of all your available hard drives (whatever their size, however they're c

Scotch Box is a preconfigured Vagrant Box with a full array of LAMP Stack features to get you up and running with Vagrant in no time.
Scotch Box is a preconfigured Vagrant Box with a full array of LAMP Stack features to get you up and running with Vagrant in no time.

Scotch Box is a preconfigured Vagrant Box with a full array of LAMP Stack features to get you up and running with Vagrant in no time.

A Laravel artisan based package to create the AWS (SES + SNS) infrastructure to receive email event notifications with Http/Https endpoint.
A Laravel artisan based package to create the AWS (SES + SNS) infrastructure to receive email event notifications with Http/Https endpoint.

Laravel SES Tracking Setup the AWS infrastructure to handle email events using SES/SNS and http/s endpoints with a single Laravel artisan command. Thi

Releases(v1.0.0-beta)
  • v1.0.0-beta(Sep 15, 2022)

  • v1.0.0-alpha(Sep 14, 2022)

    This is the first release.

    • Authenticate in console in order to retrieve a token.
    • Use the token everywhere in order to run artisan commands.
    • Configure the token lifetime and the environements where the console authentication is mandatory.
    • Configure the user model with whom the token is associated with.
    • Customize the authentication logic, either it is a local authentication or using an external web service.
    Source code(tar.gz)
    Source code(zip)
Owner
YOo Slim
Fullstack Software Engineer
YOo Slim
Enforce that your classes get only instantiated by the factories you define!

Enforce that your classes get only instantiated by the factories you define!

null 3 Nov 15, 2021
Test and enforce architectural rules in your Laravel applications. Keep your app's architecture clean and consistent!

Laravel Arkitect Laravel Arkitect lets you test and enforce your architectural rules in your Laravel applications, and it's a PHPArkitect wrapper for

SMorteza Ebadi 53 Nov 10, 2022
Detect flaws in your architecture, before they drag you down into the depths of dependency hell ...

Detect flaws in your architecture before they drag you down into the depths of dependency hell ... What it does System Requirements Installation Phive

Michael Haeuslmann 505 Nov 11, 2022
Task for GrumPHP that adds CSS linting support with stylelint. An easy way to enforce convention and avoid errors in your styles

grumphp-stylelint-task Installation Stylelint is a static analysis tool for styles. A mighty, modern linter that helps you avoid errors and enforce co

null 3 Apr 29, 2021
Talkino allows you to integrate multi social messengers and contact into your website and enable your users to contact you using multi social messengers' accounts.

Talkino Welcome to our GitHub Repository Talkino is a click to chat plugin to show your agents’ multiple social messengers, phone and emails on the ch

Traxconn 2 Sep 21, 2022
Your performance & security consultant, an artisan command away.

Enlightn A Laravel Tool To Boost Your App's Performance & Security Introduction Think of Enlightn as your performance and security consultant. Enlight

Enlightn 713 Nov 30, 2022
A Pocketmine-MP (PMMP) plugin to help staff members enforce the rules of the server.

StaffMode is an all-in-one Pocketmine-MP (PMMP) moderation plugin made to simplify the life of staff members.

ItsMax123 9 Sep 17, 2022
Execute Artisan commands on remote servers

Execute Artisan commands on remote servers This package provides a command to execute Artisan command on a remote server. Here's an example that will

Spatie 236 Nov 24, 2022
Refresh artisan commands,table,migrations,models,controllers...

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Javier Fernández 11 Oct 18, 2022