|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of jwt-auth |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Sean Tymon <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Tymon\JWTAuth\Commands; |
|
13
|
|
|
|
|
14
|
|
|
use Illuminate\Support\Str; |
|
15
|
|
|
use Illuminate\Console\Command; |
|
16
|
|
|
|
|
17
|
|
|
class JWTGenerateSecretCommand extends Command |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* The console command signature. |
|
21
|
|
|
* |
|
22
|
|
|
* @var string |
|
23
|
|
|
*/ |
|
24
|
|
|
protected $signature = 'jwt:secret {show : Simply display the key instead of modifying files.}'; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* The console command description. |
|
28
|
|
|
* |
|
29
|
|
|
* @var string |
|
30
|
|
|
*/ |
|
31
|
|
|
protected $description = 'Set the JWTAuth secret key used to sign the tokens'; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Execute the console command. |
|
35
|
|
|
* |
|
36
|
|
|
* @return void |
|
37
|
|
|
*/ |
|
38
|
|
|
public function fire() |
|
39
|
|
|
{ |
|
40
|
|
|
$key = $this->getRandomKey(); |
|
41
|
|
|
|
|
42
|
|
|
if ($this->option('show')) { |
|
43
|
|
|
return $this->comment($key); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
$path = base_path('.env'); |
|
47
|
|
|
|
|
48
|
|
|
if (file_exists($path)) { |
|
49
|
|
|
|
|
50
|
|
|
// check if there is already a secret set first |
|
51
|
|
|
if (! Str::contains(file_get_contents($path), 'JWT_SECRET')) { |
|
52
|
|
|
file_put_contents($path, "\r\nJWT_SECRET=$key", FILE_APPEND); |
|
53
|
|
|
} else { |
|
54
|
|
|
|
|
55
|
|
|
// let's be sure you want to do this |
|
56
|
|
|
$confirmed = $this->confirm('This will invalidate all existing tokens. Are you sure you want to override the secret key?'); |
|
57
|
|
|
|
|
58
|
|
|
if ($confirmed) { |
|
59
|
|
|
file_put_contents($path, str_replace( |
|
60
|
|
|
'JWT_SECRET='.$this->laravel['config']['jwt.secret'], 'JWT_SECRET='.$key, file_get_contents($path) |
|
61
|
|
|
)); |
|
62
|
|
|
} else { |
|
63
|
|
|
return $this->comment('Phew... No changes were made to your secret key.'); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
$this->laravel['config']['jwt.secret'] = $key; |
|
69
|
|
|
|
|
70
|
|
|
$this->info("jwt-auth secret [$key] set successfully."); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* Generate a random key for the JWT Auth secret. |
|
75
|
|
|
* |
|
76
|
|
|
* @return string |
|
77
|
|
|
*/ |
|
78
|
|
|
protected function getRandomKey() |
|
79
|
|
|
{ |
|
80
|
|
|
return Str::quickRandom(32); |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|