forked from unicodeveloper/laravel-cloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSecureShellKey.php
102 lines (88 loc) · 2.46 KB
/
SecureShellKey.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace App;
use Symfony\Component\Process\Process;
class SecureShellKey
{
/**
* Create a new SSH key for a new user.
*
* @param string $password
* @return object
*/
public static function forNewUser($password = '')
{
return app()->environment(/*'local',*/ 'testing')
? static::forTesting()
: static::make($password);
}
/**
* Create a new SSH key for testing.
*
* @return object
*/
protected static function forTesting()
{
return (object) [
'publicKey' => file_get_contents(env('TEST_SSH_CONTAINER_PUBLIC_KEY')),
'privateKey' => file_get_contents(env('TEST_SSH_CONTAINER_KEY')),
];
}
/**
* Create a new SSH key.
*
* @param string $password
* @return object
*/
public static function make($password = '')
{
$name = str_random(20);
(new Process(
"ssh-keygen -C \"[email protected]\" -f {$name} -t rsa -b 4096 -N ".escapeshellarg($password),
storage_path('app')
))->run();
[$publicKey, $privateKey] = [
file_get_contents(storage_path('app/'.$name.'.pub')),
file_get_contents(storage_path('app/'.$name)),
];
@unlink(storage_path('app/'.$name.'.pub'));
@unlink(storage_path('app/'.$name));
return (object) compact('publicKey', 'privateKey');
}
/**
* Store a secure shell key for the given user.
*
* @param \App\User $user
* @return string
*/
public static function storeFor(User $user)
{
return tap(storage_path('app/keys/'.$user->id), function ($path) use ($user) {
static::ensureKeyDirectoryExists();
static::ensureFileExists($path, $user->private_worker_key, 0600);
});
}
/**
* Ensure the SSH key directory exists.
*
* @return void
*/
protected static function ensureKeyDirectoryExists()
{
if (! is_dir(storage_path('app/keys'))) {
mkdir(storage_path('app/keys'), 0755, true);
}
}
/**
* Ensure the given file exists.
*
* @param string $path
* @param string $contents
* @param string $chmod
* @return string
*/
protected static function ensureFileExists($path, $contents, $chmod)
{
file_put_contents($path, $contents);
chmod($path, $chmod);
}
}