Preserva base local aceite de identidade e acessos
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Http;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Modules\Identity\Services\Audit;
|
||||
use App\Modules\Identity\Services\IdentityWorkflow;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class IdentityController extends Controller
|
||||
{
|
||||
public function __construct(private IdentityWorkflow $workflow) {}
|
||||
|
||||
public function session(Request $request)
|
||||
{
|
||||
if ($request->user() && (int) $request->session()->get('auth_version', 0) !== (int) $request->user()->auth_version) {
|
||||
Auth::logout(); $request->session()->invalidate(); $request->session()->regenerateToken();
|
||||
}
|
||||
return response()->json($this->workflow->snapshot($request))->header('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
public function login(Request $request)
|
||||
{
|
||||
$data = $request->validate(['email' => 'required|email|max:255', 'password' => 'required|string|max:1024']);
|
||||
$email = mb_strtolower(trim($data['email']));
|
||||
if (strlen($data['password']) > 72) { throw ValidationException::withMessages(['email' => 'Email ou palavra-passe inválidos.']); }
|
||||
$key = 'sgf-login:'.hash('sha256', $email.'|'.$request->ip());
|
||||
$ipKey = 'sgf-login-ip:'.hash('sha256', (string) $request->ip());
|
||||
abort_if(RateLimiter::tooManyAttempts($key, config('identity.login_attempts')) || RateLimiter::tooManyAttempts($ipKey, config('identity.login_ip_attempts')), 429, 'Demasiadas tentativas. Aguarde antes de tentar novamente.');
|
||||
if (! Auth::attempt(['email' => $email, 'password' => $data['password']], false)) {
|
||||
RateLimiter::hit($key, config('identity.login_decay_seconds'));
|
||||
RateLimiter::hit($ipKey, config('identity.login_decay_seconds'));
|
||||
Audit::record('auth.failed', null);
|
||||
throw ValidationException::withMessages(['email' => 'Email ou palavra-passe inválidos.']);
|
||||
}
|
||||
RateLimiter::clear($key);
|
||||
$request->session()->regenerate();
|
||||
$request->session()->forget('company_context');
|
||||
$request->session()->put('auth_version', (int) $request->user()->auth_version);
|
||||
Audit::record('auth.login', $request->user()->id);
|
||||
return $this->session($request);
|
||||
}
|
||||
|
||||
public function logout(Request $request)
|
||||
{
|
||||
Audit::record('auth.logout', $request->user()->id);
|
||||
Auth::logout(); $request->session()->invalidate(); $request->session()->regenerateToken();
|
||||
return response()->json(['csrf' => csrf_token()])->header('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
public function select(Request $request) { return response()->json($this->workflow->select($request)); }
|
||||
public function company(Request $request, int $company)
|
||||
{
|
||||
$ids = app(\App\Shared\Context\CompanyContext::class)->identifiers();
|
||||
abort_unless($company === $ids['company_id'], 403);
|
||||
return response()->json(\Illuminate\Support\Facades\DB::table('companies')->where('id', $company)->where('tenant_id', $ids['tenant_id'])->first(['id', 'name']));
|
||||
}
|
||||
public function unit(Request $request, int $unit)
|
||||
{
|
||||
$ids = app(\App\Shared\Context\CompanyContext::class)->identifiers();
|
||||
app(\App\Modules\Identity\Services\Permissions::class)->require($request->user()->id, $ids['tenant_id'], $ids['company_id'], 'unit.view', $unit);
|
||||
$record = \Illuminate\Support\Facades\DB::table('units')->where('id', $unit)->where('company_id', $ids['company_id'])->where('tenant_id', $ids['tenant_id'])->first(['id', 'name']);
|
||||
abort_unless($record, 403);
|
||||
return response()->json($record);
|
||||
}
|
||||
public function renameCompany(Request $request, int $company) { $this->workflow->renameCompany($request, $company); return response()->json(['ok' => true]); }
|
||||
public function renameUnit(Request $request, int $unit) { $this->workflow->renameUnit($request, $unit); return response()->json(['ok' => true]); }
|
||||
public function createUnit(Request $request) { return response()->json(['id' => $this->workflow->createUnit($request)], 201); }
|
||||
public function accesses(Request $request) { return response()->json($this->workflow->accessList($request)); }
|
||||
public function grant(Request $request) { $this->workflow->changeAccess($request, true); return response()->json(['ok' => true]); }
|
||||
public function revoke(Request $request) { $this->workflow->changeAccess($request, false); return response()->json(['ok' => true]); }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Http;
|
||||
|
||||
use App\Shared\Context\CompanyContext;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class RequireCompanyContext
|
||||
{
|
||||
public function __construct(private CompanyContext $context) {}
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$this->context->clear();
|
||||
try {
|
||||
$selection = $request->session()->get('company_context', []);
|
||||
$tenant = $selection['tenant_id'] ?? null;
|
||||
$company = $selection['company_id'] ?? null;
|
||||
abort_unless($request->user() && $tenant && $company, 403, 'Contexto de empresa obrigatório.');
|
||||
$this->context->selectFor((int) $request->user()->getKey(), $tenant, $company, $selection['unit_id'] ?? null);
|
||||
if (! $request->isMethodSafe()) {
|
||||
$token = $request->header('X-SGF-Context');
|
||||
abort_unless(is_string($token) && hash_equals($selection['token'] ?? '', $token), 409, 'O contexto mudou. Reabra o formulário antes de guardar.');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
} finally {
|
||||
$this->context->clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Http;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
final class RequireValidSession
|
||||
{
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
abort_unless($request->user(), 401);
|
||||
if ((int) $request->session()->get('auth_version', 0) !== (int) $request->user()->auth_version) {
|
||||
auth()->logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
abort(401, 'Sessão terminada. Entre novamente.');
|
||||
}
|
||||
$response = $next($request);
|
||||
$response->headers->set('Cache-Control', 'no-store');
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
// Identity catalogue; company selection is authorized by CompanyContext.
|
||||
final class Company extends Model
|
||||
{
|
||||
protected $fillable = ['tenant_id', 'name'];
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
final class Tenant extends Model
|
||||
{
|
||||
protected $fillable = ['name'];
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Models;
|
||||
|
||||
use App\Shared\Context\BelongsToCompany;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
final class Unit extends Model
|
||||
{
|
||||
use BelongsToCompany;
|
||||
|
||||
protected $fillable = ['name'];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::addGlobalScope('unit-access', function (\Illuminate\Database\Eloquent\Builder $query): void {
|
||||
$query->whereIn('units.id', app(\App\Shared\Context\CompanyContext::class)->permittedUnitIds());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class Audit
|
||||
{
|
||||
public static function record(string $action, ?int $actor, ?int $tenant = null, ?int $company = null, ?int $unit = null, ?int $subject = null, array $details = []): void
|
||||
{
|
||||
// Explicit allowlist: credentials, session/context tokens and request bodies never enter audit.
|
||||
$safe = array_intersect_key($details, array_flip(['before_name', 'after_name', 'permission', 'reason', 'operator', 'grants']));
|
||||
DB::table('identity_audit')->insert([
|
||||
'action' => $action, 'actor_id' => $actor, 'tenant_id' => $tenant,
|
||||
'company_id' => $company, 'unit_id' => $unit, 'subject_id' => $subject,
|
||||
'details' => json_encode($safe, JSON_THROW_ON_ERROR), 'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Shared\Context\CompanyContext;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class IdentityWorkflow
|
||||
{
|
||||
public function __construct(private Permissions $permissions, private CompanyContext $context) {}
|
||||
|
||||
public function companies(int $user): array
|
||||
{
|
||||
return DB::table('companies as c')->join('permission_grants as g', 'g.company_id', '=', 'c.id')
|
||||
->where('g.user_id', $user)->where('g.permission', 'company.view')->whereNull('g.unit_id')
|
||||
->select('c.id', 'c.tenant_id', 'c.name')->orderBy('c.name')->get()->all();
|
||||
}
|
||||
|
||||
public function units(int $user, int $tenant, int $company): array
|
||||
{
|
||||
return DB::table('units')->where('tenant_id', $tenant)->where('company_id', $company)
|
||||
->whereIn('id', $this->permissions->unitIds($user, $tenant, $company))
|
||||
->select('id', 'name')->orderBy('name')->get()->all();
|
||||
}
|
||||
|
||||
public function snapshot(Request $request): array
|
||||
{
|
||||
$user = $request->user();
|
||||
$result = ['user' => $user ? ['id' => $user->id, 'name' => $user->name, 'email' => $user->email] : null,
|
||||
'csrf' => csrf_token(), 'companies' => [], 'context' => null,
|
||||
'setup_pending' => app()->environment('local') && ! DB::table('users')->exists()];
|
||||
if (! $user) { return $result; }
|
||||
$result['companies'] = $this->companies($user->id);
|
||||
$selected = $request->session()->get('company_context');
|
||||
if (! $selected) { return $result; }
|
||||
try {
|
||||
$this->context->selectFor($user->id, $selected['tenant_id'], $selected['company_id'], $selected['unit_id']);
|
||||
$company = DB::table('companies')->where('id', $selected['company_id'])->first(['id', 'name', 'tenant_id']);
|
||||
$unit = $selected['unit_id'] ? DB::table('units')->where('id', $selected['unit_id'])->first(['id', 'name']) : null;
|
||||
$grants = DB::table('permission_grants')->where('user_id', $user->id)->where('company_id', $company->id)
|
||||
->get(['permission', 'unit_id'])->map(fn ($grant) => ['permission' => $grant->permission, 'unit_id' => $grant->unit_id ? (int) $grant->unit_id : null])->all();
|
||||
$result['context'] = ['company' => $company, 'unit' => $unit, 'units' => $this->units($user->id, $company->tenant_id, $company->id),
|
||||
'token' => $selected['token'], 'grants' => $grants];
|
||||
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $exception) {
|
||||
if ($exception->getStatusCode() !== 403) { throw $exception; }
|
||||
$request->session()->forget('company_context');
|
||||
$result['notice'] = 'O acesso ao contexto anterior mudou. Seleccione um contexto autorizado.';
|
||||
} finally { $this->context->clear(); }
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function select(Request $request): array
|
||||
{
|
||||
$data = $request->validate(['tenant_id' => 'required|integer|min:1', 'company_id' => 'required|integer|min:1', 'unit_id' => 'nullable|integer|min:1']);
|
||||
$unit = isset($data['unit_id']) ? (int) $data['unit_id'] : null;
|
||||
// Selection is explicit, never silently carries the old unit into another company.
|
||||
$this->context->selectFor($request->user()->id, (int) $data['tenant_id'], (int) $data['company_id'], $unit);
|
||||
$request->session()->put('company_context', ['tenant_id' => (int) $data['tenant_id'], 'company_id' => (int) $data['company_id'],
|
||||
'unit_id' => $unit, 'token' => bin2hex(random_bytes(24))]);
|
||||
Audit::record('context.selected', $request->user()->id, (int) $data['tenant_id'], (int) $data['company_id'], $unit);
|
||||
return $this->snapshot($request);
|
||||
}
|
||||
|
||||
public function renameCompany(Request $request, int $company): void
|
||||
{
|
||||
$data = $request->validate(['name' => 'required|string|max:255', 'tenant_id' => 'prohibited', 'company_id' => 'prohibited', 'unit_id' => 'prohibited', 'id' => 'prohibited']);
|
||||
$this->mutate($request, function ($ids, $user) use ($company, $data): void {
|
||||
abort_unless($company === $ids['company_id'], 403);
|
||||
$this->permissions->require($user, $ids['tenant_id'], $company, 'company.edit');
|
||||
$before = DB::table('companies')->where('id', $company)->value('name');
|
||||
DB::table('companies')->where('id', $company)->update(['name' => trim($data['name']), 'updated_at' => now()]);
|
||||
Audit::record('company.renamed', $user, $ids['tenant_id'], $company, details: ['before_name' => $before, 'after_name' => trim($data['name'])]);
|
||||
});
|
||||
}
|
||||
|
||||
public function renameUnit(Request $request, int $unit): void
|
||||
{
|
||||
$data = $request->validate(['name' => 'required|string|max:255', 'tenant_id' => 'prohibited', 'company_id' => 'prohibited', 'unit_id' => 'prohibited', 'id' => 'prohibited']);
|
||||
$this->mutate($request, function ($ids, $user) use ($unit, $data): void {
|
||||
abort_unless($this->context->unitId() === $unit, 409, 'Seleccione esta unidade antes de editar.');
|
||||
$this->permissions->require($user, $ids['tenant_id'], $ids['company_id'], 'unit.edit', $unit);
|
||||
$before = DB::table('units')->where('id', $unit)->where('company_id', $ids['company_id'])->value('name');
|
||||
abort_if($before === null, 403);
|
||||
DB::table('units')->where('id', $unit)->where('company_id', $ids['company_id'])->update(['name' => trim($data['name']), 'updated_at' => now()]);
|
||||
Audit::record('unit.renamed', $user, $ids['tenant_id'], $ids['company_id'], $unit, details: ['before_name' => $before, 'after_name' => trim($data['name'])]);
|
||||
});
|
||||
}
|
||||
|
||||
public function createUnit(Request $request): int
|
||||
{
|
||||
$data = $request->validate(['name' => 'required|string|max:255', 'tenant_id' => 'prohibited', 'company_id' => 'prohibited', 'unit_id' => 'prohibited', 'id' => 'prohibited']);
|
||||
return $this->mutate($request, function ($ids, $user) use ($data): int {
|
||||
$this->permissions->require($user, $ids['tenant_id'], $ids['company_id'], 'unit.create');
|
||||
$unit = DB::table('units')->insertGetId($ids + ['name' => trim($data['name']), 'created_at' => now(), 'updated_at' => now()]);
|
||||
Audit::record('unit.created', $user, $ids['tenant_id'], $ids['company_id'], $unit, details: ['after_name' => trim($data['name'])]);
|
||||
foreach (Permissions::UNIT as $permission) {
|
||||
$this->insertGrant($user, $ids, $unit, $permission);
|
||||
Audit::record('access.granted_on_creation', $user, $ids['tenant_id'], $ids['company_id'], $unit, $user, ['permission' => $permission]);
|
||||
}
|
||||
return $unit;
|
||||
});
|
||||
}
|
||||
|
||||
public function accessList(Request $request): array
|
||||
{
|
||||
$ids = $this->context->identifiers();
|
||||
$this->permissions->require($request->user()->id, $ids['tenant_id'], $ids['company_id'], 'access.manage');
|
||||
$allowedUnits = $this->context->permittedUnitIds();
|
||||
$members = DB::table('company_memberships as m')->join('users as u', 'u.id', '=', 'm.user_id')
|
||||
->where('m.tenant_id', $ids['tenant_id'])->where('m.company_id', $ids['company_id'])->select('u.id', 'u.name', 'u.email')->orderBy('u.name')->get();
|
||||
$grants = DB::table('permission_grants')->where('tenant_id', $ids['tenant_id'])->where('company_id', $ids['company_id'])
|
||||
->where(fn ($q) => $q->whereNull('unit_id')->orWhereIn('unit_id', $allowedUnits))->get(['id', 'user_id', 'unit_id', 'permission']);
|
||||
return ['members' => $members, 'grants' => $grants, 'catalogue' => ['company' => Permissions::COMPANY, 'unit' => Permissions::UNIT]];
|
||||
}
|
||||
|
||||
public function changeAccess(Request $request, bool $grant): void
|
||||
{
|
||||
$data = $request->validate(['email' => 'required|email|max:255', 'permission' => 'required|string', 'unit_id' => 'nullable|integer|min:1',
|
||||
'reason' => 'required|string|max:500', 'tenant_id' => 'prohibited', 'company_id' => 'prohibited', 'user_id' => 'prohibited']);
|
||||
$this->mutate($request, function ($ids, $actor) use ($data, $grant): void {
|
||||
$company = $ids['company_id']; $tenant = $ids['tenant_id'];
|
||||
$this->permissions->require($actor, $tenant, $company, 'access.manage');
|
||||
$unit = isset($data['unit_id']) ? (int) $data['unit_id'] : null;
|
||||
$catalogue = $unit === null ? Permissions::COMPANY : Permissions::UNIT;
|
||||
abort_unless(in_array($data['permission'], $catalogue, true), 422, 'Permissão ou âmbito inválido.');
|
||||
$this->permissions->require($actor, $tenant, $company, $data['permission'], $unit);
|
||||
if ($unit !== null) {
|
||||
$this->permissions->require($actor, $tenant, $company, 'unit.view', $unit);
|
||||
abort_unless(DB::table('units')->where('id', $unit)->where('tenant_id', $tenant)->where('company_id', $company)->exists(), 403);
|
||||
}
|
||||
$target = User::query()->where('email', mb_strtolower($data['email']))->first();
|
||||
if (! $target) { throw ValidationException::withMessages(['email' => 'Não foi possível atribuir este acesso. Confirme o utilizador pelo procedimento local.']); }
|
||||
$membership = DB::table('company_memberships')->where($ids)->where('user_id', $target->id);
|
||||
if (! $membership->exists()) {
|
||||
abort_unless($grant && $data['permission'] === 'company.view' && $unit === null, 403, 'Conceda primeiro consulta da empresa.');
|
||||
DB::table('company_memberships')->insert($ids + ['user_id' => $target->id]);
|
||||
}
|
||||
if ($grant && $data['permission'] !== 'company.view') {
|
||||
$this->permissions->require($target->id, $tenant, $company, 'company.view');
|
||||
if ($unit && $data['permission'] === 'unit.edit') { $this->permissions->require($target->id, $tenant, $company, 'unit.view', $unit); }
|
||||
}
|
||||
$removed = [];
|
||||
if ($grant) { $this->insertGrant($target->id, $ids, $unit, $data['permission']); }
|
||||
else {
|
||||
$query = DB::table('permission_grants')->where($ids)->where('user_id', $target->id);
|
||||
if ($data['permission'] === 'company.view') {
|
||||
// Revocation deactivates all derived grants; reject partial authority rather than silently exceeding it.
|
||||
foreach ($query->get() as $existing) { $this->permissions->require($actor, $tenant, $company, $existing->permission, $existing->unit_id ? (int) $existing->unit_id : null); }
|
||||
$removed = $query->get(['permission', 'unit_id'])->map(fn ($row) => (array) $row)->all();
|
||||
$query->delete();
|
||||
} else {
|
||||
if ($data['permission'] === 'unit.view') {
|
||||
if ($this->permissions->has($target->id, $tenant, $company, 'unit.edit', $unit)) { $this->permissions->require($actor, $tenant, $company, 'unit.edit', $unit); }
|
||||
$query->where('unit_id', $unit)->whereIn('permission', Permissions::UNIT);
|
||||
} else { $query->where('unit_id', $unit)->where('permission', $data['permission']); }
|
||||
$removed = $query->get(['permission', 'unit_id'])->map(fn ($row) => (array) $row)->all();
|
||||
$query->delete();
|
||||
}
|
||||
}
|
||||
Audit::record($grant ? 'access.granted' : 'access.revoked', $actor, $tenant, $company, $unit, $target->id,
|
||||
['permission' => $data['permission'], 'reason' => $data['reason'], 'grants' => $grant ? [['permission' => $data['permission'], 'unit_id' => $unit]] : $removed]);
|
||||
});
|
||||
}
|
||||
|
||||
private function insertGrant(int $user, array $ids, ?int $unit, string $permission): void
|
||||
{
|
||||
DB::table('permission_grants')->insertOrIgnore($ids + ['user_id' => $user, 'unit_id' => $unit, 'permission' => $permission, 'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
|
||||
private function mutate(Request $request, callable $operation): mixed
|
||||
{
|
||||
$selected = $this->context->identifiers();
|
||||
return DB::transaction(function () use ($request, $operation, $selected) {
|
||||
// All access changes and business mutations serialize on the same company row.
|
||||
DB::table('companies')->where('id', $selected['company_id'])->where('tenant_id', $selected['tenant_id'])->lockForUpdate()->firstOrFail();
|
||||
$this->context->selectFor($request->user()->id, $selected['tenant_id'], $selected['company_id'], $this->context->unitId());
|
||||
return $operation($selected, $request->user()->id);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class LocalDatabaseGuard
|
||||
{
|
||||
public static function allows(): bool
|
||||
{
|
||||
if (! app()->environment('local')) { return false; }
|
||||
$connection = config('database.default');
|
||||
$config = config("database.connections.$connection", []);
|
||||
foreach (['driver' => 'pgsql', 'host' => '127.0.0.1', 'port' => '55432', 'database' => 'sgf_tempo_dev', 'username' => 'sgf_dev_app'] as $key => $expected) {
|
||||
if ((string) ($config[$key] ?? '') !== $expected) { return false; }
|
||||
}
|
||||
if (! empty($config['url']) || ! empty($config['read']) || ! empty($config['write'])) { return false; }
|
||||
try {
|
||||
$identity = DB::selectOne('SELECT current_database() AS db, current_user AS role, rolsuper, rolcreatedb, rolcreaterole, rolbypassrls FROM pg_roles WHERE rolname = current_user');
|
||||
return $identity->db === 'sgf_tempo_dev' && $identity->role === 'sgf_dev_app'
|
||||
&& ! $identity->rolsuper && ! $identity->rolcreatedb && ! $identity->rolcreaterole && ! $identity->rolbypassrls;
|
||||
} catch (\Throwable) { return false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class Permissions
|
||||
{
|
||||
public const COMPANY = ['company.view', 'company.edit', 'unit.create', 'access.manage'];
|
||||
public const UNIT = ['unit.view', 'unit.edit'];
|
||||
|
||||
public function has(int $user, int $tenant, int $company, string $permission, ?int $unit = null): bool
|
||||
{
|
||||
return DB::table('permission_grants')->where('user_id', $user)->where('tenant_id', $tenant)
|
||||
->where('company_id', $company)->where('permission', $permission)->where('unit_id', $unit)->exists();
|
||||
}
|
||||
|
||||
public function require(int $user, int $tenant, int $company, string $permission, ?int $unit = null): void
|
||||
{
|
||||
abort_unless($this->has($user, $tenant, $company, $permission, $unit), 403, 'Acção não autorizada.');
|
||||
}
|
||||
|
||||
public function unitIds(int $user, int $tenant, int $company): array
|
||||
{
|
||||
return DB::table('permission_grants')->where('user_id', $user)->where('tenant_id', $tenant)
|
||||
->where('company_id', $company)->where('permission', 'unit.view')->pluck('unit_id')->map(fn ($id) => (int) $id)->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Identity\Services;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
final class ProtectedProvisioningInput
|
||||
{
|
||||
public static function read($stream, string $email): array
|
||||
{
|
||||
try {
|
||||
$raw = stream_get_contents($stream, 16385);
|
||||
if (! is_string($raw) || strlen($raw) > 16384) { throw new RuntimeException(); }
|
||||
$data = json_decode($raw, true, 16, JSON_THROW_ON_ERROR);
|
||||
if (! is_array($data) || ($data['confirmed'] ?? null) !== true || ($data['email'] ?? null) !== $email
|
||||
|| ! is_string($data['password'] ?? null) || ! is_string($data['confirmation'] ?? null)) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
return [$data['password'], $data['confirmation']];
|
||||
} catch (\Throwable) {
|
||||
// Never include payload, parser errors, credentials or tokens in diagnostics.
|
||||
throw new RuntimeException('Entrada protegida inválida ou não confirmada. Nada alterado.');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user