feat: P2 RBAC defers — REST API + invitation workflow
Closes the P2 items from /tmp/service/new/01-TZ-rbac §4.1 §4.2.
== User invitation workflow ==
New columns on users: invited_at, invited_by_id (FK self), accepted_at,
invitation_token (sha256 hash, indexed). Migration is idempotent.
User::sendInvitation($invitedBy = auth()->user())
- generates 64-char random token
- stores sha256(token) in invitation_token column (never plaintext)
- marks invited_at = now(), status = inactive
- queues UserInvitationMail to the user's email with the signed accept URL
- returns the raw token (for tests / API consumers)
User::findByInvitationToken($rawToken) hashes + lookups.
User::acceptInvitation($password) sets password (hashed cast), clears
invitation_token, marks accepted_at + email_verified_at, status = active.
Web routes (no auth — token IS the credential):
GET /invitations/{token} → password-set form
POST /invitations/{token} → validates min:8 + confirmed, accepts
Tokens expire after 7 days (checked against invited_at). Expired and
invalid tokens render dedicated views (invitations/expired.blade.php,
invitations/invalid.blade.php) instead of generic 404 — so the user
knows to ask for a resend.
UserInvitationMail uses Filament's existing markdown layout; subject
includes the tenant display_name.
== REST API ==
Twenty new endpoints under /api/v1/ (Sanctum auth + tenant scoping
via the existing EnsureTokenMatchesTenant middleware). All gated by
ADMIN_USERS_* / ADMIN_ROLES_MANAGE permissions; mechanic-level token
gets 403.
Users:
GET /users — paginated + role/status/q filters
GET /users/{u} — eager-loads roles + overrides + invitedBy
POST /users — creates inactive user + sends invitation
PATCH /users/{u} — update name/email/role/status
DELETE /users/{u} — soft delete
POST /users/{u}/activate
POST /users/{u}/deactivate — also revokes all sessions
POST /users/{u}/resend-invitation
POST /users/{u}/force-password-reset — re-sends invitation
GET /users/{u}/sessions — list active sessions (from sessions table)
DELETE /users/{u}/sessions — revoke all
DELETE /users/{u}/sessions/{sessionId} — revoke one
GET /users/{u}/roles — assigned roles
POST /users/{u}/roles — assign role
DELETE /users/{u}/roles/{role} — remove role
GET /users/{u}/permissions — effective: role perms + grants - active denies
POST /users/{u}/permission-overrides — add grant/deny (with optional expires_at)
DELETE /users/{u}/permission-overrides/{perm}
Roles:
apiResource roles — index/show/store/update/destroy
(system roles guarded against rename/delete)
GET /roles/{r}/permissions
PUT /roles/{r}/permissions — bulk sync
GET /permissions — catalog: flat list + grouped + labels + role labels
Authorization is uniform: every controller method calls $this->authorize()
which throws 403 if canDo(perm) is false. canDo() already honors the
overrides + admin bypass + audit log from earlier commits, so the API
behaves identically to the Filament UI.
== Tests ==
InvitationFlowTest (8): token generation + sha256 storage + queued mail,
findByInvitationToken happy/sad path, accept sets password + activates,
GET form renders, POST accepts + redirects, invalid token view,
backdated invited_at → expired view, password too short → validation error.
RbacApiTest (12): admin can list users, mechanic 403, create user
queues invitation, assign+remove role round-trip, effective permissions
endpoint subtracts active denies, add+remove override via API,
role index returns 7 system roles with permission counts (51 for owner),
role sync permissions, system role destroy rejected with 422,
permission catalog endpoint returns all 51 + grouped + labels,
revoke all sessions deletes only target user's rows.
Suite: 234 passed (659 assertions). Was 214.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Auth\Permissions;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use Spatie\Permission\PermissionRegistrar;
|
||||
|
||||
class RoleApiController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_ROLES_MANAGE);
|
||||
$roles = Role::withCount('permissions')->orderBy('name')->get();
|
||||
return response()->json(['data' => $roles]);
|
||||
}
|
||||
|
||||
public function show(Role $role): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_ROLES_MANAGE);
|
||||
return response()->json(['data' => $role->load('permissions')]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_ROLES_MANAGE);
|
||||
$data = $request->validate([
|
||||
'name' => 'required|string|max:64',
|
||||
'permissions' => 'sometimes|array',
|
||||
'permissions.*' => 'string',
|
||||
]);
|
||||
// Disallow overwriting system roles
|
||||
if (in_array($data['name'], array_keys(Permissions::roleMatrix()), true)) {
|
||||
return response()->json(['error' => 'System role name is reserved'], 422);
|
||||
}
|
||||
$role = Role::create(['name' => $data['name'], 'guard_name' => 'web']);
|
||||
if (! empty($data['permissions'])) {
|
||||
$role->syncPermissions($data['permissions']);
|
||||
}
|
||||
return response()->json(['data' => $role->load('permissions')], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, Role $role): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_ROLES_MANAGE);
|
||||
if (in_array($role->name, array_keys(Permissions::roleMatrix()), true)) {
|
||||
return response()->json(['error' => 'Cannot rename system role'], 422);
|
||||
}
|
||||
$data = $request->validate(['name' => 'required|string|max:64']);
|
||||
$role->update($data);
|
||||
return response()->json(['data' => $role]);
|
||||
}
|
||||
|
||||
public function destroy(Role $role): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_ROLES_MANAGE);
|
||||
if (in_array($role->name, array_keys(Permissions::roleMatrix()), true)) {
|
||||
return response()->json(['error' => 'Cannot delete system role'], 422);
|
||||
}
|
||||
$role->delete();
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
public function permissions(Role $role): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_ROLES_MANAGE);
|
||||
return response()->json(['data' => $role->permissions->pluck('name')]);
|
||||
}
|
||||
|
||||
public function syncPermissions(Request $request, Role $role): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_ROLES_MANAGE);
|
||||
$data = $request->validate([
|
||||
'permissions' => 'required|array',
|
||||
'permissions.*' => 'string',
|
||||
]);
|
||||
$role->syncPermissions($data['permissions']);
|
||||
app(PermissionRegistrar::class)->forgetCachedPermissions();
|
||||
return response()->json(['data' => $role->fresh()->permissions->pluck('name')]);
|
||||
}
|
||||
|
||||
public function permissionCatalog(): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'data' => Permission::orderBy('name')->get(['id', 'name']),
|
||||
'grouped' => Permissions::grouped(),
|
||||
'labels' => Permissions::labels(),
|
||||
'roles' => Permissions::roleLabels(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function authorize(string $permission): void
|
||||
{
|
||||
if (! auth()->user() || ! auth()->user()->canDo($permission)) {
|
||||
abort(403, "Missing permission: $permission");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Auth\Permissions;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Tenant\User;
|
||||
use App\Models\Tenant\UserPermissionOverride;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
|
||||
class UserApiController extends Controller
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_VIEW);
|
||||
|
||||
$q = User::query();
|
||||
if ($role = $request->query('role')) $q->where('role', $role);
|
||||
if ($status = $request->query('status')) $q->where('status', $status);
|
||||
if ($search = $request->query('q')) {
|
||||
$q->where(fn ($qq) => $qq->where('name', 'like', "%$search%")->orWhere('email', 'like', "%$search%"));
|
||||
}
|
||||
return response()->json([
|
||||
'data' => $q->paginate((int) $request->query('per_page', 25))->items(),
|
||||
'meta' => ['total' => $q->count()],
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_VIEW);
|
||||
return response()->json(['data' => $user->load('roles', 'permissionOverrides.permission', 'invitedBy:id,name')]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
|
||||
$data = $request->validate([
|
||||
'name' => 'required|string|max:120',
|
||||
'email' => 'required|email|max:120',
|
||||
'phone' => 'nullable|string|max:40',
|
||||
'role' => 'required|string|in:' . implode(',', array_keys(Permissions::roleMatrix())),
|
||||
'locale' => 'nullable|in:ro,ru,en',
|
||||
'send_invitation' => 'nullable|boolean',
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => $data['name'],
|
||||
'email' => $data['email'],
|
||||
'phone' => $data['phone'] ?? null,
|
||||
'role' => $data['role'],
|
||||
'locale' => $data['locale'] ?? 'ro',
|
||||
'status' => 'inactive',
|
||||
'password' => Hash::make(bin2hex(random_bytes(16))), // placeholder until invitation accept
|
||||
]);
|
||||
$user->syncRoles([$data['role']]);
|
||||
|
||||
if ($data['send_invitation'] ?? true) {
|
||||
$user->sendInvitation(auth()->user());
|
||||
}
|
||||
|
||||
return response()->json(['data' => $user->fresh(), 'invitation_sent' => $data['send_invitation'] ?? true], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
|
||||
$data = $request->validate([
|
||||
'name' => 'sometimes|string|max:120',
|
||||
'email' => 'sometimes|email|max:120',
|
||||
'phone' => 'sometimes|nullable|string|max:40',
|
||||
'locale' => 'sometimes|in:ro,ru,en',
|
||||
'role' => 'sometimes|in:' . implode(',', array_keys(Permissions::roleMatrix())),
|
||||
'status' => 'sometimes|in:active,inactive,blocked',
|
||||
]);
|
||||
$user->update($data);
|
||||
if (isset($data['role'])) $user->syncRoles([$data['role']]);
|
||||
return response()->json(['data' => $user->fresh()]);
|
||||
}
|
||||
|
||||
public function destroy(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$user->delete();
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
public function activate(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$user->update(['status' => 'active']);
|
||||
return response()->json(['data' => $user->fresh()]);
|
||||
}
|
||||
|
||||
public function deactivate(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$user->update(['status' => 'inactive']);
|
||||
DB::table('sessions')->where('user_id', $user->id)->delete();
|
||||
return response()->json(['data' => $user->fresh()]);
|
||||
}
|
||||
|
||||
public function resendInvitation(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
if ($user->accepted_at) {
|
||||
return response()->json(['error' => 'User already accepted invitation'], 422);
|
||||
}
|
||||
$user->sendInvitation(auth()->user());
|
||||
return response()->json(['invitation_sent' => true]);
|
||||
}
|
||||
|
||||
public function forcePasswordReset(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$user->update(['status' => 'inactive', 'accepted_at' => null]);
|
||||
DB::table('sessions')->where('user_id', $user->id)->delete();
|
||||
$user->sendInvitation(auth()->user());
|
||||
return response()->json(['invitation_sent' => true]);
|
||||
}
|
||||
|
||||
public function sessions(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$rows = DB::table('sessions')->where('user_id', $user->id)
|
||||
->select('id', 'ip_address', 'user_agent', 'last_activity')->get();
|
||||
return response()->json(['data' => $rows]);
|
||||
}
|
||||
|
||||
public function revokeSession(User $user, string $sessionId): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$n = DB::table('sessions')->where('user_id', $user->id)->where('id', $sessionId)->delete();
|
||||
return response()->json(['revoked' => $n > 0]);
|
||||
}
|
||||
|
||||
public function revokeAllSessions(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$n = DB::table('sessions')->where('user_id', $user->id)->delete();
|
||||
return response()->json(['revoked_count' => $n]);
|
||||
}
|
||||
|
||||
public function roles(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_VIEW);
|
||||
return response()->json(['data' => $user->roles->pluck('name')]);
|
||||
}
|
||||
|
||||
public function assignRole(Request $request, User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$data = $request->validate(['role' => 'required|string']);
|
||||
$user->assignRole($data['role']);
|
||||
return response()->json(['data' => $user->roles->pluck('name')]);
|
||||
}
|
||||
|
||||
public function removeRole(User $user, string $role): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$user->removeRole($role);
|
||||
return response()->json(['data' => $user->roles->pluck('name')]);
|
||||
}
|
||||
|
||||
public function permissions(User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_VIEW);
|
||||
// Effective: roles + grants - denies (active only)
|
||||
$rolePerms = $user->getAllPermissions()->pluck('name');
|
||||
$denies = $user->permissionOverrides()
|
||||
->where('mode', 'deny')
|
||||
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))
|
||||
->with('permission')->get()->pluck('permission.name');
|
||||
$grants = $user->permissionOverrides()
|
||||
->where('mode', 'grant')
|
||||
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))
|
||||
->with('permission')->get()->pluck('permission.name');
|
||||
$effective = $rolePerms->merge($grants)->unique()->reject(fn ($p) => $denies->contains($p))->values();
|
||||
return response()->json([
|
||||
'data' => $effective,
|
||||
'overrides' => ['grants' => $grants, 'denies' => $denies],
|
||||
]);
|
||||
}
|
||||
|
||||
public function addOverride(Request $request, User $user): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$data = $request->validate([
|
||||
'permission' => 'required|string',
|
||||
'mode' => 'required|in:grant,deny',
|
||||
'reason' => 'nullable|string',
|
||||
'expires_at' => 'nullable|date',
|
||||
]);
|
||||
$perm = Permission::where('name', $data['permission'])->firstOrFail();
|
||||
UserPermissionOverride::updateOrCreate(
|
||||
['user_id' => $user->id, 'permission_id' => $perm->id],
|
||||
[
|
||||
'mode' => $data['mode'],
|
||||
'reason' => $data['reason'] ?? null,
|
||||
'expires_at' => $data['expires_at'] ?? null,
|
||||
'granted_by_id' => auth()->id(),
|
||||
'granted_at' => now(),
|
||||
]
|
||||
);
|
||||
return response()->json(['data' => $user->load('permissionOverrides.permission')]);
|
||||
}
|
||||
|
||||
public function removeOverride(User $user, string $permission): JsonResponse
|
||||
{
|
||||
$this->authorize(Permissions::ADMIN_USERS_MANAGE);
|
||||
$perm = Permission::where('name', $permission)->firstOrFail();
|
||||
UserPermissionOverride::where('user_id', $user->id)->where('permission_id', $perm->id)->delete();
|
||||
return response()->json(['removed' => true]);
|
||||
}
|
||||
|
||||
private function authorize(string $permission): void
|
||||
{
|
||||
if (! auth()->user() || ! auth()->user()->canDo($permission)) {
|
||||
abort(403, "Missing permission: $permission");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Tenant\User;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class InvitationController extends Controller
|
||||
{
|
||||
public function show(string $token)
|
||||
{
|
||||
$user = User::findByInvitationToken($token);
|
||||
if (! $user || ! $user->isPendingInvitation()) {
|
||||
return view('invitations.invalid');
|
||||
}
|
||||
// Invitations expire after 7 days
|
||||
if ($user->invited_at && $user->invited_at->lt(now()->subDays(7))) {
|
||||
return view('invitations.expired');
|
||||
}
|
||||
|
||||
return view('invitations.accept', [
|
||||
'token' => $token,
|
||||
'name' => $user->name,
|
||||
'email' => $user->email,
|
||||
'company' => $user->company?->display_name ?? $user->company?->name ?? 'AutoCRM',
|
||||
]);
|
||||
}
|
||||
|
||||
public function accept(string $token, Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'password' => 'required|min:8|confirmed',
|
||||
]);
|
||||
|
||||
$user = User::findByInvitationToken($token);
|
||||
if (! $user || ! $user->isPendingInvitation()) {
|
||||
return view('invitations.invalid');
|
||||
}
|
||||
if ($user->invited_at && $user->invited_at->lt(now()->subDays(7))) {
|
||||
return view('invitations.expired');
|
||||
}
|
||||
|
||||
$user->acceptInvitation($request->input('password'));
|
||||
|
||||
// Redirect to tenant login on the appropriate subdomain
|
||||
$loginUrl = $user->company?->url('/app/login') ?? '/app/login';
|
||||
return redirect($loginUrl)->with('status', 'Invitația a fost acceptată. Loghează-te cu noua parolă.');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user