initial commit
This commit is contained in:
commit
3f64f4a49a
221 files changed
+26665
No files matched your search
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Models\ApiToken;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Support\IpAllowlist;
|
||||
|
||||
/**
|
||||
* Ключ API: Authorization: Bearer ptn_xxx_yyy.
|
||||
*
|
||||
* Ключ — такой же вход в данные, как и пароль, поэтому область видимости
|
||||
* действует и здесь: в атрибуты кладётся владелец ключа, его viewer и scope,
|
||||
* и контроллер API работает ровно с теми записями, что и его хозяин в панели.
|
||||
*/
|
||||
final class ApiKey
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
$key = $request->bearerToken();
|
||||
|
||||
if ($key === '') {
|
||||
return Response::error('Не передан ключ доступа: Authorization: Bearer <ключ>', 401);
|
||||
}
|
||||
|
||||
$token = ApiToken::match($key);
|
||||
|
||||
if ($token === null) {
|
||||
return Response::error('Ключ доступа не найден или отключён', 401);
|
||||
}
|
||||
|
||||
$allowed = trim((string) $token->raw('allowed_ips'));
|
||||
|
||||
// Пустой список — ограничения нет; заполненный проверяем целиком,
|
||||
// включая сети CIDR
|
||||
if ($allowed !== '' && !IpAllowlist::allows($allowed, $request->ip())) {
|
||||
return Response::error('Этот ключ нельзя использовать с адреса ' . $request->ip(), 403);
|
||||
}
|
||||
|
||||
$user = User::find((int) $token->raw('user_id'));
|
||||
|
||||
if ($user === null || !$user->isActive()) {
|
||||
return Response::error('Владелец ключа отключён', 403);
|
||||
}
|
||||
|
||||
$token->markUsed($request->ip());
|
||||
|
||||
$viewer = Viewer::fromUser($user);
|
||||
|
||||
$request->setAttribute('token', $token)
|
||||
->setAttribute('user', $user)
|
||||
->setAttribute('viewer', $viewer)
|
||||
->setAttribute('scope', $viewer->scope());
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Install\Installer;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Пускает только вошедших. Заодно кладёт в атрибуты запроса пользователя,
|
||||
* viewer и область видимости — роутер подставит их в контроллер по именам
|
||||
* аргументов, и лезть в сессию из контроллера не придётся.
|
||||
*/
|
||||
final class Authenticate
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
// Приложение ещё не установлено — сначала установщик, а не форма входа
|
||||
if (!Installer::installed()) {
|
||||
return Response::redirect(View::route('install'));
|
||||
}
|
||||
|
||||
$user = Auth::user();
|
||||
|
||||
if ($user === null) {
|
||||
if ($request->wantsJson()) {
|
||||
return Response::error('Нужно войти', 401);
|
||||
}
|
||||
|
||||
// Куда вернуть после входа: человек шёл по ссылке, а не на главную
|
||||
View::stash('intended', $request->fullPath());
|
||||
|
||||
return Response::redirect(View::route('login'));
|
||||
}
|
||||
|
||||
$viewer = Auth::viewer();
|
||||
|
||||
$request->setAttribute('user', $user)
|
||||
->setAttribute('viewer', $viewer)
|
||||
->setAttribute('scope', $viewer->scope());
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Проверка права: can:users.manage. Несколько прав через черту — «хватит любого»:
|
||||
* can:notes.view|notes.manage.
|
||||
*
|
||||
* Ставится прослойкой у группы маршрутов, а не проверкой в контроллере: так
|
||||
* забыть её можно только вместе со всей группой.
|
||||
*/
|
||||
final class Can
|
||||
{
|
||||
public function __invoke(Request $request, callable $next, string $permission = ''): Response
|
||||
{
|
||||
$viewer = Auth::viewer();
|
||||
|
||||
$permissions = array_values(array_filter(explode('|', $permission)));
|
||||
|
||||
if ($permissions === [] || $viewer->canAny($permissions)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if ($request->wantsJson()) {
|
||||
return Response::error('Недостаточно прав', 403);
|
||||
}
|
||||
|
||||
return Response::html(View::render('errors/403', [
|
||||
'message' => 'Этот раздел вам не доступен.',
|
||||
], 'Нет доступа'), 403);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Install\Installer;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Только для не вошедших: форма входа и регистрация. Вошедшего уводим на
|
||||
* главную — показывать ему форму входа незачем.
|
||||
*/
|
||||
final class Guest
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
if (!Installer::installed()) {
|
||||
return Response::redirect(View::route('install'));
|
||||
}
|
||||
|
||||
if (Auth::check()) {
|
||||
return Response::redirect(View::route('home'));
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Install\Installer;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Веб-установщик открыт, только пока приложение не установлено.
|
||||
*
|
||||
* Иначе мастером воспользовался бы любой прохожий: он пишет .env и заводит
|
||||
* администратора.
|
||||
*/
|
||||
final class Install
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
if (Installer::installed()) {
|
||||
return Response::redirect(View::route('home'));
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Models\ApiToken;
|
||||
use Rsgrinko\Proton\RateLimit\RateLimiter;
|
||||
|
||||
/**
|
||||
* Ограничение частоты: throttle:60,60 — не больше 60 запросов за 60 секунд.
|
||||
*
|
||||
* Считаем по ключу API, если он есть, иначе по адресу: иначе один клиент за
|
||||
* общим NAT перекрыл бы кислород всем соседям.
|
||||
*/
|
||||
final class Throttle
|
||||
{
|
||||
public function __invoke(Request $request, callable $next, string $options = '60,60'): Response
|
||||
{
|
||||
[$max, $seconds] = array_pad(explode(',', $options), 2, '60');
|
||||
|
||||
$max = max(1, (int) $max);
|
||||
$seconds = max(1, (int) $seconds);
|
||||
|
||||
$limiter = new RateLimiter();
|
||||
$key = 'throttle:' . $this->subject($request) . ':' . $seconds;
|
||||
|
||||
if (!$limiter->attempt($key, $max, $seconds)) {
|
||||
$retry = $limiter->retryAfter($key);
|
||||
|
||||
return Response::error('Слишком много запросов, попробуйте позже', 429, ['retry_after' => $retry])
|
||||
->withHeader('Retry-After', (string) max(1, $retry));
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
private function subject(Request $request): string
|
||||
{
|
||||
$token = $request->attribute('token');
|
||||
|
||||
if ($token instanceof ApiToken) {
|
||||
return 'token:' . $token->id();
|
||||
}
|
||||
|
||||
return 'ip:' . $request->ip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Csrf;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Сверяет токен формы при любом изменяющем запросе.
|
||||
*
|
||||
* Вешается на группу веб-маршрутов целиком: забыть её на одном контроллере
|
||||
* куда проще, чем на всей группе. API это не касается — там ключ в заголовке,
|
||||
* а не кука, и подделать запрос с чужого сайта нельзя.
|
||||
*/
|
||||
final class VerifyCsrf
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
if (!$request->isWriting()) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$token = (string) $request->input(Csrf::FIELD, $request->header(Csrf::HEADER));
|
||||
|
||||
if (Csrf::check($token)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if ($request->wantsJson()) {
|
||||
return Response::error('Форма устарела, обновите страницу', 403);
|
||||
}
|
||||
|
||||
View::flash('Форма устарела. Обновите страницу и попробуйте ещё раз', 'error');
|
||||
|
||||
return Response::html(View::render('errors/403', [
|
||||
'message' => 'Не сходится токен формы. Обычно это значит, что страница была открыта слишком долго.',
|
||||
], 'Форма устарела'), 403);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user