Skip to content

Instantly share code, notes, and snippets.

@krisanalfa
Last active September 25, 2023 17:25
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save krisanalfa/0407dd822f2888226f45 to your computer and use it in GitHub Desktop.
Save krisanalfa/0407dd822f2888226f45 to your computer and use it in GitHub Desktop.
Lumen Key Generator Commands
<?php
namespace App\Console\Commands;
use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class KeyGenerateCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'key:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = "Set the application key";
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$key = $this->getRandomKey();
if ($this->option('show')) {
return $this->line('<comment>'.$key.'</comment>');
}
$path = base_path('.env');
if (file_exists($path)) {
file_put_contents(
$path,
str_replace(env('APP_KEY'), $key, file_get_contents($path))
);
}
$this->info("Application key [$key] set successfully.");
}
/**
* Generate a random key for the application.
*
* @return string
*/
protected function getRandomKey()
{
return Str::random(32);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
array('show', null, InputOption::VALUE_NONE, 'Simply display the key instead of modifying files.'),
);
}
}
@shamir92
Copy link

shamir92 commented Dec 7, 2016

thanks a lot bro for your script

@vishal1221
Copy link

Thanks Bro i am totaly new here where i can put this controller and how to run it?

@deargonaut
Copy link

Thanks!
Doesn't work on empty key. If you replace line 43 with this it does.

str_replace('APP_KEY=' . env('APP_KEY'), 'APP_KEY=' . $key, file_get_contents($path))

@a7madev
Copy link

a7madev commented Jul 19, 2017

Thanks! I changed line 41-44 to
file_put_contents($path, str_replace('APP_KEY=' . env('APP_KEY'), 'APP_KEY=' . $key, file_get_contents($path)));

@iamandrewluca
Copy link

iamandrewluca commented Jan 14, 2018

It seems that fire function changed to handle

flipboxstudio/lumen-generator@f07a9ae

@brenjt
Copy link

brenjt commented Jul 5, 2018

Why not use Encrypter::generateKey()? Your solution could get you into trouble if a different cipher was used.

@haidi20
Copy link

haidi20 commented Sep 14, 2018

thank you very much.. your script very help me.. thank you..

@DocasDev
Copy link

DocasDev commented Sep 7, 2019

O seguinte código, na linha 43:
str_replace(env('APP_KEY'), $key, file_get_contents($path))
deve ser substituído por:
preg_replace('/(APP_KEY=)(\s|.*)\n/', ("APP_KEY={$key}\n"), file_get_contents($path))
Porque o código atual não consegue inserir a APP_KEY no caso do arquivo não possuir uma.

@feeh27
Copy link

feeh27 commented Nov 22, 2019

Atualizei o código para funcionar na versão ^6.2.0 do Lumen:
I updated the code to work on Lumen version ^6.2.0:

<?php

namespace App\Console\Commands;

use Illuminate\Support\Str;
use Illuminate\Console\Command;

/**
 * Class KeyGenerateCommand
 * @package App\Console\Commands
 */
class KeyGenerateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'key:generate {--show=false}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Set the application key";

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $key = $this->getRandomKey();
        $appKey = 'base64:' . $key;

        if ($this->option('show') === null) {
            $this->line('<comment>' . $key . '</comment>');
        }

        $path = base_path('.env');

        if (file_exists($path)) {
            file_put_contents(
                $path,
                preg_replace('/(APP_KEY=)(\s|.*)\n/', ("APP_KEY={$appKey}\n"), file_get_contents($path))
            );
        }

        $this->info("Application key [$key] set successfully.");
    }

    /**
     * Generate a random key for the application.
     *
     * @return string
     */
    protected function getRandomKey()
    {
        return Str::random(64);
    }
}

Obrigado @QuodDG e @krisanalfa por suas contribuições.
Thank you @QuodDG and @krisanalfa for your contributions.

@frama21
Copy link

frama21 commented Jan 13, 2021

this is my code and this support APP_KEY for laravel encryption AES-256-CBC.
i use this in my Lumen 8 project, hope this work for you guys :)

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;

class KeyGenerateCommand extends Command
{
    use ConfirmableTrait;

    protected $signature = 'key:generate
                    {--show : Display the key instead of modifying files}
                    {--force : Force the operation to run when in production}';

    protected $description = 'Set the application key';

    public function handle()
    {
        $key = $this->generateRandomKey();

        if ($this->option('show')) {
            return $this->line('<comment>' . $key . '</comment>');
        }

        if (!$this->setKeyInEnvironmentFile($key)) {
            return;
        }

        $this->laravel['config']['app.key'] = $key;

        $this->info("Application key [$key] set successfully.");
    }

    protected function generateRandomKey()
    {
        return 'base64:' . base64_encode(random_bytes(
            $this->laravel['config']['app.cipher'] == 'AES-128-CBC' ? 16 : 32
        ));
    }

    protected function setKeyInEnvironmentFile($key)
    {
        $currentKey = $this->laravel['config']['app.key'] ?: env('APP_KEY');

        if (strlen($currentKey) !== 0 && (!$this->confirmToProceed())) {
            return false;
        }

        $this->writeNewEnvironmentFileWith($key);

        return true;
    }

    protected function writeNewEnvironmentFileWith($key)
    {
        file_put_contents($this->laravel->basePath('.env'), preg_replace(
            $this->keyReplacementPattern($key),
            'APP_KEY=' . $key,
            file_get_contents($this->laravel->basePath('.env'))
        ));
    }

    protected function keyReplacementPattern()
    {
        $currentKey = $this->laravel['config']['app.key'] ?: env('APP_KEY');
        $escaped = preg_quote('=' . $currentKey, '/');

        return "/^APP_KEY{$escaped}/m";
    }
}

@kiralee
Copy link

kiralee commented Mar 17, 2021

I think you should change from fire to handle function. Because Abstract class Command has execute method will detect handle or __invoke. For anyone face issue
Method App\Console\Commands\KeyGenerateCommand::__invoke() does not exist

Just change fire to handle will resolve the problem. Hope this help

@jagadishnallappa
Copy link

this is my code and this support APP_KEY for laravel encryption AES-256-CBC.
i use this in my Lumen 8 project, hope this work for you guys :)

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;

class KeyGenerateCommand extends Command
{
    use ConfirmableTrait;

    protected $signature = 'key:generate
                    {--show : Display the key instead of modifying files}
                    {--force : Force the operation to run when in production}';

    protected $description = 'Set the application key';

    public function handle()
    {
        $key = $this->generateRandomKey();

        if ($this->option('show')) {
            return $this->line('<comment>' . $key . '</comment>');
        }

        if (!$this->setKeyInEnvironmentFile($key)) {
            return;
        }

        $this->laravel['config']['app.key'] = $key;

        $this->info("Application key [$key] set successfully.");
    }

    protected function generateRandomKey()
    {
        return 'base64:' . base64_encode(random_bytes(
            $this->laravel['config']['app.cipher'] == 'AES-128-CBC' ? 16 : 32
        ));
    }

    protected function setKeyInEnvironmentFile($key)
    {
        $currentKey = $this->laravel['config']['app.key'] ?: env('APP_KEY');

        if (strlen($currentKey) !== 0 && (!$this->confirmToProceed())) {
            return false;
        }

        $this->writeNewEnvironmentFileWith($key);

        return true;
    }

    protected function writeNewEnvironmentFileWith($key)
    {
        file_put_contents($this->laravel->basePath('.env'), preg_replace(
            $this->keyReplacementPattern($key),
            'APP_KEY=' . $key,
            file_get_contents($this->laravel->basePath('.env'))
        ));
    }

    protected function keyReplacementPattern()
    {
        $currentKey = $this->laravel['config']['app.key'] ?: env('APP_KEY');
        $escaped = preg_quote('=' . $currentKey, '/');

        return "/^APP_KEY{$escaped}/m";
    }
}

Cheerio! I confirm this works with the latest version of lumen(8.0).

@jagadishnallappa
Copy link

I think you should change from fire to handle function. Because Abstract class Command has execute method will detect handle or __invoke. For anyone face issue
Method App\Console\Commands\KeyGenerateCommand::__invoke() does not exist

Just change fire to handle will resolve the problem. Hope this help

Aye. I confirm that he is right. This solves Method App\Console\Commands\KeyGenerateCommand::__invoke() does not exist.

@Kane-R-G
Copy link

Kane-R-G commented Feb 22, 2022

@frama21 Your solution works well but I had to update this section:

if ($this->option('show')) {
    return $this->line('<comment>' . $key . '</comment>');
 }

to

if ($this->option('show')) {
    $this->line('<comment>' . $key . '</comment>');
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment