Users module: accounts, groups, permissions with needs, manager:create-user
This commit is contained in:
1 parent
08289db744
commit
f86f5aea28
25 files changed
+744
-58
No files matched your search
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Users;
|
||||
|
||||
use Illuminate\Contracts\Auth\Authenticatable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use IriksIT\Manager\Models\Group;
|
||||
|
||||
/**
|
||||
* The accounts of the manager and the groups each is in.
|
||||
*
|
||||
* Managing accounts must not be a way to more rights than one has. So, for anyone who is no
|
||||
* super admin: an account is only changed or deleted when it may do nothing more than oneself
|
||||
* (`managerOutranks`), and it is only put in a group that gives nothing more than one has
|
||||
* oneself (`managerMayGive`). Nobody becomes a super admin here: that is `manager:create-user`.
|
||||
*
|
||||
* The answers have the shape the screens of the sites used as props.
|
||||
*/
|
||||
class AccountController
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$me = $request->user();
|
||||
$model = $this->model();
|
||||
|
||||
return response()->json([
|
||||
'accounts' => $model::query()->with('managerGroups')->orderBy('name')->orderBy('id')->get()
|
||||
->map(fn ($user) => [
|
||||
'id' => $user->getKey(),
|
||||
'name' => $user->name,
|
||||
'email' => $user->email,
|
||||
'is_super_admin' => $user->isManagerSuperAdmin(),
|
||||
'is_you' => $user->is($me),
|
||||
'groups' => $user->managerGroups->sortBy('name')->map(fn (Group $group) => ['id' => $group->id, 'name' => $group->name])->values(),
|
||||
'can_change' => $me->managerOutranks($user),
|
||||
'can_delete' => $me->managerOutranks($user) && ! $user->is($me),
|
||||
])->values(),
|
||||
'groups' => Group::query()->orderBy('name')->get()
|
||||
->map(fn (Group $group) => [
|
||||
'id' => $group->id,
|
||||
'name' => $group->name,
|
||||
'description' => $group->description,
|
||||
'can_give' => $me->managerMayGive($group),
|
||||
])->values(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([...$this->rules(), 'password' => ['required', 'string', 'min:12', 'max:200']]);
|
||||
|
||||
// Everything is checked before anything is stored: a refused group leaves no account behind.
|
||||
$details = $this->details($request, null);
|
||||
$groups = $this->groups($request);
|
||||
|
||||
$model = $this->model();
|
||||
$user = new $model;
|
||||
$user->forceFill([...$details, 'password' => Hash::make($request->string('password')->toString())])->save();
|
||||
$user->managerGroups()->sync($groups);
|
||||
|
||||
return response()->json(['id' => $user->getKey()], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, string $account): JsonResponse
|
||||
{
|
||||
$me = $request->user();
|
||||
$user = $this->find($account);
|
||||
abort_unless($me->managerOutranks($user), 403);
|
||||
|
||||
$request->validate([...$this->rules(), 'password' => ['nullable', 'string', 'min:12', 'max:200']]);
|
||||
$details = $this->details($request, $user);
|
||||
|
||||
// Groups mean nothing for a super admin, and nobody changes their own.
|
||||
$groups = $user->isManagerSuperAdmin() || $user->is($me) ? null : $this->groups($request);
|
||||
|
||||
$user->forceFill($details);
|
||||
|
||||
// Empty: the password stays as it is.
|
||||
if ($request->filled('password')) {
|
||||
$user->forceFill(['password' => Hash::make($request->string('password')->toString())]);
|
||||
}
|
||||
|
||||
$user->save();
|
||||
|
||||
if ($groups !== null) {
|
||||
$user->managerGroups()->sync($groups);
|
||||
}
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
}
|
||||
|
||||
public function destroy(Request $request, string $account): JsonResponse
|
||||
{
|
||||
$me = $request->user();
|
||||
$user = $this->find($account);
|
||||
abort_unless($me->managerOutranks($user), 403);
|
||||
|
||||
if ($user->is($me)) {
|
||||
return response()->json(['message' => 'You cannot delete your own account.'], 422);
|
||||
}
|
||||
|
||||
$user->managerGroups()->detach();
|
||||
$user->delete();
|
||||
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/** @return class-string<Authenticatable&Model> */
|
||||
private function model(): string
|
||||
{
|
||||
return config('manager.user_model');
|
||||
}
|
||||
|
||||
private function find(string $id)
|
||||
{
|
||||
return $this->model()::query()->findOrFail($id);
|
||||
}
|
||||
|
||||
/** @return array<string, list<mixed>> */
|
||||
private function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'groups' => ['array'],
|
||||
'groups.*' => ['integer'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Name and email address, the address in lower case and not in use by another account.
|
||||
*
|
||||
* @return array{name: string, email: string}
|
||||
*/
|
||||
private function details(Request $request, $user): array
|
||||
{
|
||||
$email = $request->string('email')->trim()->lower()->toString();
|
||||
|
||||
if ($this->model()::query()->where('email', $email)->when($user !== null, fn ($query) => $query->whereKeyNot($user->getKey()))->exists()) {
|
||||
throw ValidationException::withMessages(['email' => 'Another account already uses this email address.']);
|
||||
}
|
||||
|
||||
return ['name' => $request->string('name')->trim()->toString(), 'email' => $email];
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids of the groups that were ticked. One that does not exist, or that gives more than
|
||||
* the account that is logged in has, is refused.
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
private function groups(Request $request): array
|
||||
{
|
||||
$me = $request->user();
|
||||
$ids = array_values(array_unique(array_map(fn (mixed $id) => is_numeric($id) ? (int) $id : 0, $request->array('groups'))));
|
||||
$groups = Group::query()->whereKey($ids)->get();
|
||||
|
||||
if ($groups->count() !== count($ids) || $groups->contains(fn (Group $group) => ! $me->managerMayGive($group))) {
|
||||
throw ValidationException::withMessages(['groups' => 'You can only choose groups that allow nothing more than your own account.']);
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Users;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
/**
|
||||
* Creates a super admin: an account that may do everything in the manager, and the only kind
|
||||
* that manages the groups. This is the only place that hands out `is_super_admin`.
|
||||
*
|
||||
* php artisan manager:create-user
|
||||
*
|
||||
* It asks for name, email and password. For scripts, pass them as options.
|
||||
*/
|
||||
class CreateManagerUser extends Command
|
||||
{
|
||||
protected $signature = 'manager:create-user
|
||||
{--name= : Name shown in the manager}
|
||||
{--email= : Email address to log in with}
|
||||
{--password= : Password (min 12 characters); leave out to type it hidden}';
|
||||
|
||||
protected $description = 'Create a super admin: an account that may do everything in the manager';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$name = $this->value('name', 'Name');
|
||||
$email = strtolower($this->value('email', 'Email'));
|
||||
$password = $this->value('password', 'Password (min 12 characters)', secret: true);
|
||||
$model = config('manager.user_model');
|
||||
|
||||
if ($name === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
|
||||
$this->error('A name and a valid email address are required.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($model::query()->where('email', $email)->exists()) {
|
||||
$this->error("A user with email {$email} already exists.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (mb_strlen($password) < 12) {
|
||||
$this->error('Password must be at least 12 characters.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
// Direct assignment: a super admin is never mass-assignable.
|
||||
$user = new $model;
|
||||
$user->forceFill(['name' => $name, 'email' => $email, 'password' => Hash::make($password)]);
|
||||
$user->is_super_admin = true;
|
||||
$user->save();
|
||||
|
||||
$this->info("Super admin account for {$name} <{$email}> created.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/** The option when it was given, otherwise the answer to a question. */
|
||||
private function value(string $option, string $question, bool $secret = false): string
|
||||
{
|
||||
$given = $this->option($option);
|
||||
|
||||
if (is_string($given) && trim($given) !== '') {
|
||||
return $secret ? $given : trim($given);
|
||||
}
|
||||
|
||||
$answer = $secret ? $this->secret($question) : $this->ask($question);
|
||||
|
||||
if (! is_string($answer)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $secret ? $answer : trim($answer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Users;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use IriksIT\Manager\Models\Group;
|
||||
use IriksIT\Manager\Support\ModuleRegistry;
|
||||
|
||||
/** The groups and what each allows. Only for a super admin (the `groups.manage` gate). */
|
||||
class GroupController
|
||||
{
|
||||
public function __construct(private readonly ModuleRegistry $modules) {}
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'groups' => Group::query()->withCount('users')->orderBy('name')->get()
|
||||
->map(fn (Group $group) => [
|
||||
'id' => $group->id,
|
||||
'name' => $group->name,
|
||||
'description' => $group->description,
|
||||
'permissions' => $group->allowed(),
|
||||
'accounts' => $group->users_count,
|
||||
])->values(),
|
||||
'catalogue' => $this->modules->catalogue(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$group = Group::create($this->validated($request));
|
||||
|
||||
return response()->json(['id' => $group->id], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, string $group): JsonResponse
|
||||
{
|
||||
$group = Group::query()->findOrFail($group);
|
||||
$group->update($this->validated($request, $group));
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
}
|
||||
|
||||
/** The accounts in it stay; they lose what only this group allowed. */
|
||||
public function destroy(string $group): JsonResponse
|
||||
{
|
||||
$group = Group::query()->findOrFail($group);
|
||||
$group->users()->detach();
|
||||
$group->delete();
|
||||
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/** @return array{name: string, description: string|null, permissions: list<string>} */
|
||||
private function validated(Request $request, ?Group $group = null): array
|
||||
{
|
||||
$table = config('manager.table_prefix').'groups';
|
||||
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)],
|
||||
'description' => ['nullable', 'string', 'max:500'],
|
||||
'permissions' => ['array'],
|
||||
'permissions.*' => ['string', Rule::in($this->modules->permissionValues())],
|
||||
]);
|
||||
|
||||
$description = $request->string('description')->trim()->toString();
|
||||
|
||||
return [
|
||||
'name' => $request->string('name')->trim()->toString(),
|
||||
'description' => $description !== '' ? $description : null,
|
||||
'permissions' => $this->modules->complete($request->array('permissions')),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Users;
|
||||
|
||||
class UsersController
|
||||
{
|
||||
/** First opzet: lists the accounts as JSON. The screens come with the frontend. */
|
||||
public function index()
|
||||
{
|
||||
$user = config('manager.user_model');
|
||||
|
||||
return response()->json($user::query()->with('managerGroups')->latest()->paginate(25));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace IriksIT\Manager\Modules\Users;
|
||||
|
||||
use IriksIT\Manager\Modules\BaseModule;
|
||||
use IriksIT\Manager\Support\Permission;
|
||||
|
||||
class UsersModule extends BaseModule
|
||||
{
|
||||
@@ -24,14 +25,20 @@ class UsersModule extends BaseModule
|
||||
public function permissions(): array
|
||||
{
|
||||
return [
|
||||
'users.manage' => 'Create, change and delete accounts, and put them in groups',
|
||||
new Permission('accounts.manage', 'Create, change and delete accounts, and put them in groups', 'Accounts'),
|
||||
];
|
||||
}
|
||||
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Users', 'route' => 'manager.users.index', 'permission' => 'users.manage'],
|
||||
['label' => 'Accounts', 'route' => 'manager.accounts.index', 'permission' => 'accounts.manage'],
|
||||
['label' => 'Groups', 'route' => 'manager.groups.index', 'permission' => 'groups.manage'],
|
||||
];
|
||||
}
|
||||
|
||||
public function commands(): array
|
||||
{
|
||||
return [CreateManagerUser::class];
|
||||
}
|
||||
}
|
||||
@@ -9,31 +9,36 @@ return new class extends Migration
|
||||
public function up(): void
|
||||
{
|
||||
$prefix = config('manager.table_prefix');
|
||||
$users = (new (config('manager.user_model')))->getTable();
|
||||
|
||||
// New accounts are never super admins; an existing one is not promoted here.
|
||||
// `manager:create-user` is the way to make a super admin.
|
||||
if (! Schema::hasColumn($users, 'is_super_admin')) {
|
||||
Schema::table($users, fn (Blueprint $table) => $table->boolean('is_super_admin')->default(false));
|
||||
}
|
||||
|
||||
Schema::create($prefix.'groups', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('name')->unique();
|
||||
$table->string('description', 500)->nullable();
|
||||
$table->json('permissions')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create($prefix.'group_user', function (Blueprint $table) use ($prefix) {
|
||||
Schema::create($prefix.'group_user', function (Blueprint $table) use ($prefix, $users) {
|
||||
$table->foreignId('group_id')->constrained($prefix.'groups')->cascadeOnDelete();
|
||||
$table->unsignedBigInteger('user_id')->index();
|
||||
$table->foreignId('user_id')->constrained($users)->cascadeOnDelete();
|
||||
$table->primary(['group_id', 'user_id']);
|
||||
});
|
||||
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->boolean('manager_super_admin')->default(false);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$prefix = config('manager.table_prefix');
|
||||
$users = (new (config('manager.user_model')))->getTable();
|
||||
|
||||
Schema::table('users', fn (Blueprint $table) => $table->dropColumn('manager_super_admin'));
|
||||
Schema::dropIfExists($prefix.'group_user');
|
||||
Schema::dropIfExists($prefix.'groups');
|
||||
Schema::table($users, fn (Blueprint $table) => $table->dropColumn('is_super_admin'));
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,21 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Modules\Users\UsersController;
|
||||
use IriksIT\Manager\Modules\Users\AccountController;
|
||||
use IriksIT\Manager\Modules\Users\GroupController;
|
||||
|
||||
Route::get('/users', [UsersController::class, 'index'])->name('users.index')->middleware('can:users.manage');
|
||||
// `{account}` and `{group}` are resolved in the controllers: the user model is configurable,
|
||||
// so nothing is bound globally.
|
||||
Route::middleware('can:accounts.manage')->group(function () {
|
||||
Route::get('/accounts', [AccountController::class, 'index'])->name('accounts.index');
|
||||
Route::post('/accounts', [AccountController::class, 'store'])->name('accounts.store');
|
||||
Route::put('/accounts/{account}', [AccountController::class, 'update'])->name('accounts.update')->whereNumber('account');
|
||||
Route::delete('/accounts/{account}', [AccountController::class, 'destroy'])->name('accounts.destroy')->whereNumber('account');
|
||||
});
|
||||
|
||||
Route::middleware('can:groups.manage')->group(function () {
|
||||
Route::get('/groups', [GroupController::class, 'index'])->name('groups.index');
|
||||
Route::post('/groups', [GroupController::class, 'store'])->name('groups.store');
|
||||
Route::put('/groups/{group}', [GroupController::class, 'update'])->name('groups.update')->whereNumber('group');
|
||||
Route::delete('/groups/{group}', [GroupController::class, 'destroy'])->name('groups.destroy')->whereNumber('group');
|
||||
});
|
||||
Reference in new issue
Block a user