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
@@ -4,15 +4,18 @@ namespace IriksIT\Manager\Concerns;
|
|||||||
|
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use IriksIT\Manager\Models\Group;
|
use IriksIT\Manager\Models\Group;
|
||||||
|
use IriksIT\Manager\Support\ModuleRegistry;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Put this on the User model of the host app. Needs the Users module (its migration
|
* Put this on the User model of the host app (needs the Users module).
|
||||||
* adds `manager_super_admin` to the users table and creates the groups).
|
|
||||||
*
|
*
|
||||||
* A super admin may do everything. Everyone else may do what any of their groups may do.
|
* A super admin may do everything of the manager. Everyone else may do what any of their
|
||||||
|
* groups allows. `is_super_admin` is never fillable and no form sets it: only
|
||||||
|
* `manager:create-user` makes one. Keep it out of `$fillable` in the host model.
|
||||||
*/
|
*/
|
||||||
trait HasManagerAccess
|
trait HasManagerAccess
|
||||||
{
|
{
|
||||||
|
/** @return BelongsToMany<Group, $this> */
|
||||||
public function managerGroups(): BelongsToMany
|
public function managerGroups(): BelongsToMany
|
||||||
{
|
{
|
||||||
return $this->belongsToMany(Group::class, config('manager.table_prefix').'group_user', 'user_id', 'group_id');
|
return $this->belongsToMany(Group::class, config('manager.table_prefix').'group_user', 'user_id', 'group_id');
|
||||||
@@ -20,15 +23,47 @@ trait HasManagerAccess
|
|||||||
|
|
||||||
public function isManagerSuperAdmin(): bool
|
public function isManagerSuperAdmin(): bool
|
||||||
{
|
{
|
||||||
return (bool) $this->manager_super_admin;
|
return (bool) $this->getAttribute('is_super_admin');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything this account may do in the manager.
|
||||||
|
*
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public function managerPermissions(): array
|
||||||
|
{
|
||||||
|
$registry = app(ModuleRegistry::class);
|
||||||
|
|
||||||
|
if ($this->isManagerSuperAdmin()) {
|
||||||
|
return $registry->permissionValues();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $registry->complete($this->managerGroups->flatMap(fn (Group $group) => $group->allowed())->all());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function hasManagerPermission(string $permission): bool
|
public function hasManagerPermission(string $permission): bool
|
||||||
|
{
|
||||||
|
return in_array($permission, $this->managerPermissions(), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this account may do everything $other may. Someone who manages accounts only
|
||||||
|
* touches accounts that stay within their own rights; otherwise a new password for a
|
||||||
|
* mightier account would be a way up.
|
||||||
|
*/
|
||||||
|
public function managerOutranks(self $other): bool
|
||||||
{
|
{
|
||||||
if ($this->isManagerSuperAdmin()) {
|
if ($this->isManagerSuperAdmin()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->managerGroups->contains(fn (Group $group) => in_array($permission, $group->permissions ?? [], true));
|
return ! $other->isManagerSuperAdmin() && array_diff($other->managerPermissions(), $this->managerPermissions()) === [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether this account may put someone in $group: only when the group gives nothing it lacks itself. */
|
||||||
|
public function managerMayGive(Group $group): bool
|
||||||
|
{
|
||||||
|
return $this->isManagerSuperAdmin() || array_diff($group->allowed(), $this->managerPermissions()) === [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace IriksIT\Manager\Contracts;
|
namespace IriksIT\Manager\Contracts;
|
||||||
|
|
||||||
|
use IriksIT\Manager\Support\Permission;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One switchable part of the manager. A module that is off contributes nothing:
|
* One switchable part of the manager. A module that is off contributes nothing:
|
||||||
* no routes, no migrations, no menu items, no permissions.
|
* no routes, no migrations, no menu items, no permissions.
|
||||||
@@ -21,9 +23,9 @@ interface Module
|
|||||||
public function requires(): array;
|
public function requires(): array;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Permissions this module adds, as value => label. Values are prefixed by the module key.
|
* Permissions this module adds. Values are prefixed by the module key.
|
||||||
*
|
*
|
||||||
* @return array<string, string>
|
* @return list<Permission>
|
||||||
*/
|
*/
|
||||||
public function permissions(): array;
|
public function permissions(): array;
|
||||||
|
|
||||||
@@ -33,6 +35,15 @@ interface Module
|
|||||||
/** Absolute path of the routes file, or null. */
|
/** Absolute path of the routes file, or null. */
|
||||||
public function routes(): ?string;
|
public function routes(): ?string;
|
||||||
|
|
||||||
|
/** Absolute path of a routes file outside the manager (no prefix, no manager middleware), or null. */
|
||||||
|
public function publicRoutes(): ?string;
|
||||||
|
|
||||||
/** Absolute path of the migrations folder, or null. */
|
/** Absolute path of the migrations folder, or null. */
|
||||||
public function migrations(): ?string;
|
public function migrations(): ?string;
|
||||||
|
|
||||||
|
/** @return list<class-string> Artisan commands this module adds */
|
||||||
|
public function commands(): array;
|
||||||
|
|
||||||
|
/** Runs at boot, only when the module is on (register rate limiters, usage sources, ...). */
|
||||||
|
public function boot(): void;
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,9 @@ use IriksIT\Manager\Support\ModuleRegistry;
|
|||||||
* @method static bool enabled(string $key)
|
* @method static bool enabled(string $key)
|
||||||
* @method static array active()
|
* @method static array active()
|
||||||
* @method static array permissions()
|
* @method static array permissions()
|
||||||
|
* @method static array permissionValues()
|
||||||
|
* @method static array complete(array $values)
|
||||||
|
* @method static array catalogue()
|
||||||
* @method static array navigation()
|
* @method static array navigation()
|
||||||
*
|
*
|
||||||
* @see ModuleRegistry
|
* @see ModuleRegistry
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ use IriksIT\Manager\Support\ModuleRegistry;
|
|||||||
|
|
||||||
class ManagerServiceProvider extends ServiceProvider
|
class ManagerServiceProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
|
/** Only a super admin: the groups decide what everyone else may do. Not a permission of a group. */
|
||||||
|
public const MANAGE_GROUPS = 'groups.manage';
|
||||||
|
|
||||||
public function register(): void
|
public function register(): void
|
||||||
{
|
{
|
||||||
$this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager');
|
$this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager');
|
||||||
@@ -24,25 +27,35 @@ class ManagerServiceProvider extends ServiceProvider
|
|||||||
$modules->validate();
|
$modules->validate();
|
||||||
|
|
||||||
$this->publishes([__DIR__.'/../config/manager.php' => config_path('manager.php')], 'manager-config');
|
$this->publishes([__DIR__.'/../config/manager.php' => config_path('manager.php')], 'manager-config');
|
||||||
|
|
||||||
$this->loadViewsFrom(__DIR__.'/../resources/views', 'manager');
|
$this->loadViewsFrom(__DIR__.'/../resources/views', 'manager');
|
||||||
|
|
||||||
// A module that is off adds no migrations, so a site without reviews has no reviews table.
|
|
||||||
foreach ($modules->active() as $module) {
|
foreach ($modules->active() as $module) {
|
||||||
if ($module->migrations() !== null) {
|
if ($module->migrations() !== null) {
|
||||||
$this->loadMigrationsFrom($module->migrations());
|
$this->loadMigrationsFrom($module->migrations());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($this->app->runningInConsole() && $module->commands() !== []) {
|
||||||
|
$this->commands($module->commands());
|
||||||
|
}
|
||||||
|
|
||||||
|
$module->boot();
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->registerGates($modules);
|
$this->registerGates($modules);
|
||||||
$this->registerRoutes($modules);
|
$this->registerRoutes($modules);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One gate per permission, and no Gate::before: a package must never answer for abilities
|
||||||
|
* of the host app. A super admin passes inside hasManagerPermission, for these gates only.
|
||||||
|
*/
|
||||||
private function registerGates(ModuleRegistry $modules): void
|
private function registerGates(ModuleRegistry $modules): void
|
||||||
{
|
{
|
||||||
foreach (array_keys($modules->permissions()) as $permission) {
|
foreach ($modules->permissionValues() as $permission) {
|
||||||
Gate::define($permission, fn ($user) => method_exists($user, 'hasManagerPermission') && $user->hasManagerPermission($permission));
|
Gate::define($permission, fn ($user) => method_exists($user, 'hasManagerPermission') && $user->hasManagerPermission($permission));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Gate::define(self::MANAGE_GROUPS, fn ($user) => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin());
|
||||||
}
|
}
|
||||||
|
|
||||||
private function registerRoutes(ModuleRegistry $modules): void
|
private function registerRoutes(ModuleRegistry $modules): void
|
||||||
@@ -59,5 +72,12 @@ class ManagerServiceProvider extends ServiceProvider
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Files for visitors: outside the manager, no prefix and none of its middleware.
|
||||||
|
foreach ($modules->active() as $module) {
|
||||||
|
if ($module->publicRoutes() !== null) {
|
||||||
|
$this->loadRoutesFrom($module->publicRoutes());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,10 +2,35 @@
|
|||||||
|
|
||||||
namespace IriksIT\Manager\Models;
|
namespace IriksIT\Manager\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
|
use IriksIT\Manager\Support\ModuleRegistry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A set of permissions with a name ("Writers"). Accounts are put in groups; a group is the
|
||||||
|
* only place where permissions are set.
|
||||||
|
*
|
||||||
|
* @property list<string>|null $permissions
|
||||||
|
*/
|
||||||
class Group extends Model
|
class Group extends Model
|
||||||
{
|
{
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return ['permissions' => 'array'];
|
return ['permissions' => 'array'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function users(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(config('manager.user_model'), config('manager.table_prefix').'group_user', 'group_id', 'user_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the group allows, without anything that is no permission (any more), for instance
|
||||||
|
* of a module that was switched off.
|
||||||
|
*
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public function allowed(): array
|
||||||
|
{
|
||||||
|
return app(ModuleRegistry::class)->complete($this->permissions ?? []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -35,6 +35,18 @@ abstract class BaseModule implements Module
|
|||||||
return $this->path('routes.php');
|
return $this->path('routes.php');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function publicRoutes(): ?string
|
||||||
|
{
|
||||||
|
return $this->path('public-routes.php');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function commands(): array
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function boot(): void {}
|
||||||
|
|
||||||
public function migrations(): ?string
|
public function migrations(): ?string
|
||||||
{
|
{
|
||||||
return $this->path('migrations');
|
return $this->path('migrations');
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace IriksIT\Manager\Modules\Media;
|
namespace IriksIT\Manager\Modules\Media;
|
||||||
|
|
||||||
use IriksIT\Manager\Modules\BaseModule;
|
use IriksIT\Manager\Modules\BaseModule;
|
||||||
|
use IriksIT\Manager\Support\Permission;
|
||||||
|
|
||||||
class MediaModule extends BaseModule
|
class MediaModule extends BaseModule
|
||||||
{
|
{
|
||||||
@@ -24,10 +25,10 @@ class MediaModule extends BaseModule
|
|||||||
public function permissions(): array
|
public function permissions(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'media.view' => 'See the media library',
|
new Permission('media.view', 'See the media library and pick files from it', 'Media'),
|
||||||
'media.upload' => 'Upload files',
|
new Permission('media.upload', 'Upload files', 'Media', needs: ['media.view']),
|
||||||
'media.edit' => 'Change name and description of a file',
|
new Permission('media.edit', 'Change the name, description and focus point of a file', 'Media', needs: ['media.view']),
|
||||||
'media.delete' => 'Delete files',
|
new Permission('media.delete', 'Delete files', 'Media', needs: ['media.view']),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace IriksIT\Manager\Modules\Pages;
|
namespace IriksIT\Manager\Modules\Pages;
|
||||||
|
|
||||||
use IriksIT\Manager\Modules\BaseModule;
|
use IriksIT\Manager\Modules\BaseModule;
|
||||||
|
use IriksIT\Manager\Support\Permission;
|
||||||
|
|
||||||
class PagesModule extends BaseModule
|
class PagesModule extends BaseModule
|
||||||
{
|
{
|
||||||
@@ -24,7 +25,7 @@ class PagesModule extends BaseModule
|
|||||||
public function permissions(): array
|
public function permissions(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'pages.edit' => 'Change the texts of the pages',
|
new Permission('pages.edit', 'Change the texts of the pages', 'Site content'),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace IriksIT\Manager\Modules\Posts;
|
namespace IriksIT\Manager\Modules\Posts;
|
||||||
|
|
||||||
use IriksIT\Manager\Modules\BaseModule;
|
use IriksIT\Manager\Modules\BaseModule;
|
||||||
|
use IriksIT\Manager\Support\Permission;
|
||||||
|
|
||||||
class PostsModule extends BaseModule
|
class PostsModule extends BaseModule
|
||||||
{
|
{
|
||||||
@@ -24,10 +25,10 @@ class PostsModule extends BaseModule
|
|||||||
public function permissions(): array
|
public function permissions(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'posts.view' => 'See the posts, drafts included',
|
new Permission('posts.view', 'See the posts, drafts included', 'Posts'),
|
||||||
'posts.write' => 'Write and change posts',
|
new Permission('posts.write', 'Write posts: create drafts and change them', 'Posts', needs: ['posts.view']),
|
||||||
'posts.publish' => 'Publish and unpublish posts',
|
new Permission('posts.publish', 'Publish, schedule and unpublish posts, and change posts that are live', 'Posts', needs: ['posts.view', 'posts.write']),
|
||||||
'posts.delete' => 'Delete posts',
|
new Permission('posts.delete', 'Delete posts', 'Posts', needs: ['posts.view']),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace IriksIT\Manager\Modules\Reviews;
|
namespace IriksIT\Manager\Modules\Reviews;
|
||||||
|
|
||||||
use IriksIT\Manager\Modules\BaseModule;
|
use IriksIT\Manager\Modules\BaseModule;
|
||||||
|
use IriksIT\Manager\Support\Permission;
|
||||||
|
|
||||||
class ReviewsModule extends BaseModule
|
class ReviewsModule extends BaseModule
|
||||||
{
|
{
|
||||||
@@ -24,7 +25,7 @@ class ReviewsModule extends BaseModule
|
|||||||
public function permissions(): array
|
public function permissions(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'reviews.manage' => 'Manage the reviews',
|
new Permission('reviews.manage', 'Manage the reviews', 'Site content'),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
namespace IriksIT\Manager\Modules\Users;
|
||||||
|
|
||||||
use IriksIT\Manager\Modules\BaseModule;
|
use IriksIT\Manager\Modules\BaseModule;
|
||||||
|
use IriksIT\Manager\Support\Permission;
|
||||||
|
|
||||||
class UsersModule extends BaseModule
|
class UsersModule extends BaseModule
|
||||||
{
|
{
|
||||||
@@ -24,14 +25,20 @@ class UsersModule extends BaseModule
|
|||||||
public function permissions(): array
|
public function permissions(): array
|
||||||
{
|
{
|
||||||
return [
|
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
|
public function navigation(): array
|
||||||
{
|
{
|
||||||
return [
|
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
|
public function up(): void
|
||||||
{
|
{
|
||||||
$prefix = config('manager.table_prefix');
|
$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) {
|
Schema::create($prefix.'groups', function (Blueprint $table) {
|
||||||
$table->id();
|
$table->id();
|
||||||
$table->string('name')->unique();
|
$table->string('name')->unique();
|
||||||
|
$table->string('description', 500)->nullable();
|
||||||
$table->json('permissions')->nullable();
|
$table->json('permissions')->nullable();
|
||||||
$table->timestamps();
|
$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->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']);
|
$table->primary(['group_id', 'user_id']);
|
||||||
});
|
});
|
||||||
|
|
||||||
Schema::table('users', function (Blueprint $table) {
|
|
||||||
$table->boolean('manager_super_admin')->default(false);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function down(): void
|
public function down(): void
|
||||||
{
|
{
|
||||||
$prefix = config('manager.table_prefix');
|
$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.'group_user');
|
||||||
Schema::dropIfExists($prefix.'groups');
|
Schema::dropIfExists($prefix.'groups');
|
||||||
|
Schema::table($users, fn (Blueprint $table) => $table->dropColumn('is_super_admin'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1,6 +1,21 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
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');
|
||||||
|
});
|
||||||
@@ -65,18 +65,72 @@ final class ModuleRegistry
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string, string> permission value => label, of the active modules only */
|
/** @return array<string, Permission> permission value => permission, of the active modules only */
|
||||||
public function permissions(): array
|
public function permissions(): array
|
||||||
{
|
{
|
||||||
$permissions = [];
|
$permissions = [];
|
||||||
|
|
||||||
foreach ($this->active() as $module) {
|
foreach ($this->active() as $module) {
|
||||||
$permissions += $module->permissions();
|
foreach ($module->permissions() as $permission) {
|
||||||
|
$permissions[$permission->value] = $permission;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $permissions;
|
return $permissions;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return list<string> */
|
||||||
|
public function permissionValues(): array
|
||||||
|
{
|
||||||
|
return array_keys($this->permissions());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The given values without what is no permission (any more), completed with what they
|
||||||
|
* need, in the order of the permissions.
|
||||||
|
*
|
||||||
|
* @param array<array-key, mixed> $values
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public function complete(array $values): array
|
||||||
|
{
|
||||||
|
$known = $this->permissions();
|
||||||
|
$wanted = [];
|
||||||
|
|
||||||
|
foreach ($values as $value) {
|
||||||
|
if (is_string($value) && isset($known[$value])) {
|
||||||
|
$wanted[$value] = true;
|
||||||
|
|
||||||
|
foreach ($known[$value]->needs as $needed) {
|
||||||
|
$wanted[$needed] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values(array_filter(array_keys($known), fn (string $value) => isset($wanted[$value])));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The list for the group form, per section.
|
||||||
|
*
|
||||||
|
* @return list<array{section: string, permissions: list<array{value: string, label: string, needs: list<string>}>}>
|
||||||
|
*/
|
||||||
|
public function catalogue(): array
|
||||||
|
{
|
||||||
|
$sections = [];
|
||||||
|
|
||||||
|
foreach ($this->permissions() as $permission) {
|
||||||
|
$sections[$permission->section][] = ['value' => $permission->value, 'label' => $permission->label, 'needs' => $permission->needs];
|
||||||
|
}
|
||||||
|
|
||||||
|
$catalogue = [];
|
||||||
|
foreach ($sections as $section => $permissions) {
|
||||||
|
$catalogue[] = ['section' => $section, 'permissions' => $permissions];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $catalogue;
|
||||||
|
}
|
||||||
|
|
||||||
/** @return list<array{label: string, route: string, permission: string}> */
|
/** @return list<array{label: string, route: string, permission: string}> */
|
||||||
public function navigation(): array
|
public function navigation(): array
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace IriksIT\Manager\Support;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One thing an account can be allowed to do. A group holds a list of these values;
|
||||||
|
* a module declares the ones it adds (Module::permissions()).
|
||||||
|
*/
|
||||||
|
final readonly class Permission
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param string $value `<module>.<action>`, also the name of the gate
|
||||||
|
* @param string $label what the group form says next to the tick box
|
||||||
|
* @param string $section the heading it is listed under
|
||||||
|
* @param list<string> $needs values this one is useless without; a group that gets this gets those too
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public string $value,
|
||||||
|
public string $label,
|
||||||
|
public string $section,
|
||||||
|
public array $needs = [],
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Gate;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
use IriksIT\Manager\Facades\Manager;
|
use IriksIT\Manager\Facades\Manager;
|
||||||
use IriksIT\Manager\Models\Group;
|
use IriksIT\Manager\Models\Group;
|
||||||
use IriksIT\Manager\Tests\Fixtures\User;
|
|
||||||
use IriksIT\Manager\Tests\TestCase;
|
use IriksIT\Manager\Tests\TestCase;
|
||||||
|
|
||||||
uses(TestCase::class);
|
uses(TestCase::class);
|
||||||
@@ -28,18 +28,24 @@ it('adds all of it for a module that is on', function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('lets a super admin in and keeps others out without the permission', function () {
|
it('lets a super admin in and keeps others out without the permission', function () {
|
||||||
$admin = User::create(['name' => 'a', 'email' => '[email protected]', 'password' => 'x', 'manager_super_admin' => true]);
|
$this->actingAs(makeUser(superAdmin: true))->getJson('/manager/posts')->assertOk();
|
||||||
$other = User::create(['name' => 'b', 'email' => '[email protected]', 'password' => 'x']);
|
$this->actingAs(makeUser())->getJson('/manager/posts')->assertForbidden();
|
||||||
|
|
||||||
$this->actingAs($admin)->getJson('/manager/posts')->assertOk();
|
|
||||||
$this->actingAs($other)->getJson('/manager/posts')->assertForbidden();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('gives a group member the permissions of the group', function () {
|
it('gives a group member the permissions of the group, with what they need', function () {
|
||||||
$user = User::create(['name' => 'c', 'email' => '[email protected]', 'password' => 'x']);
|
$user = makeUser(['posts.publish']);
|
||||||
$group = Group::create(['name' => 'Editors', 'permissions' => ['posts.view']]);
|
|
||||||
$user->managerGroups()->attach($group);
|
|
||||||
|
|
||||||
|
expect($user->managerPermissions())->toBe(['posts.view', 'posts.write', 'posts.publish']);
|
||||||
$this->actingAs($user)->getJson('/manager/posts')->assertOk();
|
$this->actingAs($user)->getJson('/manager/posts')->assertOk();
|
||||||
$this->actingAs($user)->getJson('/manager/pages')->assertForbidden();
|
$this->actingAs($user)->getJson('/manager/pages')->assertForbidden();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('forgets what a switched-off module allowed', function () {
|
||||||
|
$group = Group::create(['name' => 'Old', 'permissions' => ['posts.view', 'reviews.manage']]);
|
||||||
|
|
||||||
|
expect($group->allowed())->toBe(['posts.view']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not answer for abilities of the host app', function () {
|
||||||
|
expect(Gate::forUser(makeUser(superAdmin: true))->allows('host.something'))->toBeFalse();
|
||||||
|
});
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use IriksIT\Manager\Models\Group;
|
||||||
|
use IriksIT\Manager\Tests\Fixtures\User;
|
||||||
|
use IriksIT\Manager\Tests\TestCase;
|
||||||
|
|
||||||
|
uses(TestCase::class);
|
||||||
|
|
||||||
|
describe('groups', function () {
|
||||||
|
beforeEach(fn () => $this->actingAs(makeUser(superAdmin: true)));
|
||||||
|
|
||||||
|
it('lists the groups with what they allow and everything that can be allowed', function () {
|
||||||
|
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
|
||||||
|
makeUser()->managerGroups()->attach($group);
|
||||||
|
|
||||||
|
$this->getJson('/manager/groups')->assertOk()
|
||||||
|
->assertJsonPath('groups.0.name', 'Writers')
|
||||||
|
->assertJsonPath('groups.0.permissions', ['posts.view', 'posts.write'])
|
||||||
|
->assertJsonPath('groups.0.accounts', 1);
|
||||||
|
|
||||||
|
$values = collect($this->getJson('/manager/groups')->json('catalogue'))->flatMap(fn ($s) => collect($s['permissions'])->pluck('value'))->all();
|
||||||
|
expect($values)->toContain('accounts.manage', 'media.upload')->not->toContain('groups.manage', 'reviews.manage');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a group, with what its permissions need', function () {
|
||||||
|
$this->postJson('/manager/groups', ['name' => ' Editors ', 'description' => 'Publish', 'permissions' => ['posts.publish', 'media.upload']])->assertCreated();
|
||||||
|
|
||||||
|
expect(Group::sole()->permissions)->toBe(['media.view', 'media.upload', 'posts.view', 'posts.write', 'posts.publish']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses a name that is taken, a permission that does not exist and groups.manage', function () {
|
||||||
|
Group::create(['name' => 'Writers']);
|
||||||
|
|
||||||
|
$this->postJson('/manager/groups', ['name' => 'Writers'])->assertJsonValidationErrors('name');
|
||||||
|
$this->postJson('/manager/groups', ['name' => 'Others', 'permissions' => ['groups.manage']])->assertJsonValidationErrors('permissions.0');
|
||||||
|
expect(Group::count())->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('changes what a group allows, which its accounts feel at once', function () {
|
||||||
|
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
|
||||||
|
$writer = makeUser();
|
||||||
|
$writer->managerGroups()->attach($group);
|
||||||
|
|
||||||
|
$this->putJson("/manager/groups/{$group->id}", ['name' => 'Writers', 'permissions' => ['pages.edit']])->assertOk();
|
||||||
|
|
||||||
|
$this->actingAs($writer->refresh())->getJson('/manager/posts')->assertForbidden();
|
||||||
|
$this->getJson('/manager/pages')->assertOk();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes a group and leaves its accounts, without what it allowed', function () {
|
||||||
|
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
|
||||||
|
$writer = makeUser();
|
||||||
|
$writer->managerGroups()->attach($group);
|
||||||
|
|
||||||
|
$this->deleteJson("/manager/groups/{$group->id}")->assertOk();
|
||||||
|
|
||||||
|
expect(Group::count())->toBe(0)->and($writer->refresh()->managerPermissions())->toBe([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is not for someone who manages accounts but is no super admin', function () {
|
||||||
|
$this->actingAs(makeUser(['accounts.manage']));
|
||||||
|
|
||||||
|
$this->getJson('/manager/groups')->assertForbidden();
|
||||||
|
$this->postJson('/manager/groups', ['name' => 'Mine'])->assertForbidden();
|
||||||
|
expect(Group::where('name', 'Mine')->exists())->toBeFalse();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('accounts', function () {
|
||||||
|
it('creates an account with a hashed password, never as super admin', function () {
|
||||||
|
$this->actingAs(makeUser(superAdmin: true));
|
||||||
|
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
|
||||||
|
|
||||||
|
$this->postJson('/manager/accounts', ['name' => 'Ann', 'email' => ' [email protected] ', 'password' => 'a-long-password-1', 'groups' => [$group->id], 'is_super_admin' => true])->assertCreated();
|
||||||
|
|
||||||
|
$ann = User::where('email', '[email protected]')->sole();
|
||||||
|
expect(Hash::check('a-long-password-1', $ann->password))->toBeTrue()
|
||||||
|
->and($ann->isManagerSuperAdmin())->toBeFalse()
|
||||||
|
->and($ann->managerGroups->pluck('name')->all())->toBe(['Writers']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses a short password and an address that is in use', function () {
|
||||||
|
$me = makeUser(superAdmin: true);
|
||||||
|
$this->actingAs($me);
|
||||||
|
|
||||||
|
$this->postJson('/manager/accounts', ['name' => 'A', 'email' => '[email protected]', 'password' => 'short'])->assertJsonValidationErrors('password');
|
||||||
|
$this->postJson('/manager/accounts', ['name' => 'A', 'email' => $me->email, 'password' => 'a-long-password-1'])->assertJsonValidationErrors('email');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not let someone hand out more than they have', function () {
|
||||||
|
$this->actingAs(makeUser(['accounts.manage', 'posts.write']));
|
||||||
|
$big = Group::create(['name' => 'Big', 'permissions' => ['pages.edit']]);
|
||||||
|
|
||||||
|
$this->postJson('/manager/accounts', ['name' => 'B', 'email' => '[email protected]', 'password' => 'a-long-password-1', 'groups' => [$big->id]])->assertJsonValidationErrors('groups');
|
||||||
|
expect(User::where('email', '[email protected]')->exists())->toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not let someone change or delete a mightier account, or themselves', function () {
|
||||||
|
$me = makeUser(['accounts.manage']);
|
||||||
|
$mighty = makeUser(['accounts.manage', 'posts.write']);
|
||||||
|
$boss = makeUser(superAdmin: true);
|
||||||
|
$this->actingAs($me);
|
||||||
|
|
||||||
|
$this->putJson("/manager/accounts/{$mighty->id}", ['name' => 'X', 'email' => '[email protected]', 'password' => 'a-long-password-1'])->assertForbidden();
|
||||||
|
$this->deleteJson("/manager/accounts/{$boss->id}")->assertForbidden();
|
||||||
|
$this->deleteJson("/manager/accounts/{$me->id}")->assertStatus(422);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the password when it is left empty, and removes the group links on delete', function () {
|
||||||
|
$this->actingAs(makeUser(superAdmin: true));
|
||||||
|
$user = makeUser(['posts.view']);
|
||||||
|
$hash = $user->password;
|
||||||
|
|
||||||
|
$this->putJson("/manager/accounts/{$user->id}", ['name' => 'New name', 'email' => $user->email, 'password' => ''])->assertOk();
|
||||||
|
expect($user->refresh()->name)->toBe('New name')->and($user->password)->toBe($hash);
|
||||||
|
|
||||||
|
$this->deleteJson("/manager/accounts/{$user->id}")->assertOk();
|
||||||
|
expect(DB::table('manager_group_user')->count())->toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('makes a super admin only with the command', function () {
|
||||||
|
$this->artisan('manager:create-user', ['--name' => 'Root', '--email' => '[email protected]', '--password' => 'a-long-password-1'])->assertSuccessful();
|
||||||
|
|
||||||
|
$root = User::where('email', '[email protected]')->sole();
|
||||||
|
expect($root->isManagerSuperAdmin())->toBeTrue()->and(Hash::check('a-long-password-1', $root->password))->toBeTrue();
|
||||||
|
|
||||||
|
$this->artisan('manager:create-user', ['--name' => 'Root', '--email' => '[email protected]', '--password' => 'a-long-password-1'])->assertFailed();
|
||||||
|
$this->artisan('manager:create-user', ['--name' => 'Root', '--email' => '[email protected]', '--password' => 'short'])->assertFailed();
|
||||||
|
});
|
||||||
@@ -5,9 +5,12 @@ namespace IriksIT\Manager\Tests\Fixtures;
|
|||||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||||
use IriksIT\Manager\Concerns\HasManagerAccess;
|
use IriksIT\Manager\Concerns\HasManagerAccess;
|
||||||
|
|
||||||
|
/** Like the User of a normal app: no `hashed` cast, and no `is_super_admin` in $fillable. */
|
||||||
class User extends Authenticatable
|
class User extends Authenticatable
|
||||||
{
|
{
|
||||||
use HasManagerAccess;
|
use HasManagerAccess;
|
||||||
|
|
||||||
protected $guarded = [];
|
protected $fillable = ['name', 'email', 'password'];
|
||||||
|
|
||||||
|
protected $hidden = ['password'];
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,7 @@ return new class extends Migration
|
|||||||
$table->string('name');
|
$table->string('name');
|
||||||
$table->string('email')->unique();
|
$table->string('email')->unique();
|
||||||
$table->string('password');
|
$table->string('password');
|
||||||
|
$table->rememberToken();
|
||||||
$table->timestamps();
|
$table->timestamps();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use IriksIT\Manager\Models\Group;
|
||||||
|
use IriksIT\Manager\Tests\Fixtures\User;
|
||||||
|
|
||||||
|
function makeUser(array $permissions = [], bool $superAdmin = false, string $name = 'Someone'): User
|
||||||
|
{
|
||||||
|
static $n = 0;
|
||||||
|
$n++;
|
||||||
|
|
||||||
|
$user = new User(['name' => $name, 'email' => "user{$n}@example.com", 'password' => 'secret']);
|
||||||
|
$user->is_super_admin = $superAdmin;
|
||||||
|
$user->save();
|
||||||
|
|
||||||
|
if ($permissions !== []) {
|
||||||
|
$user->managerGroups()->attach(Group::create(['name' => "Group {$n}", 'permissions' => $permissions]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $user;
|
||||||
|
}
|
||||||
@@ -1 +1,3 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
require_once __DIR__.'/Helpers.php';
|
||||||
Reference in new issue
Block a user