Files
panel-pelican-dev/app/Services/Subusers/SubuserCreationService.php

70 lines
2.5 KiB
PHP
Raw Normal View History

2017-08-23 21:34:11 -05:00
<?php
2024-03-12 22:39:16 -04:00
namespace App\Services\Subusers;
2017-08-23 21:34:11 -05:00
2024-03-16 19:10:31 -04:00
use App\Models\User;
use Illuminate\Support\Str;
2024-03-12 22:39:16 -04:00
use App\Models\Server;
use App\Models\Subuser;
2017-08-23 21:34:11 -05:00
use Illuminate\Database\ConnectionInterface;
2024-03-12 22:39:16 -04:00
use App\Services\Users\UserCreationService;
use App\Exceptions\Service\Subuser\UserIsServerOwnerException;
use App\Exceptions\Service\Subuser\ServerSubuserExistsException;
2017-08-23 21:34:11 -05:00
class SubuserCreationService
{
2017-09-04 18:12:13 -05:00
/**
* SubuserCreationService constructor.
*/
2017-08-23 21:34:11 -05:00
public function __construct(
private ConnectionInterface $connection,
private UserCreationService $userCreationService,
2017-08-23 21:34:11 -05:00
) {
}
/**
* Creates a new user on the system and assigns them access to the provided server.
* If the email address already belongs to a user on the system a new user will not
* be created.
*
2024-03-12 22:39:16 -04:00
* @throws \App\Exceptions\Model\DataValidationException
* @throws \App\Exceptions\Service\Subuser\ServerSubuserExistsException
* @throws \App\Exceptions\Service\Subuser\UserIsServerOwnerException
* @throws \Throwable
2017-08-23 21:34:11 -05:00
*/
public function handle(Server $server, string $email, array $permissions): Subuser
2017-08-23 21:34:11 -05:00
{
return $this->connection->transaction(function () use ($server, $email, $permissions) {
2024-03-16 19:10:31 -04:00
$user = User::query()->where('email', $email)->first();
if (!$user) {
// Just cap the username generated at 64 characters at most and then append a random string
// to the end to make it "unique"...
$username = substr(preg_replace('/([^\w\.-]+)/', '', strtok($email, '@')), 0, 64) . Str::random(3);
$user = $this->userCreationService->handle([
'email' => $email,
'username' => $username,
'name_first' => 'Server',
'name_last' => 'Subuser',
'root_admin' => false,
]);
2017-08-23 21:34:11 -05:00
}
2024-03-16 19:10:31 -04:00
if ($server->owner_id === $user->id) {
throw new UserIsServerOwnerException(trans('exceptions.subusers.user_is_owner'));
}
2024-03-16 22:13:13 -04:00
$subuserCount = $server->subusers()->where('user_id', $user->id)->count();
2024-03-16 19:10:31 -04:00
if ($subuserCount !== 0) {
throw new ServerSubuserExistsException(trans('exceptions.subusers.subuser_exists'));
}
2024-03-16 22:13:13 -04:00
return Subuser::query()->create([
'user_id' => $user->id,
'server_id' => $server->id,
2020-03-27 16:42:27 -07:00
'permissions' => array_unique($permissions),
2017-09-04 18:12:13 -05:00
]);
});
2017-08-23 21:34:11 -05:00
}
}