diff --git a/AGENTS.md b/AGENTS.md index 22ae0db..c924aa0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,5 +15,5 @@ between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one ## Open decisions 1. Frontend: ship the Inertia/Vue screens inside the package (built assets, published to the host) or make the package headless with a separate UI package. -2. Moving the real controllers, revisions, audit log and the Thijs-style "simple screens" from bouwbedrijf.iriks-it.nl, module by module. +2. Moving the rest from bouwbedrijf.iriks-it.nl, module by module: posts (+labels), pages, reviews, then revisions, audit log, login and profile. Users and media are done. Leave out what is site-specific (the IriksIT API disk, the owner's simple screens, client names): this repo is public. 3. How the host's own `User` and a package `Group` relate when the host has its own roles. diff --git a/README.md b/README.md index d719b8a..d366627 100644 --- a/README.md +++ b/README.md @@ -31,11 +31,44 @@ that one is off. Implement `IriksIT\Manager\Contracts\Module` (or extend `Modules\BaseModule`), keep `routes.php` and a `migrations/` folder next to the class, and add the class to `available` in the config. -## State of this first version +## Users module -Done: module registry and switches, permissions per module as gates, groups, super admin, routes and -migrations per module, a menu that shows only what an account may reach, tests (`composer test`). +Accounts and groups. `HasManagerAccess` on the host `User` model gives it `managerGroups()`, +`managerPermissions()`, `hasManagerPermission()`, `managerOutranks()` and `managerMayGive()`. +Keep `is_super_admin` out of `$fillable`: nobody becomes a super admin through a form. -Not done yet, on purpose: the screens. The modules answer with JSON; the frontend (the Inertia/Vue -screens of bouwbedrijf.iriks-it.nl, or something the package ships itself) is the next decision, see -`AGENTS.md`. +```bash +php artisan manager:create-user # the only way to make a super admin +``` + +- A group is a name plus permissions; a permission that needs another one (`posts.publish` needs + `posts.write`) brings it along. Permissions of a module that is off are ignored. +- Whoever manages accounts only touches accounts that need nothing more than their own rights, and + only hands out groups that give nothing they lack themselves. +- `groups.manage` is a gate for super admins only, not a permission of a group. +- The package defines one gate per permission and **no `Gate::before`**: it never answers for the + abilities of your own app. +- The migration adds `is_super_admin` to your users table (the table of `manager.user_model`). It + promotes nobody. + +## Media module + +Files live on a Laravel filesystem disk (`manager.media.disk`); each row remembers its own disk. + +- Manager (behind `manager.middleware`): `GET /manager/media`, `/manager/media/items`, `POST`, + `PUT /{id}`, `DELETE /{id}`. Limits (total room, file size, extensions) are in `manager.media.*`. +- Visitors: `GET /media-files/{id}/{filename}/view`, outside the manager, no session. ETag, byte + ranges, `nosniff`, and only images, video and PDF are shown inline. Rate limiter `media-files`. +- Where a file is used: other modules or your app register a source with + `app(IriksIT\Manager\Support\MediaUsage::class)->register(fn () => $texts)`. Posts and Pages do. +- No SVG: it can carry scripts. + +## State of this version + +Done: module registry and switches, permissions per module, users (accounts, groups, command) and +media (library and public file route), 30+ tests (`composer test`). + +The answers of every action are JSON, in the shape the screens of bouwbedrijf.iriks-it.nl got as +Inertia props. The screens themselves are not in the package yet: the frontend is an open decision +(`AGENTS.md`). Posts, pages and reviews are still skeletons (a list), and so are login, profile, the +audit log and revisions: they are not part of users and media. diff --git a/TOKENS.md b/TOKENS.md index 129b836..7dfebca 100644 --- a/TOKENS.md +++ b/TOKENS.md @@ -1,6 +1,7 @@ -# Tokenverbruik van dit project +# Tokenverbruik en uren van dit project Per stuk werk een rij; zie `dev/token-usage.py`. -| Datum | Onderdeel | Versie | Model | Stappen | Uitvoer | Invoer | Cache geschreven | Cache gelezen | -|---|---|---|---|---|---|---|---|---| +| Datum | Onderdeel | Versie | Model | Stappen | Uitvoer | Invoer | Cache geschreven | Cache gelezen | Uren | +|---|---|---|---|---:|---:|---:|---:|---:|---:| +| 2026-12-04 | Eerste opzet van het pakket: modules, schakelaars, rechten. Gebruikers en media uit bouwbedrijf overgezet | - | claude-sonnet-5-5 | 34 | 57.433 | 76 | 131.194 | 3.225.205 | 0,18 | diff --git a/composer.json b/composer.json index 5373158..efcb664 100644 --- a/composer.json +++ b/composer.json @@ -6,10 +6,16 @@ "keywords": ["laravel", "manager", "cms", "admin", "modules"], "require": { "php": "^8.4", - "illuminate/support": "^13.0", + "illuminate/auth": "^13.0", + "illuminate/cache": "^13.0", + "illuminate/console": "^13.0", + "illuminate/contracts": "^13.0", "illuminate/database": "^13.0", + "illuminate/filesystem": "^13.0", "illuminate/http": "^13.0", - "illuminate/routing": "^13.0" + "illuminate/routing": "^13.0", + "illuminate/support": "^13.0", + "illuminate/validation": "^13.0" }, "require-dev": { "orchestra/testbench": "^11.0", diff --git a/config/manager.php b/config/manager.php index 7963c66..c8101c7 100644 --- a/config/manager.php +++ b/config/manager.php @@ -45,9 +45,25 @@ return [ ], /* - | The disk for uploaded media. + | The media library. Files live on a Laravel filesystem disk; each media row remembers + | its own disk, so a file stays where it was uploaded when `disk` changes later. */ - 'media_disk' => env('MANAGER_MEDIA_DISK', 'public'), + 'media' => [ + 'disk' => env('MANAGER_MEDIA_DISK', 'public'), + + // How much room the library has in total, in GB. An upload that would go over it is refused. + 'max_total_gb' => (float) env('MANAGER_MEDIA_MAX_TOTAL_GB', 15), + + // Largest single upload in MB. PHP and the web server must allow it too + // (upload_max_filesize, post_max_size, client_max_body_size). + 'max_file_mb' => (int) env('MANAGER_MEDIA_MAX_FILE_MB', 40), + + // File extensions the library accepts. SVG is deliberately missing: it can carry scripts. + 'extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'pdf', 'mp4', 'webm'], + + // Visitors loading files per minute per address (the `media-files` rate limiter). + 'per_minute' => 600, + ], /* | Prefix for the tables of the package. diff --git a/src/Concerns/HasManagerAccess.php b/src/Concerns/HasManagerAccess.php index 510caa1..ab9b7fc 100644 --- a/src/Concerns/HasManagerAccess.php +++ b/src/Concerns/HasManagerAccess.php @@ -4,15 +4,18 @@ namespace IriksIT\Manager\Concerns; use Illuminate\Database\Eloquent\Relations\BelongsToMany; 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 - * adds `manager_super_admin` to the users table and creates the groups). + * Put this on the User model of the host app (needs the Users module). * - * 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 { + /** @return BelongsToMany */ public function managerGroups(): BelongsToMany { 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 { - return (bool) $this->manager_super_admin; + return (bool) $this->getAttribute('is_super_admin'); + } + + /** + * Everything this account may do in the manager. + * + * @return list + */ + 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 + { + 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()) { 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()) === []; } } diff --git a/src/Contracts/Module.php b/src/Contracts/Module.php index cb3e68b..f63c8e9 100644 --- a/src/Contracts/Module.php +++ b/src/Contracts/Module.php @@ -2,6 +2,8 @@ namespace IriksIT\Manager\Contracts; +use IriksIT\Manager\Support\Permission; + /** * One switchable part of the manager. A module that is off contributes nothing: * no routes, no migrations, no menu items, no permissions. @@ -21,9 +23,9 @@ interface Module 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 + * @return list */ public function permissions(): array; @@ -33,6 +35,15 @@ interface Module /** Absolute path of the routes file, or null. */ 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. */ public function migrations(): ?string; + + /** @return list 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; } diff --git a/src/Exceptions/MediaStorageException.php b/src/Exceptions/MediaStorageException.php new file mode 100644 index 0000000..800ca12 --- /dev/null +++ b/src/Exceptions/MediaStorageException.php @@ -0,0 +1,17 @@ +mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager'); + $this->app->singleton(Support\MediaUsage::class); + $this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry( $app['config']->get('manager.available', []), $app['config']->get('manager.modules', []), @@ -24,25 +29,35 @@ class ManagerServiceProvider extends ServiceProvider $modules->validate(); $this->publishes([__DIR__.'/../config/manager.php' => config_path('manager.php')], 'manager-config'); - $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) { if ($module->migrations() !== null) { $this->loadMigrationsFrom($module->migrations()); } + + if ($this->app->runningInConsole() && $module->commands() !== []) { + $this->commands($module->commands()); + } + + $module->boot(); } $this->registerGates($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 { - 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(self::MANAGE_GROUPS, fn ($user) => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin()); } private function registerRoutes(ModuleRegistry $modules): void @@ -59,5 +74,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()); + } + } } } diff --git a/src/Models/Group.php b/src/Models/Group.php index c851492..3c1dd8f 100644 --- a/src/Models/Group.php +++ b/src/Models/Group.php @@ -2,10 +2,35 @@ 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|null $permissions + */ class Group extends Model { protected function casts(): 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 + */ + public function allowed(): array + { + return app(ModuleRegistry::class)->complete($this->permissions ?? []); + } } diff --git a/src/Models/Media.php b/src/Models/Media.php index 7fc2b58..fd00012 100644 --- a/src/Models/Media.php +++ b/src/Models/Media.php @@ -2,10 +2,90 @@ namespace IriksIT\Manager\Models; +use Illuminate\Database\Eloquent\Relations\BelongsTo; + +/** + * One file in the media library. The row is the bookkeeping; the file itself is stored on the + * filesystem disk `disk` under `location`. + */ class Media extends Model { + protected $hidden = ['disk', 'location']; + public function getTable(): string { return config('manager.table_prefix').'media'; } + + protected function casts(): array + { + return ['size' => 'integer', 'width' => 'integer', 'height' => 'integer', 'focus_x' => 'float', 'focus_y' => 'float']; + } + + public function uploader(): BelongsTo + { + return $this->belongsTo(config('manager.user_model'), 'uploaded_by'); + } + + public function isImage(): bool + { + return str_starts_with($this->mime_type, 'image/'); + } + + /** + * The start of this file's address. It holds the id, so it stays the same when the file is + * renamed, and is what content is searched for to see where a file is used. + */ + public function urlPrefix(): string + { + return '/media-files/'.$this->id.'/'; + } + + /** + * The address visitors load the file from. It ends in /view on purpose: web servers tend to + * answer anything that ends in .jpg themselves, as a file on disk, and never ask the app. + */ + public function url(): string + { + return $this->urlPrefix().rawurlencode($this->filename).'/view'; + } + + /** + * The focus point of the image behind an address from the library, as a CSS `object-position` + * value ("30% 65%"). Null for any other address, or when no focus point was set. + */ + public static function focusFor(?string $url): ?string + { + if ($url === null || preg_match('#^/media-files/(\d+)/#', $url, $match) !== 1) { + return null; + } + + $media = static::query()->whereKey((int) $match[1])->whereNotNull('focus_x')->whereNotNull('focus_y')->first(['id', 'focus_x', 'focus_y']); + + return $media instanceof self + ? round((float) $media->focus_x * 100, 2).'% '.round((float) $media->focus_y * 100, 2).'%' + : null; + } + + /** What the manager shows. Never includes where the file is stored. */ + public function toLibraryItem(int $usageCount = 0): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'filename' => $this->filename, + 'url' => $this->url(), + 'mime_type' => $this->mime_type, + 'is_image' => $this->isImage(), + 'size' => $this->size, + 'width' => $this->width, + 'height' => $this->height, + 'alt' => $this->alt, + 'focus_x' => $this->focus_x, + 'focus_y' => $this->focus_y, + 'uploaded_by' => $this->uploader?->name, + 'created_at' => $this->created_at?->toIso8601String(), + 'usage_count' => $usageCount, + ]; + } } diff --git a/src/Modules/BaseModule.php b/src/Modules/BaseModule.php index f0e406b..8fd37c5 100644 --- a/src/Modules/BaseModule.php +++ b/src/Modules/BaseModule.php @@ -35,6 +35,18 @@ abstract class BaseModule implements Module 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 { return $this->path('migrations'); diff --git a/src/Modules/Media/MediaController.php b/src/Modules/Media/MediaController.php index ab760f5..33105cf 100644 --- a/src/Modules/Media/MediaController.php +++ b/src/Modules/Media/MediaController.php @@ -2,13 +2,148 @@ namespace IriksIT\Manager\Modules\Media; +use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; +use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\Log; +use IriksIT\Manager\Exceptions\MediaStorageException; use IriksIT\Manager\Models\Media; +/** + * The media library. The library (also when opened as a picker from another form) loads and + * changes its items through these JSON actions. + */ class MediaController { - /** First opzet: lists the records as JSON. The screens come with the frontend. */ - public function index() + private const UNAVAILABLE = 'The file storage is not available right now. Try again in a moment.'; + + public function __construct(private readonly MediaLibrary $library) {} + + public function index(): JsonResponse { - return response()->json(Media::query()->latest()->paginate(25)); + return response()->json($this->limits()); + } + + public function items(): JsonResponse + { + $media = Media::query()->with('uploader')->latest()->latest('id')->get(); + $usage = $this->library->usageCounts($media); + + return response()->json([ + 'items' => $media->map(fn (Media $item) => $item->toLibraryItem($usage[$item->id] ?? 0))->values(), + ...$this->limits(), + ]); + } + + public function store(Request $request): JsonResponse + { + $request->validate([ + 'file' => ['required', 'file', 'mimes:'.implode(',', $this->extensions()), 'max:'.($this->maxMegabytes() * 1024)], + ...$this->focusRules(), + ]); + + $file = $request->file('file'); + abort_unless($file instanceof UploadedFile, 422); + + $room = $this->library->room(); + + if ($file->getSize() > $room['left']) { + $message = 'The media library is full: this file does not fit in the room that is left. Remove files that are no longer used, or raise manager.media.max_total_gb.'; + + return response()->json(['message' => $message, 'errors' => ['file' => [$message]], 'storage' => $room], 422); + } + + try { + $media = $this->library->store($file, $request->user()); + } catch (MediaStorageException $e) { + return $this->unavailable($e); + } + + if ($media->isImage()) { + $media->update($this->focus($request)); + } + + return response()->json(['item' => $media->load('uploader')->toLibraryItem(), 'storage' => $this->library->room()], 201); + } + + public function update(Request $request, string $media): JsonResponse + { + $media = Media::query()->findOrFail($media); + + $request->validate([ + 'name' => ['required', 'string', 'max:250'], + 'alt' => ['nullable', 'string', 'max:500'], + ...$this->focusRules(), + ]); + + $alt = $request->string('alt')->trim()->toString(); + + $media->update([ + 'name' => $request->string('name')->trim()->toString(), + 'alt' => $alt !== '' ? $alt : null, + // Only when the request says something about it; renaming keeps the focus point. + ...($media->isImage() && $request->has('focus_x') ? $this->focus($request) : []), + ]); + + $usage = $this->library->usageCounts([$media]); + + return response()->json(['item' => $media->load('uploader')->toLibraryItem($usage[$media->id] ?? 0)]); + } + + public function destroy(string $media): JsonResponse + { + $media = Media::query()->findOrFail($media); + + try { + $this->library->delete($media); + } catch (MediaStorageException $e) { + return $this->unavailable($e); + } + + return response()->json(['deleted' => true, 'storage' => $this->library->room()]); + } + + /** @return array> */ + private function focusRules(): array + { + return [ + 'focus_x' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_y'], + 'focus_y' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_x'], + ]; + } + + /** @return array{focus_x: float|null, focus_y: float|null} both null when none was sent */ + private function focus(Request $request): array + { + $x = $request->input('focus_x'); + $y = $request->input('focus_y'); + $set = is_numeric($x) && is_numeric($y); + + return ['focus_x' => $set ? round((float) $x, 4) : null, 'focus_y' => $set ? round((float) $y, 4) : null]; + } + + /** The reason goes to the log; the browser only hears that it did not work. */ + private function unavailable(MediaStorageException $e): JsonResponse + { + Log::warning('Media storage failed.', ['error' => $e->getMessage(), 'status' => $e->status]); + + return response()->json(['message' => self::UNAVAILABLE], 502); + } + + /** @return array{max_file_mb: int, extensions: list, storage: array{used: int, limit: int, left: int}} */ + private function limits(): array + { + return ['max_file_mb' => $this->maxMegabytes(), 'extensions' => $this->extensions(), 'storage' => $this->library->room()]; + } + + private function maxMegabytes(): int + { + return max(1, config()->integer('manager.media.max_file_mb')); + } + + /** @return list */ + private function extensions(): array + { + return array_values(array_filter(config()->array('manager.media.extensions'), 'is_string')); } } diff --git a/src/Modules/Media/MediaFileController.php b/src/Modules/Media/MediaFileController.php new file mode 100644 index 0000000..1311fcd --- /dev/null +++ b/src/Modules/Media/MediaFileController.php @@ -0,0 +1,156 @@ +findOrFail((int) $media); + + $headers = $this->headers($media); + + // A media id never gets other content, so what the browser has is still right. + if (in_array($headers['ETag'], $request->getETags(), true)) { + return response('', 304, $headers); + } + + $range = $this->range($request, $media->size); + + if ($range === null) { + return response('', 416, ['Content-Range' => "bytes */{$media->size}"] + $headers); + } + + [$start, $end, $partial] = $range; + $length = $end - $start + 1; + + $headers['Content-Length'] = (string) $length; + + if ($partial) { + $headers['Content-Range'] = "bytes {$start}-{$end}/{$media->size}"; + } + + if ($request->isMethod('HEAD')) { + return response('', $partial ? 206 : 200, $headers); + } + + try { + $stream = $library->open($media); + } catch (MediaStorageException $e) { + if ($e->status === 404) { + abort(404); + } + + return response('This file is temporarily unavailable.', 503, ['Retry-After' => (string) ($e->retryAfter ?? 30), 'Cache-Control' => 'no-store']); + } + + return response()->stream(fn () => $this->send($stream, $start, $length), $partial ? 206 : 200, $headers); + } + + /** @return array */ + private function headers(Media $media): array + { + $inline = in_array($media->mime_type, self::INLINE_TYPES, true); + $name = str_replace(['"', '\\', "\r", "\n"], '', $media->filename); + + return [ + 'Content-Type' => $inline ? $media->mime_type : 'application/octet-stream', + 'Content-Disposition' => ($inline ? 'inline' : 'attachment').'; filename="'.$name.'"', + 'X-Content-Type-Options' => 'nosniff', + 'Accept-Ranges' => 'bytes', + 'Cache-Control' => 'public, max-age=31536000, immutable', + 'ETag' => '"'.($media->checksum ?? 'media-'.$media->id).'"', + ]; + } + + /** + * The part of the file the browser asks for: [first byte, last byte, is it a part]. + * Null when the request asks for bytes the file does not have. + * + * @return array{int, int, bool}|null + */ + private function range(Request $request, int $size): ?array + { + $header = $request->headers->get('Range'); + $whole = [0, max($size - 1, 0), false]; + + // No range, an empty file, or something other than one plain byte range: send it all. + if ($header === null || $size === 0 || preg_match('/^bytes=(\d*)-(\d*)$/', trim($header), $match) !== 1) { + return $whole; + } + + [, $first, $last] = $match; + + if ($first === '' && $last === '') { + return $whole; + } + + if ($first === '') { + // "bytes=-500": the last 500 bytes. + $start = max($size - (int) $last, 0); + $end = $size - 1; + } else { + $start = (int) $first; + $end = $last === '' ? $size - 1 : min((int) $last, $size - 1); + } + + if ($start >= $size || $start > $end) { + return null; + } + + return [$start, $end, true]; + } + + /** @param resource $stream */ + private function send($stream, int $start, int $length): void + { + try { + if ($start > 0 && stream_get_meta_data($stream)['seekable']) { + fseek($stream, $start); + } else { + $skip = $start; + + while ($skip > 0 && ! feof($stream)) { + $chunk = fread($stream, min(65536, $skip)); + + if ($chunk === false || $chunk === '') { + break; + } + + $skip -= strlen($chunk); + } + } + + while ($length > 0 && ! feof($stream)) { + $chunk = fread($stream, min(65536, $length)); + + if ($chunk === false || $chunk === '') { + break; + } + + echo $chunk; + flush(); + + $length -= strlen($chunk); + } + } finally { + fclose($stream); + } + } +} diff --git a/src/Modules/Media/MediaLibrary.php b/src/Modules/Media/MediaLibrary.php new file mode 100644 index 0000000..069028d --- /dev/null +++ b/src/Modules/Media/MediaLibrary.php @@ -0,0 +1,122 @@ +getClientOriginalExtension()); + $baseName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME); + $filename = (Str::slug($baseName) ?: 'file').($extension !== '' ? '.'.$extension : ''); + $path = $file->getRealPath(); + + if ($path === false) { + throw new MediaStorageException('The uploaded file could not be read.'); + } + + $mimeType = $file->getMimeType() ?? 'application/octet-stream'; + $dimensions = str_starts_with($mimeType, 'image/') ? @getimagesize($path) : false; + $disk ??= config('manager.media.disk'); + + $location = $file->store('media/'.now()->format('Y/m'), $disk); + + if ($location === false) { + throw new MediaStorageException('The file could not be stored.'); + } + + return Media::create([ + 'disk' => $disk, + 'location' => $location, + 'name' => Str::limit(trim($baseName) !== '' ? trim($baseName) : 'File', 250, ''), + 'filename' => $filename, + 'mime_type' => $mimeType, + 'size' => (int) $file->getSize(), + 'checksum' => hash_file('sha256', $path) ?: null, + 'width' => $dimensions !== false ? $dimensions[0] : null, + 'height' => $dimensions !== false ? $dimensions[1] : null, + 'uploaded_by' => $uploader?->getAuthIdentifier(), + ]); + } + + /** + * How full the library is: what all files together take, how much it may hold + * (`manager.media.max_total_gb`) and what is left. In bytes. + * + * @return array{used: int, limit: int, left: int} + */ + public function room(): array + { + $configured = config('manager.media.max_total_gb'); + $limit = (int) round((is_numeric($configured) ? max(0.0, (float) $configured) : 15.0) * 1_000_000_000); + $used = (int) Media::query()->sum('size'); + + return ['used' => $used, 'limit' => $limit, 'left' => max(0, $limit - $used)]; + } + + /** + * Open a file's content as a stream. Read it and close it. + * + * @return resource + * + * @throws MediaStorageException with status 404 when the file is gone + */ + public function open(Media $media) + { + $stream = Storage::disk($media->disk)->readStream($media->location); + + if (! is_resource($stream)) { + throw new MediaStorageException('The file is no longer there.', 404); + } + + return $stream; + } + + /** Delete the file and then its row. When the storage refuses, the row stays. */ + public function delete(Media $media): void + { + $disk = Storage::disk($media->disk); + + if ($disk->exists($media->location) && ! $disk->delete($media->location)) { + throw new MediaStorageException('The file could not be deleted.'); + } + + $media->delete(); + } + + /** + * How often each media file is used, keyed by media id: how many of the registered sources + * (MediaUsage) hold its address. Nothing registered means 0. + * + * @param iterable $items + * @return array + */ + public function usageCounts(iterable $items): array + { + $haystacks = $this->usage->haystacks(); + $counts = []; + + foreach ($items as $media) { + $prefix = $media->urlPrefix(); + $counts[$media->id] = count(array_filter($haystacks, fn (string $text) => str_contains($text, $prefix))); + } + + return $counts; + } +} diff --git a/src/Modules/Media/MediaModule.php b/src/Modules/Media/MediaModule.php index df698be..8ee7f6f 100644 --- a/src/Modules/Media/MediaModule.php +++ b/src/Modules/Media/MediaModule.php @@ -2,7 +2,11 @@ namespace IriksIT\Manager\Modules\Media; +use Illuminate\Cache\RateLimiting\Limit; +use Illuminate\Http\Request; +use Illuminate\Support\Facades\RateLimiter; use IriksIT\Manager\Modules\BaseModule; +use IriksIT\Manager\Support\Permission; class MediaModule extends BaseModule { @@ -24,10 +28,10 @@ class MediaModule extends BaseModule public function permissions(): array { return [ - 'media.view' => 'See the media library', - 'media.upload' => 'Upload files', - 'media.edit' => 'Change name and description of a file', - 'media.delete' => 'Delete files', + new Permission('media.view', 'See the media library and pick files from it', 'Media'), + new Permission('media.upload', 'Upload files', 'Media', needs: ['media.view']), + new Permission('media.edit', 'Change the name, description and focus point of a file', 'Media', needs: ['media.view']), + new Permission('media.delete', 'Delete files', 'Media', needs: ['media.view']), ]; } @@ -37,4 +41,9 @@ class MediaModule extends BaseModule ['label' => 'Media', 'route' => 'manager.media.index', 'permission' => 'media.view'], ]; } + + public function boot(): void + { + RateLimiter::for('media-files', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.media.per_minute', 600)))->by((string) $request->ip())); + } } diff --git a/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php b/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php index 5c38cf8..3e22b1e 100644 --- a/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php +++ b/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php @@ -8,18 +8,26 @@ return new class extends Migration { public function up(): void { - Schema::create(config('manager.table_prefix').'media', function (Blueprint $table) { + $users = (new (config('manager.user_model')))->getTable(); + + // The file itself is elsewhere: `disk` says where, `location` is its path there. + Schema::create(config('manager.table_prefix').'media', function (Blueprint $table) use ($users) { $table->id(); - $table->string('disk'); - $table->string('path'); + $table->string('disk', 40); + $table->string('location'); + $table->string('name'); $table->string('filename'); - $table->string('mime_type'); + $table->string('mime_type', 100); $table->unsignedBigInteger('size'); + $table->string('checksum', 64)->nullable(); $table->unsignedInteger('width')->nullable(); $table->unsignedInteger('height')->nullable(); - $table->string('title')->nullable(); - $table->text('description')->nullable(); - $table->unsignedBigInteger('uploaded_by')->nullable()->index(); + $table->string('alt', 500)->nullable(); + // The part of an image that must stay in view when it is cropped to fit: + // 0-1 from the left and from the top. + $table->decimal('focus_x', 5, 4)->nullable(); + $table->decimal('focus_y', 5, 4)->nullable(); + $table->foreignId('uploaded_by')->nullable()->constrained($users)->nullOnDelete(); $table->timestamps(); }); } diff --git a/src/Modules/Media/public-routes.php b/src/Modules/Media/public-routes.php new file mode 100644 index 0000000..6577da9 --- /dev/null +++ b/src/Modules/Media/public-routes.php @@ -0,0 +1,12 @@ +whereNumber('media') + ->middleware('throttle:media-files') + ->name('manager.media.file'); diff --git a/src/Modules/Media/routes.php b/src/Modules/Media/routes.php index 0cec8fb..2b81661 100644 --- a/src/Modules/Media/routes.php +++ b/src/Modules/Media/routes.php @@ -4,3 +4,7 @@ use Illuminate\Support\Facades\Route; use IriksIT\Manager\Modules\Media\MediaController; Route::get('/media', [MediaController::class, 'index'])->name('media.index')->middleware('can:media.view'); +Route::get('/media/items', [MediaController::class, 'items'])->name('media.items')->middleware('can:media.view'); +Route::post('/media', [MediaController::class, 'store'])->name('media.store')->middleware('can:media.upload'); +Route::put('/media/{media}', [MediaController::class, 'update'])->name('media.update')->middleware('can:media.edit')->whereNumber('media'); +Route::delete('/media/{media}', [MediaController::class, 'destroy'])->name('media.destroy')->middleware('can:media.delete')->whereNumber('media'); diff --git a/src/Modules/Pages/PagesModule.php b/src/Modules/Pages/PagesModule.php index 25fc4c4..4e5b3ab 100644 --- a/src/Modules/Pages/PagesModule.php +++ b/src/Modules/Pages/PagesModule.php @@ -2,7 +2,10 @@ namespace IriksIT\Manager\Modules\Pages; +use IriksIT\Manager\Models\Page; use IriksIT\Manager\Modules\BaseModule; +use IriksIT\Manager\Support\MediaUsage; +use IriksIT\Manager\Support\Permission; class PagesModule extends BaseModule { @@ -24,7 +27,7 @@ class PagesModule extends BaseModule public function permissions(): array { return [ - 'pages.edit' => 'Change the texts of the pages', + new Permission('pages.edit', 'Change the texts of the pages', 'Site content'), ]; } @@ -34,4 +37,10 @@ class PagesModule extends BaseModule ['label' => 'Pages', 'route' => 'manager.pages.index', 'permission' => 'pages.edit'], ]; } + + /** Where the media library looks for the use of a file: the texts of the pages. */ + public function boot(): void + { + app(MediaUsage::class)->register(fn () => Page::query()->get(['body'])->flatMap(fn (Page $row) => array_values($row->only(['body'])))); + } } diff --git a/src/Modules/Posts/PostsModule.php b/src/Modules/Posts/PostsModule.php index 1de85ac..986cf1c 100644 --- a/src/Modules/Posts/PostsModule.php +++ b/src/Modules/Posts/PostsModule.php @@ -2,7 +2,10 @@ namespace IriksIT\Manager\Modules\Posts; +use IriksIT\Manager\Models\Post; use IriksIT\Manager\Modules\BaseModule; +use IriksIT\Manager\Support\MediaUsage; +use IriksIT\Manager\Support\Permission; class PostsModule extends BaseModule { @@ -24,10 +27,10 @@ class PostsModule extends BaseModule public function permissions(): array { return [ - 'posts.view' => 'See the posts, drafts included', - 'posts.write' => 'Write and change posts', - 'posts.publish' => 'Publish and unpublish posts', - 'posts.delete' => 'Delete posts', + new Permission('posts.view', 'See the posts, drafts included', 'Posts'), + new Permission('posts.write', 'Write posts: create drafts and change them', 'Posts', needs: ['posts.view']), + new Permission('posts.publish', 'Publish, schedule and unpublish posts, and change posts that are live', 'Posts', needs: ['posts.view', 'posts.write']), + new Permission('posts.delete', 'Delete posts', 'Posts', needs: ['posts.view']), ]; } @@ -37,4 +40,10 @@ class PostsModule extends BaseModule ['label' => 'Posts', 'route' => 'manager.posts.index', 'permission' => 'posts.view'], ]; } + + /** Where the media library looks for the use of a file: the texts of the posts. */ + public function boot(): void + { + app(MediaUsage::class)->register(fn () => Post::query()->get(['body', 'excerpt'])->flatMap(fn (Post $row) => array_values($row->only(['body', 'excerpt'])))); + } } diff --git a/src/Modules/Reviews/ReviewsModule.php b/src/Modules/Reviews/ReviewsModule.php index 0217148..d0618fe 100644 --- a/src/Modules/Reviews/ReviewsModule.php +++ b/src/Modules/Reviews/ReviewsModule.php @@ -3,6 +3,7 @@ namespace IriksIT\Manager\Modules\Reviews; use IriksIT\Manager\Modules\BaseModule; +use IriksIT\Manager\Support\Permission; class ReviewsModule extends BaseModule { @@ -24,7 +25,7 @@ class ReviewsModule extends BaseModule public function permissions(): array { return [ - 'reviews.manage' => 'Manage the reviews', + new Permission('reviews.manage', 'Manage the reviews', 'Site content'), ]; } diff --git a/src/Modules/Users/AccountController.php b/src/Modules/Users/AccountController.php new file mode 100644 index 0000000..ec5411f --- /dev/null +++ b/src/Modules/Users/AccountController.php @@ -0,0 +1,168 @@ +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 */ + private function model(): string + { + return config('manager.user_model'); + } + + private function find(string $id) + { + return $this->model()::query()->findOrFail($id); + } + + /** @return array> */ + 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 + */ + 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; + } +} diff --git a/src/Modules/Users/CreateManagerUser.php b/src/Modules/Users/CreateManagerUser.php new file mode 100644 index 0000000..89163eb --- /dev/null +++ b/src/Modules/Users/CreateManagerUser.php @@ -0,0 +1,78 @@ +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); + } +} diff --git a/src/Modules/Users/GroupController.php b/src/Modules/Users/GroupController.php new file mode 100644 index 0000000..b8c22f2 --- /dev/null +++ b/src/Modules/Users/GroupController.php @@ -0,0 +1,76 @@ +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} */ + 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')), + ]; + } +} diff --git a/src/Modules/Users/UsersController.php b/src/Modules/Users/UsersController.php deleted file mode 100644 index 15f447b..0000000 --- a/src/Modules/Users/UsersController.php +++ /dev/null @@ -1,14 +0,0 @@ -json($user::query()->with('managerGroups')->latest()->paginate(25)); - } -} diff --git a/src/Modules/Users/UsersModule.php b/src/Modules/Users/UsersModule.php index 51bae60..f6b99d3 100644 --- a/src/Modules/Users/UsersModule.php +++ b/src/Modules/Users/UsersModule.php @@ -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]; + } } diff --git a/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php b/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php index 71626df..64aacfd 100644 --- a/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php +++ b/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php @@ -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')); } }; diff --git a/src/Modules/Users/routes.php b/src/Modules/Users/routes.php index cfef85a..c87db22 100644 --- a/src/Modules/Users/routes.php +++ b/src/Modules/Users/routes.php @@ -1,6 +1,21 @@ 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'); +}); diff --git a/src/Support/MediaUsage.php b/src/Support/MediaUsage.php new file mode 100644 index 0000000..cef3f56 --- /dev/null +++ b/src/Support/MediaUsage.php @@ -0,0 +1,36 @@ +> */ + private array $sources = []; + + /** @param Closure(): iterable $source */ + public function register(Closure $source): void + { + $this->sources[] = $source; + } + + /** @return list */ + public function haystacks(): array + { + $texts = []; + + foreach ($this->sources as $source) { + foreach ($source() as $text) { + $texts[] = is_string($text) ? $text : ''; + } + } + + return $texts; + } +} diff --git a/src/Support/ModuleRegistry.php b/src/Support/ModuleRegistry.php index 8200989..80312fe 100644 --- a/src/Support/ModuleRegistry.php +++ b/src/Support/ModuleRegistry.php @@ -65,18 +65,72 @@ final class ModuleRegistry } } - /** @return array permission value => label, of the active modules only */ + /** @return array permission value => permission, of the active modules only */ public function permissions(): array { $permissions = []; foreach ($this->active() as $module) { - $permissions += $module->permissions(); + foreach ($module->permissions() as $permission) { + $permissions[$permission->value] = $permission; + } } return $permissions; } + /** @return list */ + 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 $values + * @return list + */ + 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}>}> + */ + 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 */ public function navigation(): array { diff --git a/src/Support/Permission.php b/src/Support/Permission.php new file mode 100644 index 0000000..dce806c --- /dev/null +++ b/src/Support/Permission.php @@ -0,0 +1,23 @@ +.`, 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 $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 = [], + ) {} +} diff --git a/tests/Feature/MediaOffTest.php b/tests/Feature/MediaOffTest.php new file mode 100644 index 0000000..05114a7 --- /dev/null +++ b/tests/Feature/MediaOffTest.php @@ -0,0 +1,14 @@ +toBeFalse() + ->and(Route::has('manager.media.file'))->toBeFalse() + ->and(Schema::hasTable('manager_media'))->toBeFalse(); + + $this->get('/media-files/1/x.png/view')->assertNotFound(); +}); diff --git a/tests/Feature/MediaTest.php b/tests/Feature/MediaTest.php new file mode 100644 index 0000000..f964ae3 --- /dev/null +++ b/tests/Feature/MediaTest.php @@ -0,0 +1,128 @@ +createWithContent($name, file_get_contents(__DIR__.'/../Fixtures/pixel.png')); +} + +beforeEach(function () { + Storage::fake('public'); + $this->actingAs(makeUser(['media.delete', 'media.edit', 'media.upload'])); +}); + +describe('uploading', function () { + it('stores a file on the disk and records it', function () { + $item = $this->postJson('/manager/media', ['file' => png(), 'focus_x' => 0.3, 'focus_y' => 0.65])->assertCreated()->json('item'); + + $media = Media::sole(); + Storage::disk('public')->assertExists($media->location); + expect($item['url'])->toBe("/media-files/{$media->id}/my-photo.png/view") + ->and($item)->not->toHaveKeys(['disk', 'location']) + ->and($media->name)->toBe('My Photo') + ->and($media->width)->toBe(1) + ->and($media->checksum)->toBe(hash_file('sha256', __DIR__.'/../Fixtures/pixel.png')) + ->and($media->focus_x)->toBe(0.3) + ->and(Media::focusFor($item['url']))->toBe('30% 65%') + ->and(Media::focusFor('/somewhere/else'))->toBeNull(); + }); + + it('refuses what is not allowed: svg, too big, no room', function () { + $svg = UploadedFile::fake()->createWithContent('x.svg', ''); + $this->postJson('/manager/media', ['file' => $svg])->assertJsonValidationErrors('file'); + + config(['manager.media.max_file_mb' => 1]); + $this->postJson('/manager/media', ['file' => UploadedFile::fake()->create('big.pdf', 2048, 'application/pdf')])->assertJsonValidationErrors('file'); + + config(['manager.media.max_total_gb' => 0.000001]); + $this->postJson('/manager/media', ['file' => UploadedFile::fake()->create('a.pdf', 5, 'application/pdf')])->assertStatus(422)->assertJsonPath('storage.limit', 1000); + expect(Media::count())->toBe(0); + }); + + it('needs the permission', function () { + $this->actingAs(makeUser(['media.view'])); + + $this->postJson('/manager/media', ['file' => png()])->assertForbidden(); + $this->getJson('/manager/media/items')->assertOk(); + }); +}); + +describe('changing and deleting', function () { + it('renames and keeps the focus point unless one is sent', function () { + $id = $this->postJson('/manager/media', ['file' => png(), 'focus_x' => 0.1, 'focus_y' => 0.2])->json('item.id'); + + $this->putJson("/manager/media/{$id}", ['name' => 'New', 'alt' => ' A cat '])->assertOk()->assertJsonPath('item.alt', 'A cat'); + expect(Media::find($id)->focus_y)->toBe(0.2); + + $this->putJson("/manager/media/{$id}", ['name' => 'New', 'focus_x' => 0.5])->assertJsonValidationErrors('focus_y'); + }); + + it('deletes the file and the row', function () { + $this->postJson('/manager/media', ['file' => png()]); + $media = Media::sole(); + + $this->deleteJson("/manager/media/{$media->id}")->assertOk(); + + Storage::disk('public')->assertMissing($media->location); + expect(Media::count())->toBe(0); + }); +}); + +describe('usage', function () { + it('counts where a file is used, through the registered sources of the modules that are on', function () { + $id = $this->postJson('/manager/media', ['file' => png()])->json('item.id'); + Post::create(['slug' => 'a', 'title' => 'A', 'body' => "See ![x](/media-files/{$id}/my-photo.png/view)"]); + + expect(collect($this->getJson('/manager/media/items')->json('items'))->firstWhere('id', $id)['usage_count'])->toBe(1); + }); + +}); + +describe('the file for visitors', function () { + beforeEach(function () { + $this->postJson('/manager/media', ['file' => png()]); + $this->media = Media::sole(); + auth()->logout(); + $this->app['auth']->forgetGuards(); + }); + + it('is served without logging in, with caching headers', function () { + $response = $this->get($this->media->url())->assertOk()->assertHeader('Content-Type', 'image/png'); + + expect($response->headers->get('Cache-Control'))->toContain('immutable') + ->and($response->headers->get('X-Content-Type-Options'))->toBe('nosniff') + ->and($response->headers->has('Set-Cookie'))->toBeFalse() + ->and($response->streamedContent())->toBe(file_get_contents(__DIR__.'/../Fixtures/pixel.png')); + }); + + it('answers 304 for a known ETag and a part for a range', function () { + $etag = '"'.$this->media->checksum.'"'; + $this->get($this->media->url(), ['If-None-Match' => $etag])->assertStatus(304); + + $part = $this->get($this->media->url(), ['Range' => 'bytes=0-9'])->assertStatus(206)->assertHeader('Content-Range', "bytes 0-9/{$this->media->size}"); + expect($part->streamedContent())->toBe(substr(file_get_contents(__DIR__.'/../Fixtures/pixel.png'), 0, 10)); + + $this->get($this->media->url(), ['Range' => 'bytes=9999-'])->assertStatus(416); + }); + + it('offers anything that is not a safe type as a download', function () { + $this->media->update(['mime_type' => 'text/html']); + + $this->get($this->media->url())->assertHeader('Content-Type', 'application/octet-stream') + ->assertHeader('Content-Disposition', 'attachment; filename="my-photo.png"'); + }); + + it('is 404 when the row or the file is gone', function () { + $this->get('/media-files/9999/x.png/view')->assertNotFound(); + + Storage::disk('public')->delete($this->media->location); + $this->get($this->media->url())->assertNotFound(); + }); +}); diff --git a/tests/Feature/ModulesTest.php b/tests/Feature/ModulesTest.php index b100c40..1a38eaf 100644 --- a/tests/Feature/ModulesTest.php +++ b/tests/Feature/ModulesTest.php @@ -1,9 +1,9 @@ 'a', 'email' => 'a@x.nl', 'password' => 'x', 'manager_super_admin' => true]); - $other = User::create(['name' => 'b', 'email' => 'b@x.nl', 'password' => 'x']); - - $this->actingAs($admin)->getJson('/manager/posts')->assertOk(); - $this->actingAs($other)->getJson('/manager/posts')->assertForbidden(); + $this->actingAs(makeUser(superAdmin: true))->getJson('/manager/posts')->assertOk(); + $this->actingAs(makeUser())->getJson('/manager/posts')->assertForbidden(); }); -it('gives a group member the permissions of the group', function () { - $user = User::create(['name' => 'c', 'email' => 'c@x.nl', 'password' => 'x']); - $group = Group::create(['name' => 'Editors', 'permissions' => ['posts.view']]); - $user->managerGroups()->attach($group); +it('gives a group member the permissions of the group, with what they need', function () { + $user = makeUser(['posts.publish']); + expect($user->managerPermissions())->toBe(['posts.view', 'posts.write', 'posts.publish']); $this->actingAs($user)->getJson('/manager/posts')->assertOk(); $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(); +}); diff --git a/tests/Feature/UsersTest.php b/tests/Feature/UsersTest.php new file mode 100644 index 0000000..917d154 --- /dev/null +++ b/tests/Feature/UsersTest.php @@ -0,0 +1,132 @@ + $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' => ' ANN@Example.com ', 'password' => 'a-long-password-1', 'groups' => [$group->id], 'is_super_admin' => true])->assertCreated(); + + $ann = User::where('email', 'ann@example.com')->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' => 'a@example.com', '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' => 'b@example.com', 'password' => 'a-long-password-1', 'groups' => [$big->id]])->assertJsonValidationErrors('groups'); + expect(User::where('email', 'b@example.com')->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' => 'x@example.com', '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' => 'Root@Example.com', '--password' => 'a-long-password-1'])->assertSuccessful(); + + $root = User::where('email', 'root@example.com')->sole(); + expect($root->isManagerSuperAdmin())->toBeTrue()->and(Hash::check('a-long-password-1', $root->password))->toBeTrue(); + + $this->artisan('manager:create-user', ['--name' => 'Root', '--email' => 'root@example.com', '--password' => 'a-long-password-1'])->assertFailed(); + $this->artisan('manager:create-user', ['--name' => 'Root', '--email' => 'r2@example.com', '--password' => 'short'])->assertFailed(); +}); diff --git a/tests/Fixtures/User.php b/tests/Fixtures/User.php index 50506f5..ec9cded 100644 --- a/tests/Fixtures/User.php +++ b/tests/Fixtures/User.php @@ -5,9 +5,12 @@ namespace IriksIT\Manager\Tests\Fixtures; use Illuminate\Foundation\Auth\User as Authenticatable; 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 { use HasManagerAccess; - protected $guarded = []; + protected $fillable = ['name', 'email', 'password']; + + protected $hidden = ['password']; } diff --git a/tests/Fixtures/migrations/0001_01_01_000000_create_users_table.php b/tests/Fixtures/migrations/0001_01_01_000000_create_users_table.php index 2565e42..b0e92e2 100644 --- a/tests/Fixtures/migrations/0001_01_01_000000_create_users_table.php +++ b/tests/Fixtures/migrations/0001_01_01_000000_create_users_table.php @@ -13,6 +13,7 @@ return new class extends Migration $table->string('name'); $table->string('email')->unique(); $table->string('password'); + $table->rememberToken(); $table->timestamps(); }); } diff --git a/tests/Fixtures/pixel.png b/tests/Fixtures/pixel.png new file mode 100644 index 0000000..613754c Binary files /dev/null and b/tests/Fixtures/pixel.png differ diff --git a/tests/Helpers.php b/tests/Helpers.php new file mode 100644 index 0000000..b9cc535 --- /dev/null +++ b/tests/Helpers.php @@ -0,0 +1,20 @@ + $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; +} diff --git a/tests/MediaOffTestCase.php b/tests/MediaOffTestCase.php new file mode 100644 index 0000000..0c13084 --- /dev/null +++ b/tests/MediaOffTestCase.php @@ -0,0 +1,8 @@ + false]; +} diff --git a/tests/Pest.php b/tests/Pest.php index b3d9bbc..838ccb7 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1 +1,3 @@