Просмотр файла app/Controllers/BaseController.php

Размер файла: 2.56Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Controllers;
  6.  
  7. use App\Models\Ban;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Pagination\Paginator;
  10. use Illuminate\Support\Facades\Cache;
  11. use Illuminate\Support\Facades\Lang;
  12. use Illuminate\Support\Facades\View;
  13.  
  14. class BaseController
  15. {
  16. public function __construct()
  17. {
  18. $request = request();
  19.  
  20. if (! $this->isBanned($request)) {
  21. $this->frequencyLimit();
  22.  
  23. // Сайт закрыт для гостей
  24. if (setting('closedsite') === 1 && ! getUser() && ! $request->is('register', 'login', 'recovery', 'captcha')) {
  25. setFlash('danger', __('main.not_authorized'));
  26. redirect('/login');
  27. }
  28.  
  29. // Сайт закрыт для всех
  30. if (setting('closedsite') === 2 && ! isAdmin() && ! $request->is('closed', 'login')) {
  31. redirect('/closed');
  32. }
  33.  
  34. Paginator::$defaultView = 'app/_paginator';
  35.  
  36. [$path, $name] = explode('\\', static::class);
  37.  
  38. if ($path === 'Modules') {
  39. View::addNamespace($name, MODULES . '/' . $name . '/resources/views');
  40. Lang::addNamespace($name, MODULES . '/' . $name . '/resources/lang');
  41. }
  42. }
  43. }
  44.  
  45. /**
  46. * Проверка на ip-бан
  47. *
  48. * @param Request $request
  49. *
  50. * @return bool
  51. */
  52. private function isBanned(Request $request): bool
  53. {
  54. if (! isAdmin() && isset(ipBan()[getIp()])) {
  55. if ($request->is('ipban', 'captcha')) {
  56. return true;
  57. }
  58.  
  59. redirect('/ipban');
  60. }
  61.  
  62. return false;
  63. }
  64.  
  65. /**
  66. * Ограничение частоты запросов
  67. *
  68. * @return void
  69. */
  70. private function frequencyLimit(): void
  71. {
  72. if (setting('doslimit')) {
  73. $key = 'request_' . getIp();
  74. Cache::remember($key, 60, static function () {
  75. return 0;
  76. });
  77.  
  78. $requests = Cache::increment($key);
  79. /* Автоматическая блокировка */
  80. if ($requests > setting('doslimit')) {
  81. $ipban = Ban::query()->where('ip', getIp())->first();
  82.  
  83. if (! $ipban) {
  84. Ban::query()->insertOrIgnore([
  85. 'ip' => getIp(),
  86. 'created_at' => SITETIME,
  87. ]);
  88. }
  89.  
  90. ipBan(true);
  91. saveErrorLog(666);
  92. clearCache($key);
  93. }
  94. }
  95. }
  96. }