Path: blob/1.0-develop/app/Services/Subusers/SubuserCreationService.php
10281 views
<?php12namespace Pterodactyl\Services\Subusers;34use Illuminate\Support\Str;5use Pterodactyl\Models\Server;6use Pterodactyl\Models\Subuser;7use Illuminate\Database\ConnectionInterface;8use Pterodactyl\Services\Users\UserCreationService;9use Pterodactyl\Repositories\Eloquent\SubuserRepository;10use Pterodactyl\Contracts\Repository\UserRepositoryInterface;11use Pterodactyl\Exceptions\Repository\RecordNotFoundException;12use Pterodactyl\Exceptions\Service\Subuser\UserIsServerOwnerException;13use Pterodactyl\Exceptions\Service\Subuser\ServerSubuserExistsException;1415class SubuserCreationService16{17/**18* SubuserCreationService constructor.19*/20public function __construct(21private ConnectionInterface $connection,22private SubuserRepository $subuserRepository,23private UserCreationService $userCreationService,24private UserRepositoryInterface $userRepository,25) {26}2728/**29* Creates a new user on the system and assigns them access to the provided server.30* If the email address already belongs to a user on the system a new user will not31* be created.32*33* @throws \Pterodactyl\Exceptions\Model\DataValidationException34* @throws ServerSubuserExistsException35* @throws UserIsServerOwnerException36* @throws \Throwable37*/38public function handle(Server $server, string $email, array $permissions): Subuser39{40return $this->connection->transaction(function () use ($server, $email, $permissions) {41try {42$user = $this->userRepository->findFirstWhere([['email', '=', $email]]);4344if ($server->owner_id === $user->id) {45throw new UserIsServerOwnerException(trans('exceptions.subusers.user_is_owner'));46}4748$subuserCount = $this->subuserRepository->findCountWhere([['user_id', '=', $user->id], ['server_id', '=', $server->id]]);49if ($subuserCount !== 0) {50throw new ServerSubuserExistsException(trans('exceptions.subusers.subuser_exists'));51}52} catch (RecordNotFoundException) {53// Just cap the username generated at 64 characters at most and then append a random string54// to the end to make it "unique"...55$username = substr(preg_replace('/([^\w\.-]+)/', '', strtok($email, '@')), 0, 64) . Str::random(3);5657$user = $this->userCreationService->handle([58'email' => $email,59'username' => $username,60'name_first' => 'Server',61'name_last' => 'Subuser',62'root_admin' => false,63]);64}6566return $this->subuserRepository->create([67'user_id' => $user->id,68'server_id' => $server->id,69'permissions' => array_unique($permissions),70]);71});72}73}747576