Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Services/Subusers/SubuserCreationService.php
10281 views
1
<?php
2
3
namespace Pterodactyl\Services\Subusers;
4
5
use Illuminate\Support\Str;
6
use Pterodactyl\Models\Server;
7
use Pterodactyl\Models\Subuser;
8
use Illuminate\Database\ConnectionInterface;
9
use Pterodactyl\Services\Users\UserCreationService;
10
use Pterodactyl\Repositories\Eloquent\SubuserRepository;
11
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
12
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
13
use Pterodactyl\Exceptions\Service\Subuser\UserIsServerOwnerException;
14
use Pterodactyl\Exceptions\Service\Subuser\ServerSubuserExistsException;
15
16
class SubuserCreationService
17
{
18
/**
19
* SubuserCreationService constructor.
20
*/
21
public function __construct(
22
private ConnectionInterface $connection,
23
private SubuserRepository $subuserRepository,
24
private UserCreationService $userCreationService,
25
private UserRepositoryInterface $userRepository,
26
) {
27
}
28
29
/**
30
* Creates a new user on the system and assigns them access to the provided server.
31
* If the email address already belongs to a user on the system a new user will not
32
* be created.
33
*
34
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
35
* @throws ServerSubuserExistsException
36
* @throws UserIsServerOwnerException
37
* @throws \Throwable
38
*/
39
public function handle(Server $server, string $email, array $permissions): Subuser
40
{
41
return $this->connection->transaction(function () use ($server, $email, $permissions) {
42
try {
43
$user = $this->userRepository->findFirstWhere([['email', '=', $email]]);
44
45
if ($server->owner_id === $user->id) {
46
throw new UserIsServerOwnerException(trans('exceptions.subusers.user_is_owner'));
47
}
48
49
$subuserCount = $this->subuserRepository->findCountWhere([['user_id', '=', $user->id], ['server_id', '=', $server->id]]);
50
if ($subuserCount !== 0) {
51
throw new ServerSubuserExistsException(trans('exceptions.subusers.subuser_exists'));
52
}
53
} catch (RecordNotFoundException) {
54
// Just cap the username generated at 64 characters at most and then append a random string
55
// to the end to make it "unique"...
56
$username = substr(preg_replace('/([^\w\.-]+)/', '', strtok($email, '@')), 0, 64) . Str::random(3);
57
58
$user = $this->userCreationService->handle([
59
'email' => $email,
60
'username' => $username,
61
'name_first' => 'Server',
62
'name_last' => 'Subuser',
63
'root_admin' => false,
64
]);
65
}
66
67
return $this->subuserRepository->create([
68
'user_id' => $user->id,
69
'server_id' => $server->id,
70
'permissions' => array_unique($permissions),
71
]);
72
});
73
}
74
}
75
76