mirror of
https://github.com/pterodactyl/panel.git
synced 2026-12-05 22:05:47 -05:00
user actions
This commit is contained in:
@@ -6,18 +6,106 @@ namespace Pterodactyl\Actions\Users;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Password;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\In;
|
||||
use Pterodactyl\Contracts\Users\CreatesUsers;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Notifications\AccountCreated;
|
||||
use Pterodactyl\Rules\UserEmail;
|
||||
use Pterodactyl\Rules\Username;
|
||||
use Pterodactyl\Services\Extensions\ExtensionFields;
|
||||
use Pterodactyl\Services\Extensions\ValidatedExtensionValues;
|
||||
use Throwable;
|
||||
|
||||
final readonly class CreateUser implements CreatesUsers
|
||||
{
|
||||
/**
|
||||
* Rules every new user password must pass, wherever it is set.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
public const array PASSWORD = ['string', 'min:8'];
|
||||
|
||||
public function __construct(private ExtensionFields $extensions) {}
|
||||
|
||||
/**
|
||||
* A user's fields. Pass the user being updated so its own email, username and external
|
||||
* id are not taken for duplicates.
|
||||
*
|
||||
* @return NormalizedValidationRules
|
||||
*/
|
||||
public static function rules(?User $user = null): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'email:strict', 'between:1,191', new UserEmail, Rule::unique('users', 'email')->ignore($user)],
|
||||
'external_id' => ['sometimes', 'nullable', 'string', 'max:191', Rule::unique('users', 'external_id')->ignore($user)],
|
||||
'username' => ['required', 'between:1,191', Rule::unique('users', 'username')->ignore($user), new Username],
|
||||
'name_first' => ['required', 'string', 'between:1,191'],
|
||||
'name_last' => ['required', 'string', 'between:1,191'],
|
||||
'password' => ['sometimes', 'nullable', ...self::PASSWORD],
|
||||
'root_admin' => ['boolean'],
|
||||
'language' => ['string', new In(array_keys((new User)->getAvailableLanguages()))],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates user input and returns the model attributes it describes. Given the user
|
||||
* being updated, only the fields in the input are validated and returned, so the rest
|
||||
* keep their stored values. A blank password is left out.
|
||||
*
|
||||
* @param ActionInput $input
|
||||
* @return array{email?: string, username?: string, name_first?: string, name_last?: string, external_id?: string|null, password?: string, root_admin?: bool, language?: string}
|
||||
*/
|
||||
public static function attributes(array $input, ?User $user = null): array
|
||||
{
|
||||
$rules = self::rules($user);
|
||||
if ($user instanceof User) {
|
||||
foreach ($rules as $field => $fieldRules) {
|
||||
$rules[$field] = ['sometimes', ...$fieldRules];
|
||||
}
|
||||
}
|
||||
|
||||
$input = Validator::make($input, $rules)->safe();
|
||||
|
||||
$attributes = [];
|
||||
if ($input->has('email')) {
|
||||
$attributes['email'] = $input->string('email')->toString();
|
||||
}
|
||||
|
||||
if ($input->has('username')) {
|
||||
$attributes['username'] = $input->string('username')->toString();
|
||||
}
|
||||
|
||||
if ($input->has('name_first')) {
|
||||
$attributes['name_first'] = $input->string('name_first')->toString();
|
||||
}
|
||||
|
||||
if ($input->has('name_last')) {
|
||||
$attributes['name_last'] = $input->string('name_last')->toString();
|
||||
}
|
||||
|
||||
if ($input->has('external_id')) {
|
||||
$attributes['external_id'] = $input->filled('external_id') ? $input->string('external_id')->toString() : null;
|
||||
}
|
||||
|
||||
$password = $input->string('password')->toString();
|
||||
if ($password !== '') {
|
||||
$attributes['password'] = $password;
|
||||
}
|
||||
|
||||
if ($input->has('root_admin')) {
|
||||
$attributes['root_admin'] = $input->boolean('root_admin');
|
||||
}
|
||||
|
||||
if ($input->filled('language')) {
|
||||
$attributes['language'] = $input->string('language')->toString();
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new user on the system. When no password is provided a random one is
|
||||
* set and a password reset token is generated for the account welcome email.
|
||||
@@ -25,22 +113,20 @@ final readonly class CreateUser implements CreatesUsers
|
||||
* The UUID and password hash are handled by the model itself (HasVersion4Uuids
|
||||
* and the hashed password cast).
|
||||
*
|
||||
* @param UserCreationData $data
|
||||
* @param ActionInput $input
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function create(array $data): User
|
||||
public function create(array $input): User
|
||||
{
|
||||
$extensions = ValidatedExtensionValues::of($data['extensions'] ?? null);
|
||||
unset($data['extensions']);
|
||||
$attributes = self::attributes($input);
|
||||
$extensions = ValidatedExtensionValues::of($input['extensions'] ?? null);
|
||||
|
||||
$generateResetToken = empty($data['password']);
|
||||
if ($generateResetToken) {
|
||||
$data['password'] = Str::random(30);
|
||||
}
|
||||
$generateResetToken = ! isset($attributes['password']);
|
||||
$attributes['password'] ??= Str::random(30);
|
||||
|
||||
[$user, $token] = DB::transaction(function () use ($data, $generateResetToken, $extensions): array {
|
||||
$user = User::query()->create($data);
|
||||
[$user, $token] = DB::transaction(function () use ($attributes, $generateResetToken, $extensions): array {
|
||||
$user = User::query()->create($attributes);
|
||||
$this->extensions->save($user, $extensions);
|
||||
|
||||
return [$user->refresh(), $generateResetToken ? Password::createToken($user) : null];
|
||||
|
||||
@@ -4,7 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Actions\Users;
|
||||
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Pterodactyl\Contracts\Users\UpdatesUsers;
|
||||
use Pterodactyl\Events\User\PasswordChanged;
|
||||
@@ -21,25 +20,21 @@ final readonly class UpdateUser implements UpdatesUsers
|
||||
* Update the user model instance and return the updated model. The hashed
|
||||
* password cast on the model takes care of hashing a new password.
|
||||
*
|
||||
* @param UserUpdateData $data
|
||||
* @param ActionInput $input
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function update(User $user, array $data): User
|
||||
public function update(User $user, array $input): User
|
||||
{
|
||||
$extensions = ValidatedExtensionValues::of($data['extensions'] ?? null);
|
||||
unset($data['extensions']);
|
||||
$attributes = CreateUser::attributes($input, $user);
|
||||
$extensions = ValidatedExtensionValues::of($input['extensions'] ?? null);
|
||||
|
||||
if (empty(Arr::get($data, 'password'))) {
|
||||
unset($data['password']);
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($user, $data, $extensions): void {
|
||||
$user->forceFill($data)->saveOrFail();
|
||||
DB::transaction(function () use ($user, $attributes, $extensions): void {
|
||||
$user->forceFill($attributes)->saveOrFail();
|
||||
$this->extensions->save($user, $extensions);
|
||||
});
|
||||
|
||||
if (isset($data['password'])) {
|
||||
if (isset($attributes['password'])) {
|
||||
event(new PasswordChanged($user));
|
||||
}
|
||||
|
||||
|
||||
@@ -7,11 +7,10 @@ namespace Pterodactyl\Console\Commands\User;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Pterodactyl\Contracts\Users\CreatesUsers;
|
||||
use Pterodactyl\Facades\Activity;
|
||||
use Pterodactyl\Support\JsonValueGuard;
|
||||
use Pterodactyl\Validation\UserRules;
|
||||
use Throwable;
|
||||
|
||||
#[Description('Creates a user on the system via the CLI.')]
|
||||
@@ -37,26 +36,23 @@ class MakeUserCommand extends Command
|
||||
$password = $this->secret(trans('command/messages.user.ask_password'));
|
||||
}
|
||||
|
||||
$data = ['email' => $email, 'username' => $username, 'name_first' => $name_first, 'name_last' => $name_last, 'password' => $password, 'root_admin' => $root_admin];
|
||||
|
||||
$validator = Validator::make($data, UserRules::rules());
|
||||
if ($validator->fails()) {
|
||||
foreach ($validator->errors()->all() as $error) {
|
||||
try {
|
||||
$user = $users->create([
|
||||
'email' => JsonValueGuard::nullableString($email),
|
||||
'username' => JsonValueGuard::nullableString($username),
|
||||
'name_first' => JsonValueGuard::nullableString($name_first),
|
||||
'name_last' => JsonValueGuard::nullableString($name_last),
|
||||
'password' => JsonValueGuard::nullableString($password),
|
||||
'root_admin' => JsonValueGuard::scalar($root_admin),
|
||||
]);
|
||||
} catch (ValidationException $validationException) {
|
||||
foreach ($validationException->validator->errors()->all() as $error) {
|
||||
$this->error($error);
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
$user = $users->create([
|
||||
'email' => JsonValueGuard::string($email),
|
||||
'username' => JsonValueGuard::string($username),
|
||||
'name_first' => JsonValueGuard::string($name_first),
|
||||
'name_last' => JsonValueGuard::string($name_last),
|
||||
'password' => JsonValueGuard::nullableString($password),
|
||||
'root_admin' => filter_var($root_admin, FILTER_VALIDATE_BOOL),
|
||||
]);
|
||||
|
||||
Activity::event('user:user.create')
|
||||
->subject($user)
|
||||
->property(['email' => $user->email, 'username' => $user->username, 'admin' => $user->root_admin])
|
||||
|
||||
@@ -16,9 +16,12 @@ interface CreatesUsers
|
||||
* The UUID and password hash are handled by the model itself (HasVersion4Uuids
|
||||
* and the hashed password cast).
|
||||
*
|
||||
* @param UserCreationData $data
|
||||
* The input is validated here, so it can come straight from any caller; extension
|
||||
* field values go under `extensions` as ValidatedExtensionValues.
|
||||
*
|
||||
* @param ActionInput $input email, username, name_first, name_last, and optionally external_id, password, root_admin and language
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function create(array $data): User;
|
||||
public function create(array $input): User;
|
||||
}
|
||||
|
||||
@@ -13,9 +13,13 @@ interface UpdatesUsers
|
||||
* Update the user model instance and return the updated model. The hashed
|
||||
* password cast on the model takes care of hashing a new password.
|
||||
*
|
||||
* @param UserUpdateData $data
|
||||
* The input is validated here, so it can come straight from any caller. Only the fields
|
||||
* given are changed; a blank password leaves the password alone. Extension field values
|
||||
* go under `extensions` as ValidatedExtensionValues.
|
||||
*
|
||||
* @param ActionInput $input any of the fields a user is created with
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function update(User $user, array $data): User;
|
||||
public function update(User $user, array $input): User;
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ class UserController extends AdminApiController
|
||||
#[ExtensionFieldsParam]
|
||||
public function store(StoreUserRequest $request, CreatesUsers $users): JsonResponse
|
||||
{
|
||||
$user = $users->create($request->payload());
|
||||
$user = $users->create($request->actionInput());
|
||||
|
||||
Activity::event('admin:user.create')
|
||||
->subject($user)
|
||||
@@ -148,7 +148,7 @@ class UserController extends AdminApiController
|
||||
#[ExtensionFieldsParam]
|
||||
public function update(UpdateUserRequest $request, UpdatesUsers $users, User $user): array
|
||||
{
|
||||
$user = $users->update($user, $request->payload());
|
||||
$user = $users->update($user, $request->actionInput());
|
||||
|
||||
Activity::event('admin:user.update')
|
||||
->subject($user)
|
||||
|
||||
@@ -87,7 +87,7 @@ class UserController extends ApplicationApiController
|
||||
#[ExtensionFieldsParam]
|
||||
public function update(UpdateUserRequest $request, UpdatesUsers $users, User $user): array
|
||||
{
|
||||
$user = $users->update($user, $request->payload());
|
||||
$user = $users->update($user, $request->actionInput());
|
||||
|
||||
$response = Fractal::item($user)
|
||||
->transformWith($this->getTransformer(UserTransformer::class)->withExtensionFields());
|
||||
@@ -106,7 +106,7 @@ class UserController extends ApplicationApiController
|
||||
#[ExtensionFieldsParam]
|
||||
public function store(StoreUserRequest $request, CreatesUsers $users): JsonResponse
|
||||
{
|
||||
$user = $users->create($request->payload());
|
||||
$user = $users->create($request->actionInput());
|
||||
|
||||
Activity::event('user:user.create')
|
||||
->subject($user)
|
||||
|
||||
@@ -5,18 +5,18 @@ declare(strict_types=1);
|
||||
namespace Pterodactyl\Http\Requests\Api\Admin\Users;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Arr;
|
||||
use Pterodactyl\Actions\Users\CreateUser;
|
||||
use Pterodactyl\Enum\Permissions;
|
||||
use Pterodactyl\Http\Requests\Api\Admin\AdminApiRequest;
|
||||
use Pterodactyl\Http\Requests\Concerns\ValidatesExtensionFields;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Support\JsonValueGuard;
|
||||
use Pterodactyl\Support\ValidationRuleSubset;
|
||||
use Pterodactyl\Validation\UserRules;
|
||||
|
||||
class StoreUserRequest extends AdminApiRequest
|
||||
{
|
||||
use ValidatesExtensionFields;
|
||||
use ValidatesExtensionFields {
|
||||
actionInput as private inputWithExtensions;
|
||||
}
|
||||
|
||||
public function permissions(): array
|
||||
{
|
||||
@@ -31,7 +31,7 @@ class StoreUserRequest extends AdminApiRequest
|
||||
*/
|
||||
public function rules(?array $rules = null): array
|
||||
{
|
||||
$rules ??= UserRules::rules();
|
||||
$rules ??= CreateUser::rules();
|
||||
|
||||
$response = ValidationRuleSubset::select($rules, [
|
||||
'external_id',
|
||||
@@ -43,45 +43,29 @@ class StoreUserRequest extends AdminApiRequest
|
||||
'name_last',
|
||||
]);
|
||||
|
||||
// Nested on input; remapped onto the flat `language` column in validated().
|
||||
// Nested on input; actionInput() hands it to the action as `language`.
|
||||
$response['preferences.language'] = $rules['language'];
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return UserCreationData
|
||||
* The validated input, with the language sent under `preferences` moved to the
|
||||
* action's `language` key.
|
||||
*
|
||||
* @return ActionInput
|
||||
*/
|
||||
public function payload(): array
|
||||
public function actionInput(): array
|
||||
{
|
||||
$validated = parent::validated();
|
||||
$input = $this->inputWithExtensions();
|
||||
unset($input['preferences']);
|
||||
|
||||
$data = [
|
||||
'email' => JsonValueGuard::string(Arr::get($validated, 'email')),
|
||||
'username' => JsonValueGuard::string(Arr::get($validated, 'username')),
|
||||
'name_first' => JsonValueGuard::string(Arr::get($validated, 'name_first')),
|
||||
'name_last' => JsonValueGuard::string(Arr::get($validated, 'name_last')),
|
||||
];
|
||||
|
||||
foreach (['external_id', 'password'] as $nullable) {
|
||||
if (array_key_exists($nullable, $validated)) {
|
||||
$value = Arr::get($validated, $nullable);
|
||||
$data[$nullable] = $value !== null && $value !== '' ? JsonValueGuard::string($value) : null;
|
||||
}
|
||||
$validated = $this->safe();
|
||||
if ($validated->has('preferences.language')) {
|
||||
$input['language'] = $validated->string('preferences.language')->toString();
|
||||
}
|
||||
|
||||
if (array_key_exists('root_admin', $validated)) {
|
||||
$data['root_admin'] = $this->boolean('root_admin');
|
||||
}
|
||||
|
||||
$language = Arr::get($validated, 'preferences.language');
|
||||
if ($language !== null && $language !== '') {
|
||||
$data['language'] = JsonValueGuard::string($language);
|
||||
}
|
||||
|
||||
$data['extensions'] = $this->extensionValues();
|
||||
|
||||
return $data;
|
||||
return $input;
|
||||
}
|
||||
|
||||
/** Rename fields to be more clear in error messages. */
|
||||
|
||||
@@ -4,9 +4,9 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Http\Requests\Api\Admin\Users;
|
||||
|
||||
use Pterodactyl\Actions\Users\CreateUser;
|
||||
use Pterodactyl\Enum\Permissions;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Validation\UserRules;
|
||||
|
||||
class UpdateUserRequest extends StoreUserRequest
|
||||
{
|
||||
@@ -23,7 +23,7 @@ class UpdateUserRequest extends StoreUserRequest
|
||||
*/
|
||||
public function rules(?array $rules = null): array
|
||||
{
|
||||
return parent::rules(UserRules::rules($this->parameter('user', User::class)));
|
||||
return parent::rules(CreateUser::rules($this->parameter('user', User::class)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,18 +5,18 @@ declare(strict_types=1);
|
||||
namespace Pterodactyl\Http\Requests\Api\Application\Users;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Arr;
|
||||
use Pterodactyl\Actions\Users\CreateUser;
|
||||
use Pterodactyl\Http\Requests\Api\Application\ApplicationApiRequest;
|
||||
use Pterodactyl\Http\Requests\Concerns\ValidatesExtensionFields;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Services\Acl\Api\AdminAcl;
|
||||
use Pterodactyl\Support\JsonValueGuard;
|
||||
use Pterodactyl\Support\ValidationRuleSubset;
|
||||
use Pterodactyl\Validation\UserRules;
|
||||
|
||||
class StoreUserRequest extends ApplicationApiRequest
|
||||
{
|
||||
use ValidatesExtensionFields;
|
||||
use ValidatesExtensionFields {
|
||||
actionInput as private inputWithExtensions;
|
||||
}
|
||||
|
||||
protected ?string $resource = AdminAcl::RESOURCE_USERS;
|
||||
|
||||
@@ -30,7 +30,7 @@ class StoreUserRequest extends ApplicationApiRequest
|
||||
*/
|
||||
public function rules(?array $rules = null): array
|
||||
{
|
||||
$rules ??= UserRules::rules();
|
||||
$rules ??= CreateUser::rules();
|
||||
|
||||
$response = ValidationRuleSubset::select($rules, [
|
||||
'external_id',
|
||||
@@ -48,38 +48,19 @@ class StoreUserRequest extends ApplicationApiRequest
|
||||
}
|
||||
|
||||
/**
|
||||
* @return UserCreationData
|
||||
* The validated input under the action's field names: first_name and last_name are
|
||||
* its name_first and name_last.
|
||||
*
|
||||
* @return ActionInput
|
||||
*/
|
||||
public function payload(): array
|
||||
public function actionInput(): array
|
||||
{
|
||||
$validated = parent::validated();
|
||||
$input = $this->inputWithExtensions();
|
||||
$input['name_first'] = $input['first_name'] ?? null;
|
||||
$input['name_last'] = $input['last_name'] ?? null;
|
||||
unset($input['first_name'], $input['last_name']);
|
||||
|
||||
$data = [
|
||||
'email' => JsonValueGuard::string(Arr::get($validated, 'email')),
|
||||
'username' => JsonValueGuard::string(Arr::get($validated, 'username')),
|
||||
'name_first' => JsonValueGuard::string(Arr::get($validated, 'first_name')),
|
||||
'name_last' => JsonValueGuard::string(Arr::get($validated, 'last_name')),
|
||||
];
|
||||
|
||||
foreach (['external_id', 'password'] as $nullable) {
|
||||
if (array_key_exists($nullable, $validated)) {
|
||||
$value = Arr::get($validated, $nullable);
|
||||
$data[$nullable] = $value !== null && $value !== '' ? JsonValueGuard::string($value) : null;
|
||||
}
|
||||
}
|
||||
|
||||
if (array_key_exists('root_admin', $validated)) {
|
||||
$data['root_admin'] = $this->boolean('root_admin');
|
||||
}
|
||||
|
||||
$language = Arr::get($validated, 'language');
|
||||
if ($language !== null && $language !== '') {
|
||||
$data['language'] = JsonValueGuard::string($language);
|
||||
}
|
||||
|
||||
$data['extensions'] = $this->extensionValues();
|
||||
|
||||
return $data;
|
||||
return $input;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,8 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Http\Requests\Api\Application\Users;
|
||||
|
||||
use Pterodactyl\Actions\Users\CreateUser;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Validation\UserRules;
|
||||
|
||||
class UpdateUserRequest extends StoreUserRequest
|
||||
{
|
||||
@@ -17,7 +17,7 @@ class UpdateUserRequest extends StoreUserRequest
|
||||
*/
|
||||
public function rules(?array $rules = null): array
|
||||
{
|
||||
return parent::rules(UserRules::rules($this->parameter('user', User::class)));
|
||||
return parent::rules(CreateUser::rules($this->parameter('user', User::class)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,9 +5,9 @@ declare(strict_types=1);
|
||||
namespace Pterodactyl\Http\Requests\Api\Client\Account;
|
||||
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Pterodactyl\Actions\Users\CreateUser;
|
||||
use Pterodactyl\Exceptions\Http\Base\InvalidPasswordProvidedException;
|
||||
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
|
||||
use Pterodactyl\Validation\UserRules;
|
||||
|
||||
class UpdateEmailRequest extends ClientApiRequest
|
||||
{
|
||||
@@ -31,7 +31,7 @@ class UpdateEmailRequest extends ClientApiRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => UserRules::rules($this->user())['email'],
|
||||
'email' => CreateUser::rules($this->user())['email'],
|
||||
'password' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -5,10 +5,10 @@ declare(strict_types=1);
|
||||
namespace Pterodactyl\Http\Requests\Api\Client\Account;
|
||||
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Pterodactyl\Actions\Users\CreateUser;
|
||||
use Pterodactyl\Exceptions\Http\Base\InvalidPasswordProvidedException;
|
||||
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
|
||||
use Pterodactyl\Support\JsonValueGuard;
|
||||
use Pterodactyl\Validation\UserRules;
|
||||
|
||||
class UpdatePasswordRequest extends ClientApiRequest
|
||||
{
|
||||
@@ -19,7 +19,7 @@ class UpdatePasswordRequest extends ClientApiRequest
|
||||
{
|
||||
return [
|
||||
'current_password' => ['required', 'string'],
|
||||
'password' => ['required', 'confirmed', ...UserRules::PASSWORD],
|
||||
'password' => ['required', 'confirmed', ...CreateUser::PASSWORD],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ declare(strict_types=1);
|
||||
namespace Pterodactyl\Http\Requests\Auth;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Pterodactyl\Validation\UserRules;
|
||||
use Pterodactyl\Actions\Users\CreateUser;
|
||||
|
||||
class ResetPasswordRequest extends FormRequest
|
||||
{
|
||||
@@ -22,7 +22,7 @@ class ResetPasswordRequest extends FormRequest
|
||||
return [
|
||||
'token' => ['required', 'string'],
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required', 'confirmed', ...UserRules::PASSWORD],
|
||||
'password' => ['required', 'confirmed', ...CreateUser::PASSWORD],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Validation;
|
||||
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\In;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Rules\UserEmail;
|
||||
use Pterodactyl\Rules\Username;
|
||||
|
||||
final class UserRules
|
||||
{
|
||||
/**
|
||||
* Rules every new user password must pass, wherever it is set.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
public const array PASSWORD = ['string', 'min:8'];
|
||||
|
||||
/**
|
||||
* Validation rules for the user requests and p:user:make.
|
||||
*
|
||||
* @return NormalizedValidationRules
|
||||
*/
|
||||
public static function rules(?User $ignore = null): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'email:strict', 'between:1,191', new UserEmail, Rule::unique('users', 'email')->ignore($ignore)],
|
||||
'external_id' => ['sometimes', 'nullable', 'string', 'max:191', Rule::unique('users', 'external_id')->ignore($ignore)],
|
||||
'username' => ['required', 'between:1,191', Rule::unique('users', 'username')->ignore($ignore), new Username],
|
||||
'name_first' => ['required', 'string', 'between:1,191'],
|
||||
'name_last' => ['required', 'string', 'between:1,191'],
|
||||
'password' => ['sometimes', 'nullable', ...self::PASSWORD],
|
||||
'root_admin' => ['boolean'],
|
||||
'language' => ['string', new In(array_keys((new User)->getAvailableLanguages()))],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -95,8 +95,6 @@ parameters:
|
||||
ApiKeyUpdateData: 'array{memo: string|null}'
|
||||
NodeUpdateData: 'NodeCreationData&array{daemon_token?: string, daemon_token_id?: string}'
|
||||
NodeCreationData: 'array{name: string, location_id: int, fqdn: string, scheme: string, memory: int, memory_overallocate: int, disk: int, disk_overallocate: int, daemonListen: int, daemonSFTP: int, daemonBase: string, description?: string|null, public?: bool, behind_proxy?: bool, maintenance_mode?: bool, upload_size?: int, extensions?: \Pterodactyl\Services\Extensions\ValidatedExtensionValues}'
|
||||
UserCreationData: 'array{email: string, username: string, name_first: string, name_last: string, external_id?: string|null, password?: string|null, root_admin?: bool, language?: string, extensions?: \Pterodactyl\Services\Extensions\ValidatedExtensionValues}'
|
||||
UserUpdateData: 'array{email?: string, username?: string, name_first?: string, name_last?: string, external_id?: string|null, password?: string|null, root_admin?: bool, language?: string, extensions?: \Pterodactyl\Services\Extensions\ValidatedExtensionValues}'
|
||||
SftpAuthenticationData: 'array{type: string|null, username: string, password: string}'
|
||||
EggCreationData: 'array{name: string, description: string|null, docker_images: array<string, string>, force_outgoing_ip: bool, features: list<string>, startup: string, file_denylist?: list<string>, config_from?: int|null, config_stop?: string|null, config_startup?: string|null, config_logs?: string|null, config_files?: string|null, extensions?: \Pterodactyl\Services\Extensions\ValidatedExtensionValues}'
|
||||
ServerTransferData: 'array{node_id: int, allocation_id: int, allocation_additional: list<int>}'
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Tests\Pest\Integration\Actions\Users\CreateUserTest;
|
||||
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Pterodactyl\Contracts\Subusers\CreatesSubusers;
|
||||
use Pterodactyl\Contracts\Users\CreatesUsers;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Notifications\AccountCreated;
|
||||
use Pterodactyl\Tests\Integration\IntegrationTestCase;
|
||||
|
||||
uses(IntegrationTestCase::class, DatabaseTransactions::class);
|
||||
|
||||
beforeEach(function (): void {
|
||||
Notification::fake();
|
||||
});
|
||||
|
||||
/** @return array<string, bool|int|string|null> */
|
||||
function user(array $overrides = []): array
|
||||
{
|
||||
return [...['email' => 'direct@example.com', 'username' => 'direct', 'name_first' => 'Direct', 'name_last' => 'Caller'], ...$overrides];
|
||||
}
|
||||
|
||||
test('users created without the http api meet the same rules', function (array $input, string $field): void {
|
||||
User::factory()->create(['email' => 'taken@example.com', 'username' => 'taken', 'external_id' => 'taken']);
|
||||
$count = User::query()->count();
|
||||
|
||||
try {
|
||||
$this->app->make(CreatesUsers::class)->create(user($input));
|
||||
$this->fail('The user was created.');
|
||||
} catch (ValidationException $validationException) {
|
||||
expect(array_keys($validationException->errors()))->toBe([$field]);
|
||||
}
|
||||
|
||||
expect(User::query()->count())->toBe($count);
|
||||
})->with([
|
||||
'a missing email' => [['email' => null], 'email'],
|
||||
'a malformed email' => [['email' => 'not-an-email'], 'email'],
|
||||
'an email starting with a dash' => [['email' => '-x@example.com'], 'email'],
|
||||
'a taken email' => [['email' => 'taken@example.com'], 'email'],
|
||||
'a taken username' => [['username' => 'taken'], 'username'],
|
||||
'a malformed username' => [['username' => '-bad-'], 'username'],
|
||||
'a taken external id' => [['external_id' => 'taken'], 'external_id'],
|
||||
'a short password' => [['password' => 'abc'], 'password'],
|
||||
'an unknown language' => [['language' => 'xx'], 'language'],
|
||||
'a root admin flag that is not a boolean' => [['root_admin' => 'yes'], 'root_admin'],
|
||||
'a missing first name' => [['name_first' => ''], 'name_first'],
|
||||
]);
|
||||
|
||||
test('values are coerced the way laravel validates them', function (int|string $flag, bool $admin): void {
|
||||
$user = $this->app->make(CreatesUsers::class)->create(user(['root_admin' => $flag, 'external_id' => '1024', 'username' => '1024']));
|
||||
|
||||
expect($user->root_admin)->toBe($admin)
|
||||
->and($user->external_id)->toBe('1024')
|
||||
->and($user->username)->toBe('1024');
|
||||
})->with([[1, true], ['1', true], [0, false], ['0', false]]);
|
||||
|
||||
test('a user given a password keeps it, and one without gets a reset link', function (): void {
|
||||
$users = $this->app->make(CreatesUsers::class);
|
||||
|
||||
$withPassword = $users->create(user(['password' => 'abcdefgh', 'language' => 'en', 'external_id' => '']));
|
||||
expect(Hash::check('abcdefgh', $withPassword->password))->toBeTrue()
|
||||
->and($withPassword->external_id)->toBeNull()
|
||||
->and($withPassword->root_admin)->toBeFalse();
|
||||
Notification::assertSentTo($withPassword, AccountCreated::class, fn (AccountCreated $notification): bool => $notification->token === null);
|
||||
|
||||
$withoutPassword = $users->create(user(['email' => 'blank@example.com', 'username' => 'blank', 'password' => '']));
|
||||
Notification::assertSentTo($withoutPassword, AccountCreated::class, fn (AccountCreated $notification): bool => $notification->token !== null);
|
||||
});
|
||||
|
||||
test('a subuser invited by email gets an account that meets the user rules', function (): void {
|
||||
$server = $this->createServerModel();
|
||||
$subusers = $this->app->make(CreatesSubusers::class);
|
||||
|
||||
expect(fn () => $subusers->create($server, '-invite@example.com', ['control.start']))->toThrow(ValidationException::class);
|
||||
$this->assertDatabaseMissing('users', ['email' => '-invite@example.com']);
|
||||
|
||||
$subuser = $subusers->create($server, '_new.invite@example.com', ['control.start']);
|
||||
expect($subuser->user->wasRecentlyCreated)->toBeTrue()
|
||||
->and($subuser->user->username)->toStartWith('new.invite')
|
||||
->and($subuser->user->root_admin)->toBeFalse();
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pterodactyl\Tests\Pest\Integration\Actions\Users\UpdateUserTest;
|
||||
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Pterodactyl\Contracts\Users\UpdatesUserEmails;
|
||||
use Pterodactyl\Contracts\Users\UpdatesUserPasswords;
|
||||
use Pterodactyl\Contracts\Users\UpdatesUsers;
|
||||
use Pterodactyl\Events\User\PasswordChanged;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Tests\Integration\IntegrationTestCase;
|
||||
|
||||
uses(IntegrationTestCase::class, DatabaseTransactions::class);
|
||||
|
||||
beforeEach(function (): void {
|
||||
Event::fake([PasswordChanged::class]);
|
||||
});
|
||||
|
||||
test('an update changes only the fields it is given', function (): void {
|
||||
$user = User::factory()->create(['external_id' => 'remote-1', 'language' => 'en', 'root_admin' => false]);
|
||||
$original = $user->only(['email', 'username', 'name_last', 'password', 'external_id', 'language']);
|
||||
|
||||
$this->app->make(UpdatesUsers::class)->update($user, ['name_first' => 'Renamed', 'root_admin' => '1']);
|
||||
|
||||
$user->refresh();
|
||||
expect($user->name_first)->toBe('Renamed')
|
||||
->and($user->root_admin)->toBeTrue()
|
||||
->and($user->only(array_keys($original)))->toBe($original);
|
||||
Event::assertNotDispatched(PasswordChanged::class);
|
||||
});
|
||||
|
||||
test('a blank password leaves the password alone, and a new one is hashed', function (): void {
|
||||
$user = User::factory()->create();
|
||||
$hash = $user->password;
|
||||
$users = $this->app->make(UpdatesUsers::class);
|
||||
|
||||
$users->update($user, ['password' => null]);
|
||||
$users->update($user, ['password' => '']);
|
||||
expect($user->refresh()->password)->toBe($hash);
|
||||
Event::assertNotDispatched(PasswordChanged::class);
|
||||
|
||||
$users->update($user, ['password' => 'new-password']);
|
||||
expect(Hash::check('new-password', $user->refresh()->password))->toBeTrue();
|
||||
Event::assertDispatched(PasswordChanged::class);
|
||||
});
|
||||
|
||||
test('an external id given as null or blank is cleared', function (?string $externalId): void {
|
||||
$user = User::factory()->create(['external_id' => 'remote-1']);
|
||||
|
||||
$this->app->make(UpdatesUsers::class)->update($user, ['external_id' => $externalId]);
|
||||
|
||||
expect($user->refresh()->external_id)->toBeNull();
|
||||
})->with([[null], ['']]);
|
||||
|
||||
test('users updated without the http api meet the same rules', function (array $input, string $field): void {
|
||||
User::factory()->create(['email' => 'taken@example.com', 'username' => 'taken']);
|
||||
$user = User::factory()->create()->refresh();
|
||||
$before = $user->getAttributes();
|
||||
|
||||
try {
|
||||
$this->app->make(UpdatesUsers::class)->update($user, $input);
|
||||
$this->fail('The user was updated.');
|
||||
} catch (ValidationException $validationException) {
|
||||
expect(array_keys($validationException->errors()))->toBe([$field]);
|
||||
}
|
||||
|
||||
expect($user->fresh()->getAttributes())->toBe($before);
|
||||
})->with([
|
||||
'a taken email' => [['email' => 'taken@example.com'], 'email'],
|
||||
'a taken username' => [['username' => 'taken'], 'username'],
|
||||
'a blank first name' => [['name_first' => ''], 'name_first'],
|
||||
'a short password' => [['password' => 'abc'], 'password'],
|
||||
'a root admin flag that is not a boolean' => [['root_admin' => 'yes'], 'root_admin'],
|
||||
'an unknown language' => [['language' => 'xx'], 'language'],
|
||||
]);
|
||||
|
||||
test('a user keeps its own email, username and external id', function (): void {
|
||||
$user = User::factory()->create(['external_id' => 'remote-1']);
|
||||
|
||||
$this->app->make(UpdatesUsers::class)->update($user, ['email' => $user->email, 'username' => $user->username, 'external_id' => 'remote-1']);
|
||||
|
||||
expect($user->refresh()->external_id)->toBe('remote-1');
|
||||
});
|
||||
|
||||
test('the email and password actions meet the user rules', function (): void {
|
||||
$taken = User::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
expect(fn () => $this->app->make(UpdatesUserEmails::class)->update($user, $taken->email))->toThrow(ValidationException::class)
|
||||
->and(fn () => $this->app->make(UpdatesUserPasswords::class)->update($user, 'short'))->toThrow(ValidationException::class);
|
||||
|
||||
$this->app->make(UpdatesUserPasswords::class)->update($user, 'long-enough');
|
||||
expect(Hash::check('long-enough', $user->refresh()->password))->toBeTrue();
|
||||
});
|
||||
@@ -165,6 +165,11 @@ test('a blank password leaves the password unchanged', function (): void {
|
||||
$this->putJson(route('api.admin.users.update', ['user' => $user->id]), ['username' => $user->username, 'email' => $user->email, 'name_first' => $user->name_first, 'name_last' => $user->name_last, 'password' => ''])->assertOk();
|
||||
expect($user->fresh()->password)->toBe($hash);
|
||||
});
|
||||
test('the language is read from preferences', function (): void {
|
||||
$user = User::factory()->create(['language' => 'xx']);
|
||||
$this->putJson(route('api.admin.users.update', ['user' => $user->id]), ['username' => $user->username, 'email' => $user->email, 'name_first' => $user->name_first, 'name_last' => $user->name_last, 'preferences' => ['language' => 'en']])->assertOk();
|
||||
expect($user->fresh()->language)->toBe('en');
|
||||
});
|
||||
test('invalid payloads return validation errors', function (): void {
|
||||
$response = $this->postJson(route('api.admin.users.store'), []);
|
||||
$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
|
||||
|
||||
Reference in New Issue
Block a user