First setup: module registry, switchable modules, permissions

This commit is contained in:
Matthijs Iriks committed 2026-12-04 01:18:14 +01:00
commit 936c794597
52 files changed
+1304

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
name: PR CI
on:
pull_request:
branches: [production, staging]
jobs:
pr-ci:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- uses: actions/checkout@v4
- run: composer validate
- run: composer install --no-interaction --prefer-dist
- run: vendor/bin/pint --test
- run: vendor/bin/pest
- run: composer audit
+4
View File
@@ -0,0 +1,4 @@
vendor/
composer.lock
.phpunit.cache/
.env
+19
View File
@@ -0,0 +1,19 @@
# laravel-manager — context for AI agents
Composer package (`iriks-it/laravel-manager`, namespace `IriksIT\Manager`): the manager that used to be copied
between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one package. Public repo, published to Packagist.
## Rules
- Every part is a `Module` (`src/Modules/<Name>`): permissions, menu, `routes.php`, `migrations/`. Off means nothing is registered.
- Core modules (users, media) are on by default; the rest is off or on per `config/manager.php`.
- Nothing site-specific in the package. A site's own part is its own module class.
- Tests: `composer test` (Pest + Testbench); style: `composer lint` (Pint).
- Branches: `production` is main, work on `feature/…` from `develop`; I never merge to `production`.
- No mention of an AI in commits or PRs. Keep a row per piece of work in `TOKENS.md` (`dev/token-usage.py`).
## 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.
3. How the host's own `User` and a package `Group` relate when the host has its own roles.
+41
View File
@@ -0,0 +1,41 @@
# iriks-it/laravel-manager
A modular backend for Laravel sites. Install it, switch on the parts the site needs, done.
```bash
composer require iriks-it/laravel-manager
php artisan vendor:publish --tag=manager-config
php artisan migrate
```
Put `IriksIT\Manager\Concerns\HasManagerAccess` on the `User` model. The manager lives at `/manager`
(`MANAGER_PATH`) behind the `web` and `auth` middleware (`config/manager.php`).
## Modules
| Key | What | Default |
|---|---|---|
| `users` | Accounts, groups and permissions | on |
| `media` | Media library | on |
| `pages` | Page texts | on |
| `posts` | Posts | on |
| `reviews` | Reviews | off |
Switch a part in `config/manager.php` (`modules`) or with `MANAGER_PAGES`, `MANAGER_POSTS`,
`MANAGER_REVIEWS`. A module that is off has **no routes, no tables, no menu item and no permissions**:
its migrations are not loaded at all. A module that needs another one (`requires()`) fails at boot when
that one is off.
## Your own module
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
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`).
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`.
+6
View File
@@ -0,0 +1,6 @@
# Tokenverbruik van dit project
Per stuk werk een rij; zie `dev/token-usage.py`.
| Datum | Onderdeel | Versie | Model | Stappen | Uitvoer | Invoer | Cache geschreven | Cache gelezen |
|---|---|---|---|---|---|---|---|---|
+51
View File
@@ -0,0 +1,51 @@
{
"name": "iriks-it/laravel-manager",
"description": "A modular backend (manager) for Laravel sites: users, media, pages, posts, reviews. Every part can be switched on or off.",
"type": "library",
"license": "MIT",
"keywords": ["laravel", "manager", "cms", "admin", "modules"],
"require": {
"php": "^8.4",
"illuminate/support": "^13.0",
"illuminate/database": "^13.0",
"illuminate/http": "^13.0",
"illuminate/routing": "^13.0"
},
"require-dev": {
"orchestra/testbench": "^11.0",
"pestphp/pest": "^5.0",
"laravel/pint": "^1.15"
},
"autoload": {
"psr-4": {
"IriksIT\\Manager\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"IriksIT\\Manager\\Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"providers": [
"IriksIT\\Manager\\ManagerServiceProvider"
],
"aliases": {
"Manager": "IriksIT\\Manager\\Facades\\Manager"
}
}
},
"scripts": {
"test": "pest",
"lint": "pint --test"
},
"config": {
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}
+56
View File
@@ -0,0 +1,56 @@
<?php
use IriksIT\Manager\Modules;
return [
/*
| The URL prefix and the route name prefix of the manager.
*/
'path' => env('MANAGER_PATH', 'manager'),
/*
| Middleware around every manager route. Authentication of the manager itself
| is left to the host app: use the guard it already has.
*/
'middleware' => ['web', 'auth'],
/*
| The Eloquent model of the people who log in. Must use IriksIT\Manager\Concerns\HasManagerAccess.
*/
'user_model' => env('MANAGER_USER_MODEL', 'App\\Models\\User'),
/*
| The modules this manager knows. Add your own class here to give a site its own part.
*/
'available' => [
Modules\Users\UsersModule::class,
Modules\Media\MediaModule::class,
Modules\Pages\PagesModule::class,
Modules\Posts\PostsModule::class,
Modules\Reviews\ReviewsModule::class,
],
/*
| Switch a part on or off per site. A key left out falls back to the default of the
| module: users and media are on, everything else is off. A module that is off has no
| routes, no tables (its migrations are not loaded), no menu item and no permissions.
*/
'modules' => [
'users' => true,
'media' => true,
'pages' => env('MANAGER_PAGES', true),
'posts' => env('MANAGER_POSTS', true),
'reviews' => env('MANAGER_REVIEWS', false),
],
/*
| The disk for uploaded media.
*/
'media_disk' => env('MANAGER_MEDIA_DISK', 'public'),
/*
| Prefix for the tables of the package.
*/
'table_prefix' => 'manager_',
];
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Adds up the tokens of a Claude Code session log, for TOKENS.md.
Usage: dev/token-usage.py LOG.jsonl [--since 2026-12-02T07:00] [--until 2026-12-02T12:00]
[--row "Wat er is gemaakt" [--version v0.2.0]]
With --row it also prints the line for the table of TOKENS.md, with the hours as its last cell.
The hours are the time that was worked in the period: from one entry of the log to the next,
the time between an answer and the next request included, pauses of more than half an hour
left out.
LOG.jsonl is the log of the session (~/.claude/projects/<folder>/<session>.jsonl); the logs of
helper agents in the folder `<session>/subagents` next to it are counted separately. The moments
are UTC, as in the log. An answer of the model can be in the log more than once; it is counted
once, by its message id.
Standard library only.
"""
import glob
import json
import os
import sys
def answers(path):
"""The usage of every answer in a log, by message id, with its moment."""
found = {}
with open(path, encoding="utf-8") as log:
for line in log:
try:
entry = json.loads(line)
except ValueError:
continue
message = entry.get("message") or {}
if entry.get("type") == "assistant" and message.get("usage") and message.get("id"):
found[message["id"]] = (message["usage"], entry.get("timestamp", ""), message.get("model"))
return found
PAUSE = 30 * 60
def hours(path, since, until):
"""The hours worked in the period, by the moments in the main log; pauses longer than PAUSE are left out."""
from datetime import datetime
moments = []
with open(path, encoding="utf-8", errors="replace") as log:
for line in log:
try:
entry = json.loads(line)
except ValueError:
continue
if entry.get("isSidechain") or entry.get("type") not in ("user", "assistant") or not entry.get("timestamp"):
continue
moments.append(entry["timestamp"])
moments.sort()
seconds = 0.0
for start, end in zip(moments, moments[1:]):
# A step counts for the period it starts in.
if (since and start[:16] < since) or (until and start[:16] >= until):
continue
gap = (datetime.fromisoformat(end.replace("Z", "+00:00")) - datetime.fromisoformat(start.replace("Z", "+00:00"))).total_seconds()
if gap <= PAUSE:
seconds += gap
return seconds / 3600
def total(found, since, until):
"""Steps, output, input, written to the cache, read from the cache; and the models seen."""
row = [0, 0, 0, 0, 0]
models = {}
for usage, moment, model in found.values():
if (since and moment[:16] < since) or (until and moment[:16] >= until):
continue
row[0] += 1
row[1] += usage.get("output_tokens", 0)
row[2] += usage.get("input_tokens", 0)
row[3] += usage.get("cache_creation_input_tokens", 0)
row[4] += usage.get("cache_read_input_tokens", 0)
if model and not model.startswith("<"):
models[model] = models.get(model, 0) + 1
return row, models
def number(value):
return f"{value:,}".replace(",", ".")
def show(name, row):
steps, out, new, written, read = row
print(f"{name}: {steps} steps | output {number(out)} | input {number(new)} | cache written {number(written)} | cache read {number(read)} | together {number(out + new + written + read)}")
def main():
args = sys.argv[1:]
names = ("--since", "--until", "--row", "--version")
option = lambda name: args[args.index(name) + 1] if name in args else None
since, until = option("--since"), option("--until")
paths = [arg for index, arg in enumerate(args) if arg not in names and (index == 0 or args[index - 1] not in names)]
if len(paths) != 1:
sys.exit(__doc__)
row, models = total(answers(paths[0]), since, until)
show("session", row)
print(f"hours worked: {hours(paths[0], since, until):.2f}")
helpers = {}
for path in glob.glob(os.path.join(os.path.splitext(paths[0])[0], "subagents", "*.jsonl")):
helpers.update(answers(path))
if helpers:
show("helper agents", total(helpers, since, until)[0])
if option("--row"):
if len(models) > 1:
print("More than one model in this period: make a row per model (--since/--until).", file=sys.stderr)
model = max(models, key=models.get) if models else "?"
day = (since or "")[:10] or "JJJJ-MM-DD"
worked = f"{hours(paths[0], since, until):.2f}".replace(".", ",")
cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in row] + [worked]
print("| " + " | ".join(cells) + " |")
if __name__ == "__main__":
main()
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true">
<testsuites>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>src</directory>
</include>
</source>
</phpunit>
+16
View File
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Manager</title>
</head>
<body>
<h1>Manager</h1>
<ul>
@foreach ($navigation as $item)
<li><a href="{{ route($item['route']) }}">{{ $item['label'] }}</a></li>
@endforeach
</ul>
</body>
</html>
+6
View File
@@ -0,0 +1,6 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Http\Controllers\DashboardController;
Route::get('/', DashboardController::class)->name('dashboard');
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace IriksIT\Manager\Concerns;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use IriksIT\Manager\Models\Group;
/**
* 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).
*
* A super admin may do everything. Everyone else may do what any of their groups may do.
*/
trait HasManagerAccess
{
public function managerGroups(): BelongsToMany
{
return $this->belongsToMany(Group::class, config('manager.table_prefix').'group_user', 'user_id', 'group_id');
}
public function isManagerSuperAdmin(): bool
{
return (bool) $this->manager_super_admin;
}
public function hasManagerPermission(string $permission): bool
{
if ($this->isManagerSuperAdmin()) {
return true;
}
return $this->managerGroups->contains(fn (Group $group) => in_array($permission, $group->permissions ?? [], true));
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace IriksIT\Manager\Contracts;
/**
* One switchable part of the manager. A module that is off contributes nothing:
* no routes, no migrations, no menu items, no permissions.
*/
interface Module
{
/** Short unique key, also the key in config('manager.modules'). */
public function key(): string;
/** Name in the menu. */
public function label(): string;
/** Core modules (users, media) are on unless a site explicitly turns them off. */
public function enabledByDefault(): bool;
/** @return list<string> keys of modules this one cannot work without */
public function requires(): array;
/**
* Permissions this module adds, as value => label. Values are prefixed by the module key.
*
* @return array<string, string>
*/
public function permissions(): array;
/** @return list<array{label: string, route: string, permission: string}> */
public function navigation(): array;
/** Absolute path of the routes file, or null. */
public function routes(): ?string;
/** Absolute path of the migrations folder, or null. */
public function migrations(): ?string;
}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace IriksIT\Manager\Exceptions;
class ModuleException extends \LogicException {}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace IriksIT\Manager\Facades;
use Illuminate\Support\Facades\Facade;
use IriksIT\Manager\Support\ModuleRegistry;
/**
* @method static bool enabled(string $key)
* @method static array active()
* @method static array permissions()
* @method static array navigation()
*
* @see ModuleRegistry
*/
class Manager extends Facade
{
protected static function getFacadeAccessor(): string
{
return ModuleRegistry::class;
}
}
@@ -0,0 +1,20 @@
<?php
namespace IriksIT\Manager\Http\Controllers;
use Illuminate\Http\Request;
use IriksIT\Manager\Support\ModuleRegistry;
class DashboardController
{
public function __invoke(Request $request, ModuleRegistry $modules)
{
// Only what this account may reach.
$navigation = array_values(array_filter(
$modules->navigation(),
fn (array $item) => $request->user()?->can($item['permission']),
));
return view('manager::dashboard', ['navigation' => $navigation]);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace IriksIT\Manager;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use IriksIT\Manager\Support\ModuleRegistry;
class ManagerServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager');
$this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry(
$app['config']->get('manager.available', []),
$app['config']->get('manager.modules', []),
));
}
public function boot(ModuleRegistry $modules): void
{
$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());
}
}
$this->registerGates($modules);
$this->registerRoutes($modules);
}
private function registerGates(ModuleRegistry $modules): void
{
foreach (array_keys($modules->permissions()) as $permission) {
Gate::define($permission, fn ($user) => method_exists($user, 'hasManagerPermission') && $user->hasManagerPermission($permission));
}
}
private function registerRoutes(ModuleRegistry $modules): void
{
Route::middleware(config('manager.middleware'))
->prefix(config('manager.path'))
->name('manager.')
->group(function () use ($modules) {
$this->loadRoutesFrom(__DIR__.'/../routes/manager.php');
foreach ($modules->active() as $module) {
if ($module->routes() !== null) {
$this->loadRoutesFrom($module->routes());
}
}
});
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace IriksIT\Manager\Models;
class Group extends Model
{
protected function casts(): array
{
return ['permissions' => 'array'];
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace IriksIT\Manager\Models;
class Media extends Model
{
public function getTable(): string
{
return config('manager.table_prefix').'media';
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace IriksIT\Manager\Models;
use Illuminate\Database\Eloquent\Model as Eloquent;
/** Base of the package models: tables get the configured prefix, e.g. manager_pages. */
abstract class Model extends Eloquent
{
protected $guarded = [];
public function getTable(): string
{
return $this->table ?? config('manager.table_prefix').parent::getTable();
}
}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace IriksIT\Manager\Models;
class Page extends Model {}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace IriksIT\Manager\Models;
class Post extends Model {}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace IriksIT\Manager\Models;
class Review extends Model {}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace IriksIT\Manager\Modules;
use IriksIT\Manager\Contracts\Module;
/**
* Convention over configuration: a module `Foo` lives in src/Modules/Foo, with
* routes.php and a migrations/ folder next to its class when it needs them.
*/
abstract class BaseModule implements Module
{
public function enabledByDefault(): bool
{
return false;
}
public function requires(): array
{
return [];
}
public function permissions(): array
{
return [];
}
public function navigation(): array
{
return [];
}
public function routes(): ?string
{
return $this->path('routes.php');
}
public function migrations(): ?string
{
return $this->path('migrations');
}
private function path(string $name): ?string
{
$path = dirname((new \ReflectionClass($this))->getFileName()).'/'.$name;
return file_exists($path) ? $path : null;
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace IriksIT\Manager\Modules\Media;
use IriksIT\Manager\Models\Media;
class MediaController
{
/** First opzet: lists the records as JSON. The screens come with the frontend. */
public function index()
{
return response()->json(Media::query()->latest()->paginate(25));
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace IriksIT\Manager\Modules\Media;
use IriksIT\Manager\Modules\BaseModule;
class MediaModule extends BaseModule
{
public function key(): string
{
return 'media';
}
public function label(): string
{
return 'Media';
}
public function enabledByDefault(): bool
{
return true;
}
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',
];
}
public function navigation(): array
{
return [
['label' => 'Media', 'route' => 'manager.media.index', 'permission' => 'media.view'],
];
}
}
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create(config('manager.table_prefix').'media', function (Blueprint $table) {
$table->id();
$table->string('disk');
$table->string('path');
$table->string('filename');
$table->string('mime_type');
$table->unsignedBigInteger('size');
$table->unsignedInteger('width')->nullable();
$table->unsignedInteger('height')->nullable();
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->unsignedBigInteger('uploaded_by')->nullable()->index();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists(config('manager.table_prefix').'media');
}
};
+6
View File
@@ -0,0 +1,6 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Media\MediaController;
Route::get('/media', [MediaController::class, 'index'])->name('media.index')->middleware('can:media.view');
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace IriksIT\Manager\Modules\Pages;
use IriksIT\Manager\Models\Page;
class PagesController
{
/** First opzet: lists the records as JSON. The screens come with the frontend. */
public function index()
{
return response()->json(Page::query()->latest()->paginate(25));
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace IriksIT\Manager\Modules\Pages;
use IriksIT\Manager\Modules\BaseModule;
class PagesModule extends BaseModule
{
public function key(): string
{
return 'pages';
}
public function label(): string
{
return 'Pages';
}
public function enabledByDefault(): bool
{
return false;
}
public function permissions(): array
{
return [
'pages.edit' => 'Change the texts of the pages',
];
}
public function navigation(): array
{
return [
['label' => 'Pages', 'route' => 'manager.pages.index', 'permission' => 'pages.edit'],
];
}
}
@@ -0,0 +1,25 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create(config('manager.table_prefix').'pages', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique();
$table->string('title');
$table->longText('body')->nullable();
$table->boolean('is_published')->default(false);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists(config('manager.table_prefix').'pages');
}
};
+6
View File
@@ -0,0 +1,6 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Pages\PagesController;
Route::get('/pages', [PagesController::class, 'index'])->name('pages.index')->middleware('can:pages.edit');
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace IriksIT\Manager\Modules\Posts;
use IriksIT\Manager\Models\Post;
class PostsController
{
/** First opzet: lists the records as JSON. The screens come with the frontend. */
public function index()
{
return response()->json(Post::query()->latest()->paginate(25));
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace IriksIT\Manager\Modules\Posts;
use IriksIT\Manager\Modules\BaseModule;
class PostsModule extends BaseModule
{
public function key(): string
{
return 'posts';
}
public function label(): string
{
return 'Posts';
}
public function enabledByDefault(): bool
{
return false;
}
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',
];
}
public function navigation(): array
{
return [
['label' => 'Posts', 'route' => 'manager.posts.index', 'permission' => 'posts.view'],
];
}
}
@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create(config('manager.table_prefix').'posts', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique();
$table->string('title');
$table->text('excerpt')->nullable();
$table->longText('body')->nullable();
$table->timestamp('published_at')->nullable()->index();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists(config('manager.table_prefix').'posts');
}
};
+6
View File
@@ -0,0 +1,6 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Posts\PostsController;
Route::get('/posts', [PostsController::class, 'index'])->name('posts.index')->middleware('can:posts.view');
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace IriksIT\Manager\Modules\Reviews;
use IriksIT\Manager\Models\Review;
class ReviewsController
{
/** First opzet: lists the records as JSON. The screens come with the frontend. */
public function index()
{
return response()->json(Review::query()->latest()->paginate(25));
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace IriksIT\Manager\Modules\Reviews;
use IriksIT\Manager\Modules\BaseModule;
class ReviewsModule extends BaseModule
{
public function key(): string
{
return 'reviews';
}
public function label(): string
{
return 'Reviews';
}
public function enabledByDefault(): bool
{
return false;
}
public function permissions(): array
{
return [
'reviews.manage' => 'Manage the reviews',
];
}
public function navigation(): array
{
return [
['label' => 'Reviews', 'route' => 'manager.reviews.index', 'permission' => 'reviews.manage'],
];
}
}
@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create(config('manager.table_prefix').'reviews', function (Blueprint $table) {
$table->id();
$table->string('author');
$table->string('place')->nullable();
$table->unsignedTinyInteger('rating')->nullable();
$table->text('body');
$table->boolean('is_visible')->default(true);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists(config('manager.table_prefix').'reviews');
}
};
+6
View File
@@ -0,0 +1,6 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Reviews\ReviewsController;
Route::get('/reviews', [ReviewsController::class, 'index'])->name('reviews.index')->middleware('can:reviews.manage');
+14
View File
@@ -0,0 +1,14 @@
<?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));
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace IriksIT\Manager\Modules\Users;
use IriksIT\Manager\Modules\BaseModule;
class UsersModule extends BaseModule
{
public function key(): string
{
return 'users';
}
public function label(): string
{
return 'Users';
}
public function enabledByDefault(): bool
{
return true;
}
public function permissions(): array
{
return [
'users.manage' => 'Create, change and delete accounts, and put them in groups',
];
}
public function navigation(): array
{
return [
['label' => 'Users', 'route' => 'manager.users.index', 'permission' => 'users.manage'],
];
}
}
@@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
$prefix = config('manager.table_prefix');
Schema::create($prefix.'groups', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->json('permissions')->nullable();
$table->timestamps();
});
Schema::create($prefix.'group_user', function (Blueprint $table) use ($prefix) {
$table->foreignId('group_id')->constrained($prefix.'groups')->cascadeOnDelete();
$table->unsignedBigInteger('user_id')->index();
$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');
Schema::table('users', fn (Blueprint $table) => $table->dropColumn('manager_super_admin'));
Schema::dropIfExists($prefix.'group_user');
Schema::dropIfExists($prefix.'groups');
}
};
+6
View File
@@ -0,0 +1,6 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Users\UsersController;
Route::get('/users', [UsersController::class, 'index'])->name('users.index')->middleware('can:users.manage');
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace IriksIT\Manager\Support;
use IriksIT\Manager\Contracts\Module;
use IriksIT\Manager\Exceptions\ModuleException;
/**
* Knows which modules exist and which of them are on for this site.
*/
final class ModuleRegistry
{
/** @var array<string, Module> */
private array $all = [];
/**
* @param list<class-string<Module>> $available
* @param array<string, bool> $switches
*/
public function __construct(array $available, private readonly array $switches)
{
foreach ($available as $class) {
$module = new $class;
$this->all[$module->key()] = $module;
}
}
/** @return array<string, Module> every known module */
public function all(): array
{
return $this->all;
}
public function has(string $key): bool
{
return isset($this->all[$key]);
}
public function enabled(string $key): bool
{
if (! $this->has($key)) {
return false;
}
return (bool) ($this->switches[$key] ?? $this->all[$key]->enabledByDefault());
}
/** @return array<string, Module> the modules that are on */
public function active(): array
{
return array_filter($this->all, fn (Module $module) => $this->enabled($module->key()));
}
/**
* A module that is on while one it needs is off is a configuration mistake: fail loudly at boot.
*/
public function validate(): void
{
foreach ($this->active() as $module) {
foreach ($module->requires() as $needed) {
if (! $this->enabled($needed)) {
throw new ModuleException("Manager module '{$module->key()}' needs module '{$needed}', which is off.");
}
}
}
}
/** @return array<string, string> permission value => label, of the active modules only */
public function permissions(): array
{
$permissions = [];
foreach ($this->active() as $module) {
$permissions += $module->permissions();
}
return $permissions;
}
/** @return list<array{label: string, route: string, permission: string}> */
public function navigation(): array
{
$items = [];
foreach ($this->active() as $module) {
array_push($items, ...$module->navigation());
}
return $items;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Facades\Manager;
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Tests\Fixtures\User;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
it('has users and media on and reviews off by default', function () {
expect(Manager::enabled('users'))->toBeTrue()
->and(Manager::enabled('media'))->toBeTrue()
->and(Manager::enabled('reviews'))->toBeFalse();
});
it('adds no routes, tables or permissions for a module that is off', function () {
expect(Route::has('manager.reviews.index'))->toBeFalse()
->and(Schema::hasTable('manager_reviews'))->toBeFalse()
->and(Manager::permissions())->not->toHaveKey('reviews.manage')
->and(collect(Manager::navigation())->pluck('label'))->not->toContain('Reviews');
});
it('adds all of it for a module that is on', function () {
expect(Route::has('manager.posts.index'))->toBeTrue()
->and(Schema::hasTable('manager_posts'))->toBeTrue()
->and(Manager::permissions())->toHaveKey('posts.publish');
});
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]);
$other = User::create(['name' => 'b', 'email' => '[email protected]', 'password' => 'x']);
$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 () {
$user = User::create(['name' => 'c', 'email' => '[email protected]', 'password' => 'x']);
$group = Group::create(['name' => 'Editors', 'permissions' => ['posts.view']]);
$user->managerGroups()->attach($group);
$this->actingAs($user)->getJson('/manager/posts')->assertOk();
$this->actingAs($user)->getJson('/manager/pages')->assertForbidden();
});
+11
View File
@@ -0,0 +1,11 @@
<?php
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Tests\ReviewsOnTestCase;
uses(ReviewsOnTestCase::class);
it('can switch an optional module on', function () {
expect(Route::has('manager.reviews.index'))->toBeTrue()
->and(Schema::hasTable('manager_reviews'))->toBeTrue();
});
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace IriksIT\Manager\Tests\Fixtures;
use Illuminate\Foundation\Auth\User as Authenticatable;
use IriksIT\Manager\Concerns\HasManagerAccess;
class User extends Authenticatable
{
use HasManagerAccess;
protected $guarded = [];
}
@@ -0,0 +1,19 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
}
};
+1
View File
@@ -0,0 +1 @@
<?php
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace IriksIT\Manager\Tests;
/** A site that switched the optional reviews module on. */
abstract class ReviewsOnTestCase extends TestCase
{
protected array $modules = ['reviews' => true];
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace IriksIT\Manager\Tests;
use Illuminate\Foundation\Testing\RefreshDatabase;
use IriksIT\Manager\ManagerServiceProvider;
use IriksIT\Manager\Tests\Fixtures\User;
use Orchestra\Testbench\TestCase as Orchestra;
abstract class TestCase extends Orchestra
{
use RefreshDatabase;
/** @var array<string, bool> */
protected array $modules = [];
protected function getPackageProviders($app): array
{
return [ManagerServiceProvider::class];
}
protected function defineEnvironment($app): void
{
$app['config']->set('database.default', 'testing');
$app['config']->set('app.key', 'base64:'.base64_encode(str_repeat('a', 32)));
$app['config']->set('manager.user_model', User::class);
$app['config']->set('manager.modules', array_merge($app['config']->get('manager.modules'), $this->modules));
}
protected function defineDatabaseMigrations(): void
{
$this->loadMigrationsFrom(__DIR__.'/Fixtures/migrations');
}
}