Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7c894471e5 | |||
| d2fc561c03 | |||
| 9d940dd1b9 | |||
| 2dc250669e | |||
| 2cc49234e4 | |||
| 38db78573c | |||
| 48409575a9 |
+1
-1
@@ -14,5 +14,5 @@ trim_trailing_whitespace = false
|
|||||||
[*.{yml,yaml}]
|
[*.{yml,yaml}]
|
||||||
indent_size = 2
|
indent_size = 2
|
||||||
|
|
||||||
[docker-compose.yml]
|
[compose.yaml]
|
||||||
indent_size = 4
|
indent_size = 4
|
||||||
|
|||||||
+34
-28
@@ -4,36 +4,55 @@ APP_KEY=
|
|||||||
APP_DEBUG=true
|
APP_DEBUG=true
|
||||||
APP_URL=http://localhost
|
APP_URL=http://localhost
|
||||||
|
|
||||||
|
APP_LOCALE=en
|
||||||
|
APP_FALLBACK_LOCALE=en
|
||||||
|
APP_FAKER_LOCALE=en_US
|
||||||
|
|
||||||
|
APP_MAINTENANCE_DRIVER=file
|
||||||
|
# APP_MAINTENANCE_STORE=database
|
||||||
|
|
||||||
|
# PHP_CLI_SERVER_WORKERS=4
|
||||||
|
|
||||||
|
BCRYPT_ROUNDS=12
|
||||||
|
|
||||||
LOG_CHANNEL=stack
|
LOG_CHANNEL=stack
|
||||||
|
LOG_STACK=single
|
||||||
LOG_DEPRECATIONS_CHANNEL=null
|
LOG_DEPRECATIONS_CHANNEL=null
|
||||||
LOG_LEVEL=debug
|
LOG_LEVEL=debug
|
||||||
|
|
||||||
DB_CONNECTION=mysql
|
DB_CONNECTION=sqlite
|
||||||
DB_HOST=127.0.0.1
|
# DB_HOST=127.0.0.1
|
||||||
DB_PORT=3306
|
# DB_PORT=3306
|
||||||
DB_DATABASE=laravel
|
# DB_DATABASE=laravel
|
||||||
DB_USERNAME=root
|
# DB_USERNAME=root
|
||||||
DB_PASSWORD=
|
# DB_PASSWORD=
|
||||||
|
|
||||||
BROADCAST_DRIVER=log
|
SESSION_DRIVER=database
|
||||||
CACHE_DRIVER=file
|
|
||||||
FILESYSTEM_DISK=local
|
|
||||||
QUEUE_CONNECTION=sync
|
|
||||||
SESSION_DRIVER=file
|
|
||||||
SESSION_LIFETIME=120
|
SESSION_LIFETIME=120
|
||||||
|
SESSION_ENCRYPT=false
|
||||||
|
SESSION_PATH=/
|
||||||
|
SESSION_DOMAIN=null
|
||||||
|
|
||||||
|
BROADCAST_CONNECTION=log
|
||||||
|
FILESYSTEM_DISK=local
|
||||||
|
QUEUE_CONNECTION=database
|
||||||
|
|
||||||
|
CACHE_STORE=database
|
||||||
|
# CACHE_PREFIX=
|
||||||
|
|
||||||
MEMCACHED_HOST=127.0.0.1
|
MEMCACHED_HOST=127.0.0.1
|
||||||
|
|
||||||
|
REDIS_CLIENT=phpredis
|
||||||
REDIS_HOST=127.0.0.1
|
REDIS_HOST=127.0.0.1
|
||||||
REDIS_PASSWORD=null
|
REDIS_PASSWORD=null
|
||||||
REDIS_PORT=6379
|
REDIS_PORT=6379
|
||||||
|
|
||||||
MAIL_MAILER=smtp
|
MAIL_MAILER=log
|
||||||
MAIL_HOST=mailpit
|
MAIL_SCHEME=null
|
||||||
MAIL_PORT=1025
|
MAIL_HOST=127.0.0.1
|
||||||
|
MAIL_PORT=2525
|
||||||
MAIL_USERNAME=null
|
MAIL_USERNAME=null
|
||||||
MAIL_PASSWORD=null
|
MAIL_PASSWORD=null
|
||||||
MAIL_ENCRYPTION=null
|
|
||||||
MAIL_FROM_ADDRESS="hello@example.com"
|
MAIL_FROM_ADDRESS="hello@example.com"
|
||||||
MAIL_FROM_NAME="${APP_NAME}"
|
MAIL_FROM_NAME="${APP_NAME}"
|
||||||
|
|
||||||
@@ -43,17 +62,4 @@ AWS_DEFAULT_REGION=us-east-1
|
|||||||
AWS_BUCKET=
|
AWS_BUCKET=
|
||||||
AWS_USE_PATH_STYLE_ENDPOINT=false
|
AWS_USE_PATH_STYLE_ENDPOINT=false
|
||||||
|
|
||||||
PUSHER_APP_ID=
|
|
||||||
PUSHER_APP_KEY=
|
|
||||||
PUSHER_APP_SECRET=
|
|
||||||
PUSHER_HOST=
|
|
||||||
PUSHER_PORT=443
|
|
||||||
PUSHER_SCHEME=https
|
|
||||||
PUSHER_APP_CLUSTER=mt1
|
|
||||||
|
|
||||||
VITE_APP_NAME="${APP_NAME}"
|
VITE_APP_NAME="${APP_NAME}"
|
||||||
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
|
|
||||||
VITE_PUSHER_HOST="${PUSHER_HOST}"
|
|
||||||
VITE_PUSHER_PORT="${PUSHER_PORT}"
|
|
||||||
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
|
|
||||||
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
|
|
||||||
|
|||||||
+15
-10
@@ -1,19 +1,24 @@
|
|||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
.env
|
||||||
|
.env.backup
|
||||||
|
.env.production
|
||||||
|
.phpactor.json
|
||||||
|
.phpunit.result.cache
|
||||||
|
/.fleet
|
||||||
|
/.idea
|
||||||
|
/.nova
|
||||||
/.phpunit.cache
|
/.phpunit.cache
|
||||||
|
/.vscode
|
||||||
|
/.zed
|
||||||
|
/auth.json
|
||||||
/node_modules
|
/node_modules
|
||||||
/public/build
|
/public/build
|
||||||
/public/hot
|
/public/hot
|
||||||
/public/storage
|
/public/storage
|
||||||
/storage/*.key
|
/storage/*.key
|
||||||
|
/storage/pail
|
||||||
/vendor
|
/vendor
|
||||||
.env
|
|
||||||
.env.backup
|
|
||||||
.env.production
|
|
||||||
.phpunit.result.cache
|
|
||||||
Homestead.json
|
Homestead.json
|
||||||
Homestead.yaml
|
Homestead.yaml
|
||||||
auth.json
|
Thumbs.db
|
||||||
npm-debug.log
|
|
||||||
yarn-error.log
|
|
||||||
/.fleet
|
|
||||||
/.idea
|
|
||||||
/.vscode
|
|
||||||
|
|||||||
@@ -39,8 +39,7 @@ class TaxiController extends Controller
|
|||||||
* @param TaxiMailerService $sendMailService сервис отправки писем
|
* @param TaxiMailerService $sendMailService сервис отправки писем
|
||||||
* @param TaxiOrderService $orderService сервис работы с заказами
|
* @param TaxiOrderService $orderService сервис работы с заказами
|
||||||
*/
|
*/
|
||||||
public function __construct(protected TaxiMailerService $sendMailService, protected TaxiOrderService $orderService) {
|
public function __construct(protected TaxiMailerService $sendMailService, protected TaxiOrderService $orderService) {}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -79,7 +78,7 @@ class TaxiController extends Controller
|
|||||||
$todaydate = new DateTime();
|
$todaydate = new DateTime();
|
||||||
$todaydate->setTime(00, 00, 00);
|
$todaydate->setTime(00, 00, 00);
|
||||||
$todaydate = $todaydate->format('Y-m-d');
|
$todaydate = $todaydate->format('Y-m-d');
|
||||||
$orders = TaxiModels\TaxiMain::where('taxi_date', '>=', $todaydate)
|
$orders = TaxiModels\TaxiMain::where('taxi_date', '>=', $todayFdate)
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
return $orders;
|
return $orders;
|
||||||
@@ -138,20 +137,24 @@ class TaxiController extends Controller
|
|||||||
// //ЗДЕСЬ НЕПОНЯТНО ОТКУДА ВЗЯТЬ ЗНАЧЕНИЕ. ОБРАТИТЬСЯ К ЛОКАЛЬНО МОДУЛЬНОМУ ENV?
|
// //ЗДЕСЬ НЕПОНЯТНО ОТКУДА ВЗЯТЬ ЗНАЧЕНИЕ. ОБРАТИТЬСЯ К ЛОКАЛЬНО МОДУЛЬНОМУ ENV?
|
||||||
// config('taxi.name_ru'),
|
// config('taxi.name_ru'),
|
||||||
// ));
|
// ));
|
||||||
return response()->json( ['message' => "Заявка успешно создана. Номер заявки $newOrderId"] );
|
return response()->json(['message' => "Заявка успешно создана. Номер заявки $newOrderId"]);
|
||||||
} catch (\Throwable $t) {
|
} catch (\Throwable $t) {
|
||||||
#Гаврилов
|
#Гаврилов
|
||||||
//ОТПРАВКА СООБЩЕНИЯ С ОШИБКОЙ. ЗАТЕСТИ и отправляй response
|
//ОТПРАВКА СООБЩЕНИЯ С ОШИБКОЙ. ЗАТЕСТИ и отправляй response
|
||||||
//ОШИБКИ $T->GETmESSAGE НУЖНО ЛОГИРОВАТЬ, НО ПОЛЬЗОВАТЕЛЯМ ВЫВОДИТЬ ПРОСТО СООБЩЕНИЕ оШИБКА, ИНАЧЕ ОНИ ВИДЯТ ТЕХН ЧЕСКИЙ ТЕКСТ
|
//ОШИБКИ $T->GETmESSAGE НУЖНО ЛОГИРОВАТЬ, НО ПОЛЬЗОВАТЕЛЯМ ВЫВОДИТЬ ПРОСТО СООБЩЕНИЕ "оШИБКА", ИНАЧЕ ОНИ ВИДЯТ ТЕХНиЧЕСКИЙ ТЕКСТ
|
||||||
//СНАЧАЛА ПЕРЕХВАТЫЙ EXCEPTION, ПОТОМ УЖЕ THOWBLE. EXCEPTION ВЫВОДИ ПОЛЬЗОВАТЕЛЮ, THORWBLE ЛОГИРУЙ ОТДЕЛЬНО
|
//СНАЧАЛА ПЕРЕХВАТЫЙ EXCEPTION, ПОТОМ УЖЕ THOWBLE. ТЕКСТ ИЗ EXCEPTION ВЫВОДИ ПОЛЬЗОВАТЕЛЮ - ТАМ КАСТОМНЫЕ ТЕКСТ ОШИБКИ, А ТЕКСТ ИЗ THORWBLE ЛОГИРУЙ ОТДЕЛЬНО, ТАК КАК ТАМ ТЕХНИЧЕСКОЕ ОПИСАНИЕ ОШИБКИ
|
||||||
echo '<pre>'; var_dump($t->getMessage()); echo'</pre>';
|
echo '<pre>';
|
||||||
echo '<pre>'; var_dump($t->getTrace()); echo'</pre>';
|
var_dump($t->getMessage());
|
||||||
|
echo '</pre>';
|
||||||
|
echo '<pre>';
|
||||||
|
var_dump($t->getTrace());
|
||||||
|
echo '</pre>';
|
||||||
$createRqstMsg = "Ошибка!" . $t->getMessage() . ". Заявка не создана";
|
$createRqstMsg = "Ошибка!" . $t->getMessage() . ". Заявка не создана";
|
||||||
return response()->json(['message' => $createRqstMsg], 400);
|
return response()->json(['message' => $createRqstMsg], 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
//ГАВРИЛОВ
|
//ГАВРИЛОВ
|
||||||
//ДОБАВЬ ФОРМИРОВАНИЕ ОТВЕТА ЧЕРЕЗ ГЕНЕРАЦИЮ РЕСУРСА, а не через response()
|
//ДОБАВЬ ФОРМИРОВАНИЕ ОТВЕТА ЧЕРЕЗ ApiResponder, а не через response()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -292,8 +295,6 @@ class TaxiController extends Controller
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
DB::beginTransaction();
|
DB::beginTransaction();
|
||||||
#Гаврилов
|
|
||||||
//ЕЩЕ РАЗ, ЧТО ЗА LOCKFORUPDATE
|
|
||||||
$orderData = TaxiModels\TaxiMain::lockForUpdate()->find($rqst->id);
|
$orderData = TaxiModels\TaxiMain::lockForUpdate()->find($rqst->id);
|
||||||
$oldOrderData = TaxiModels\TaxiMain::find($rqst->id);
|
$oldOrderData = TaxiModels\TaxiMain::find($rqst->id);
|
||||||
|
|
||||||
@@ -309,7 +310,7 @@ class TaxiController extends Controller
|
|||||||
throw new Exception("Нельзя менять заявки, дата которых уже прошла");
|
throw new Exception("Нельзя менять заявки, дата которых уже прошла");
|
||||||
// return response()->json(['message' => 'Нельзя менять заявки, дата которых уже прошла'], 400);
|
// return response()->json(['message' => 'Нельзя менять заявки, дата которых уже прошла'], 400);
|
||||||
}
|
}
|
||||||
foreach($editOrderData as $fieldName => $fieldVal) {
|
foreach ($editOrderData as $fieldName => $fieldVal) {
|
||||||
if (isset($orderData->$fieldName)) {
|
if (isset($orderData->$fieldName)) {
|
||||||
$orderData[$fieldName] = $fieldVal;
|
$orderData[$fieldName] = $fieldVal;
|
||||||
}
|
}
|
||||||
@@ -343,7 +344,7 @@ class TaxiController extends Controller
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
//ГАВРИЛОВ. убрать поле Запрос актуален? и при отмене заявки убирать ее из таблицы Активные заявки
|
//ГАВРИЛОВ. убрать поле Запрос актуален? и при отмене заявки убирать ее из таблицы Активные заявки?
|
||||||
|
|
||||||
//гаврилов. СДЕЛАТЬ ВОЗМОЖНОСТЬ ВЫГРУЗИТЬ В ОТЧЕТНОСТЬ ВСЕ ИМЕЮЩИЕСЯ ЗАЯВКИ В CSV ФАЙЛ.
|
//гаврилов. СДЕЛАТЬ ВОЗМОЖНОСТЬ ВЫГРУЗИТЬ В ОТЧЕТНОСТЬ ВСЕ ИМЕЮЩИЕСЯ ЗАЯВКИ В CSV ФАЙЛ.
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ class CheckTimeRqstAvailability
|
|||||||
$timeMin->setTime($minRqstTime, 00, 00);
|
$timeMin->setTime($minRqstTime, 00, 00);
|
||||||
|
|
||||||
#Гаврилов
|
#Гаврилов
|
||||||
//ПОМЕНЯЙ
|
//ПОМЕНЯЙ (ПОКА ТАК ДЛЯ ТЕСТИРОВАНИЯ)
|
||||||
if (!($timeNow > $timeMin && $timeNow < $timeMax)) {
|
if (!($timeNow > $timeMin && $timeNow < $timeMax)) {
|
||||||
//if (!($timeNow > $timeMin && $timeNow > $timeMax)) {
|
//if (!($timeNow > $timeMin && $timeNow > $timeMax)) {
|
||||||
$errMsg = "Работа с заявками на такси заблокирована с $maxRqstTime:00 по 0$minRqstTime:00";
|
$errMsg = "Работа с заявками на такси заблокирована с $maxRqstTime:00 по 0$minRqstTime:00";
|
||||||
@@ -34,6 +34,8 @@ class CheckTimeRqstAvailability
|
|||||||
//ПОДУМАТЬ КАКОЙ КОД ЛУЧШЕ ВЕРНУТЬ
|
//ПОДУМАТЬ КАКОЙ КОД ЛУЧШЕ ВЕРНУТЬ
|
||||||
//Метод expectsJson позволяет определить вызывается ли api роут через ajax/fetch, либо web route.
|
//Метод expectsJson позволяет определить вызывается ли api роут через ajax/fetch, либо web route.
|
||||||
if ($request->expectsJson()) {
|
if ($request->expectsJson()) {
|
||||||
|
#Гаврилов
|
||||||
|
//ЗАМЕНИТЬ НА ОТВЕТ ЧЕРЕЗ APIRESPONDER. ТАМ ЛУЧШЕ РЕАЛИЗОВАТЬ ВСЮ КАСТОМНУЮ ЛОГИКУ ГЕНЕРАЦИИ ОТВЕТОВ НА API ЗАПРОСЫ С ФРОНТА
|
||||||
return response()->json([
|
return response()->json([
|
||||||
'errorMsg' => $errMsg
|
'errorMsg' => $errMsg
|
||||||
], 400);
|
], 400);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use App\Models\OldMagicModels;
|
|||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use DateTime;
|
use DateTime;
|
||||||
|
|
||||||
|
//Не помню точно, но это считается частью логики ларавель - не моя задумка. Некая сущность, которая через себя пропускает данные запроса, валидируя их. Вроде даже вызывается автоматически при работе с формой. Вызывается сразу в начале передачи данных, поэтому гарантирует, что по всему флоу работы с запросом объект с данными уже валиден для нас
|
||||||
class TaxiOrderRequest extends FormRequest
|
class TaxiOrderRequest extends FormRequest
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace Modules\Taxi\App\Providers;
|
|||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
use Modules\Taxi\App\Services\TaxiMailerService;
|
use Modules\Taxi\App\Services\TaxiMailerService;
|
||||||
|
|
||||||
|
//Регистрация сервиса отправки писем по работе с Такси
|
||||||
class TaxiMailerProvider extends ServiceProvider
|
class TaxiMailerProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
@@ -12,9 +13,7 @@ class TaxiMailerProvider extends ServiceProvider
|
|||||||
*/
|
*/
|
||||||
public function register(): void
|
public function register(): void
|
||||||
{
|
{
|
||||||
#Гаврилов
|
$this->app->bind(TaxiMailerService::class, function ($app) {
|
||||||
//ЗАЧЕМ В КАЧЕСТВЕ АРГУМЕНТА ПЕРЕЛАЕТСЯ $app?
|
|
||||||
$this->app->bind(TaxiMailerService::class, function($app) {
|
|
||||||
return new TaxiMailerService();
|
return new TaxiMailerService();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace Modules\Taxi\App\Providers;
|
|||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
use Modules\Taxi\App\Console\SendOrdersToTaxiCommand;
|
use Modules\Taxi\App\Console\SendOrdersToTaxiCommand;
|
||||||
|
|
||||||
|
//Не вполне помню зачем этот провайдер, для какого сервиса. Судя по названию, для работы с расписанием операций с приложением. Например, отправка итогового письма с заявками на такси или чистка чего-то
|
||||||
class TaxiScheduleProvider extends ServiceProvider
|
class TaxiScheduleProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace Modules\Taxi\App\Providers;
|
|||||||
use Illuminate\Support\Facades\Blade;
|
use Illuminate\Support\Facades\Blade;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
|
||||||
|
//Подозреваю, что это какой-то core провайдер для модуля
|
||||||
class TaxiServiceProvider extends ServiceProvider
|
class TaxiServiceProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
protected string $moduleName = 'Taxi';
|
protected string $moduleName = 'Taxi';
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::create('taxi_main', function (Blueprint $table) {
|
|
||||||
$table->id();
|
|
||||||
$table->string('emp_login', 30)->comment('логин сотрудника кто поедет');
|
|
||||||
$table->string('emp_phone', 15)->comment('телефон сотрудника');
|
|
||||||
$table->date('taxi_date')->comment('дата заказа такси');
|
|
||||||
$table->time('taxi_time')->comment('время заказа такси');
|
|
||||||
$table->string('taxi_address', 500)->comment('адрес заказа такси');
|
|
||||||
$table->boolean('archive')->default(0);
|
|
||||||
$table->timestamps();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
Schema::dropIfExists('taxi_main');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::create('taxi_hist', function (Blueprint $table) {
|
|
||||||
$table->id('hist_id');
|
|
||||||
$table->integer('id_change_row')->default(NULL)->comment('id изменяемой строки');
|
|
||||||
$table->string('table_name', 50)->default(NULL)->comment('имя изменямой таблицы');
|
|
||||||
$table->string('field_name', 50)->default(NULL)->comment('имя изменяемого поля');
|
|
||||||
$table->string('emp_login', 50)->default(NULL)->comment('логин сотрудника, внесшего изменение');
|
|
||||||
$table->string('value_before', 500)->default(NULL)->comment('значение ДО');
|
|
||||||
$table->string('value_after', 500)->default(NULL)->comment('значение ПОСЛЕ');
|
|
||||||
$table->timestamps();
|
|
||||||
$table->comment('Таблица с историей изменений по процессу Заказ такси');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
Schema::dropIfExists('taxi_hist');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::create('taxi_time_period', function (Blueprint $table) {
|
|
||||||
$table->id();
|
|
||||||
$table->string('time_period', 5)->comment('Временнoй промежуток');
|
|
||||||
$table->boolean('archive')->default(0)->comment('Актуальность');
|
|
||||||
$table->timestamps();
|
|
||||||
$table->comment('Временные промежутки для заказа такси');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
Schema::dropIfExists('taxi_time_period');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::rename('taxi_time_period', 'taxi_time_periods');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_main', function (Blueprint $table){
|
|
||||||
$table->string('taxi_time', 8)->change();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_main', function (Blueprint $table) {
|
|
||||||
//$table->renameColumn('archive', 'cancel_rqst');
|
|
||||||
$table->string('taxi_time', 6)->change();
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_main', function (Blueprint $table) {
|
|
||||||
$table->boolean('cancel_rqst')->default(0)->after('archive');
|
|
||||||
$table->dropColumn('archive');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
// Schema::table('taxi_main', function(Blueprint $table) {
|
|
||||||
// $table->renameColumn('taxi_address', 'order_addr_to');
|
|
||||||
// });
|
|
||||||
DB::statement('ALTER TABLE taxi_main CHANGE COLUMN taxi_address taxi_address_to Varchar(500)');
|
|
||||||
// Schema::table('taxi_main', function (Blueprint $table) {
|
|
||||||
// $table->renameColumn('taxi_address', 'taxi_address_to')->change();
|
|
||||||
// //$table->string('taxi_time', 8)->change();
|
|
||||||
// });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
// Schema::table('taxi_main', function(Blueprint $table) {
|
|
||||||
// $table->renameColumn('order_addr_to', 'taxi_address');
|
|
||||||
// });
|
|
||||||
DB::statement('ALTER TABLE taxi_main CHANGE COLUMN taxi_address_to taxi_address Varchar(500)');
|
|
||||||
// Schema::table('taxi_main', function (Blueprint $table) {
|
|
||||||
// //$table->renameColumn('archive', 'cancel_rqst');
|
|
||||||
// $table->renameColumn('taxi_address_to', 'taxi_address')->change();
|
|
||||||
// // $table->string('taxi_time', 6)->change();
|
|
||||||
// });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_main', function(Blueprint $table){
|
|
||||||
$table->string('taxi_address_from', 500)->after('taxi_time')->comment('Адрес откуда ехать');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_main', function(Blueprint $table){
|
|
||||||
$table->dropColumn('taxi_address_from');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_main', function(Blueprint $table){
|
|
||||||
$table->string('taxi_address_from', 500)->nullable(false)->change();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_main', function(Blueprint $table){
|
|
||||||
$table->string('taxi_address_from', 500)->nullable(true)->change();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_main', function(Blueprint $table){
|
|
||||||
$table->string('taxi_address_to', 500)->nullable(false)->change();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_main', function(Blueprint $table){
|
|
||||||
$table->string('taxi_address_to', 500)->nullable(true)->change();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_time_periods', function(Blueprint $table){
|
|
||||||
$table->boolean('morning_time')->after('time_period')->nullable(false)->default(true)->comment('Утренний промежуток времени');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
Schema::table('taxi_time_periods', function(Blueprint $table){
|
|
||||||
$table->dropColumn('morning_time');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
DB::statement('ALTER TABLE taxi_time_periods CHANGE COLUMN morning_time is_morning_time Boolean');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
DB::statement('ALTER TABLE taxi_time_periods CHANGE COLUMN is_morning_time morning_time Boolean');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
|
|
||||||
return new class extends Migration
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
|
||||||
Schema::create('office_address', function(Blueprint $table){
|
|
||||||
$table->id();
|
|
||||||
$table->string('place', 20)->nullable(false)->comment('Площадка');
|
|
||||||
$table->string('address', 100)->nullable(false)->comment('Адрес');
|
|
||||||
$table->comment('Адреса офисов для подстановки в заказы такси');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
|
||||||
Schema::drop('office_address');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
#Гаврилов
|
||||||
|
//РЕШИЛ, ЧТО ТАКОЙ КОНФИГ - МОЖЕТ БЫТЬ ОБЯЗАТЕЛЬНОЙ ЧАСТЬЮ КАЖДОГО МОДУЛЯ
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'name' => 'Taxi',
|
'name' => 'Taxi',
|
||||||
#Гаврилов
|
#Гаврилов
|
||||||
|
|||||||
@@ -1,67 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Modules\Test\App\Http\Controllers;
|
|
||||||
|
|
||||||
use App\Http\Controllers\Controller;
|
|
||||||
use Illuminate\Http\RedirectResponse;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Http\Response;
|
|
||||||
|
|
||||||
class TestController extends Controller
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Display a listing of the resource.
|
|
||||||
*/
|
|
||||||
public function index()
|
|
||||||
{
|
|
||||||
return view('test::index');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Show the form for creating a new resource.
|
|
||||||
*/
|
|
||||||
public function create()
|
|
||||||
{
|
|
||||||
return view('test::create');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Store a newly created resource in storage.
|
|
||||||
*/
|
|
||||||
public function store(Request $request): RedirectResponse
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Show the specified resource.
|
|
||||||
*/
|
|
||||||
public function show($id)
|
|
||||||
{
|
|
||||||
return view('test::show');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Show the form for editing the specified resource.
|
|
||||||
*/
|
|
||||||
public function edit($id)
|
|
||||||
{
|
|
||||||
return view('test::edit');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update the specified resource in storage.
|
|
||||||
*/
|
|
||||||
public function update(Request $request, $id): RedirectResponse
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove the specified resource from storage.
|
|
||||||
*/
|
|
||||||
public function destroy($id)
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Modules\Test\App\Providers;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
|
||||||
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
|
||||||
|
|
||||||
class RouteServiceProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The module namespace to assume when generating URLs to actions.
|
|
||||||
*/
|
|
||||||
protected string $moduleNamespace = 'Modules\Test\App\Http\Controllers';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Called before routes are registered.
|
|
||||||
*
|
|
||||||
* Register any model bindings or pattern based filters.
|
|
||||||
*/
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
parent::boot();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Define the routes for the application.
|
|
||||||
*/
|
|
||||||
public function map(): void
|
|
||||||
{
|
|
||||||
$this->mapApiRoutes();
|
|
||||||
|
|
||||||
$this->mapWebRoutes();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Define the "web" routes for the application.
|
|
||||||
*
|
|
||||||
* These routes all receive session state, CSRF protection, etc.
|
|
||||||
*/
|
|
||||||
protected function mapWebRoutes(): void
|
|
||||||
{
|
|
||||||
Route::middleware('web')
|
|
||||||
->namespace($this->moduleNamespace)
|
|
||||||
->group(module_path('Test', '/routes/web.php'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Define the "api" routes for the application.
|
|
||||||
*
|
|
||||||
* These routes are typically stateless.
|
|
||||||
*/
|
|
||||||
protected function mapApiRoutes(): void
|
|
||||||
{
|
|
||||||
Route::prefix('api')
|
|
||||||
->middleware('api')
|
|
||||||
->namespace($this->moduleNamespace)
|
|
||||||
->group(module_path('Test', '/routes/api.php'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Modules\Test\App\Providers;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Blade;
|
|
||||||
use Illuminate\Support\ServiceProvider;
|
|
||||||
|
|
||||||
class TestServiceProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
protected string $moduleName = 'Test';
|
|
||||||
|
|
||||||
protected string $moduleNameLower = 'test';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Boot the application events.
|
|
||||||
*/
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
$this->registerCommands();
|
|
||||||
$this->registerCommandSchedules();
|
|
||||||
$this->registerTranslations();
|
|
||||||
$this->registerConfig();
|
|
||||||
$this->registerViews();
|
|
||||||
$this->loadMigrationsFrom(module_path($this->moduleName, 'Database/migrations'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register the service provider.
|
|
||||||
*/
|
|
||||||
public function register(): void
|
|
||||||
{
|
|
||||||
$this->app->register(RouteServiceProvider::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register commands in the format of Command::class
|
|
||||||
*/
|
|
||||||
protected function registerCommands(): void
|
|
||||||
{
|
|
||||||
// $this->commands([]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register command Schedules.
|
|
||||||
*/
|
|
||||||
protected function registerCommandSchedules(): void
|
|
||||||
{
|
|
||||||
// $this->app->booted(function () {
|
|
||||||
// $schedule = $this->app->make(Schedule::class);
|
|
||||||
// $schedule->command('inspire')->hourly();
|
|
||||||
// });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register translations.
|
|
||||||
*/
|
|
||||||
public function registerTranslations(): void
|
|
||||||
{
|
|
||||||
$langPath = resource_path('lang/modules/'.$this->moduleNameLower);
|
|
||||||
|
|
||||||
if (is_dir($langPath)) {
|
|
||||||
$this->loadTranslationsFrom($langPath, $this->moduleNameLower);
|
|
||||||
$this->loadJsonTranslationsFrom($langPath);
|
|
||||||
} else {
|
|
||||||
$this->loadTranslationsFrom(module_path($this->moduleName, 'lang'), $this->moduleNameLower);
|
|
||||||
$this->loadJsonTranslationsFrom(module_path($this->moduleName, 'lang'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register config.
|
|
||||||
*/
|
|
||||||
protected function registerConfig(): void
|
|
||||||
{
|
|
||||||
$this->publishes([module_path($this->moduleName, 'config/config.php') => config_path($this->moduleNameLower.'.php')], 'config');
|
|
||||||
$this->mergeConfigFrom(module_path($this->moduleName, 'config/config.php'), $this->moduleNameLower);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register views.
|
|
||||||
*/
|
|
||||||
public function registerViews(): void
|
|
||||||
{
|
|
||||||
$viewPath = resource_path('views/modules/'.$this->moduleNameLower);
|
|
||||||
$sourcePath = module_path($this->moduleName, 'resources/views');
|
|
||||||
|
|
||||||
$this->publishes([$sourcePath => $viewPath], ['views', $this->moduleNameLower.'-module-views']);
|
|
||||||
|
|
||||||
$this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->moduleNameLower);
|
|
||||||
|
|
||||||
$componentNamespace = str_replace('/', '\\', config('modules.namespace').'\\'.$this->moduleName.'\\'.config('modules.paths.generator.component-class.path'));
|
|
||||||
Blade::componentNamespace($componentNamespace, $this->moduleNameLower);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the services provided by the provider.
|
|
||||||
*/
|
|
||||||
public function provides(): array
|
|
||||||
{
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
private function getPublishableViewPaths(): array
|
|
||||||
{
|
|
||||||
$paths = [];
|
|
||||||
foreach (config('view.paths') as $path) {
|
|
||||||
if (is_dir($path.'/modules/'.$this->moduleNameLower)) {
|
|
||||||
$paths[] = $path.'/modules/'.$this->moduleNameLower;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $paths;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Modules\Test\Database\Seeders;
|
|
||||||
|
|
||||||
use Illuminate\Database\Seeder;
|
|
||||||
|
|
||||||
class TestDatabaseSeeder extends Seeder
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the database seeds.
|
|
||||||
*/
|
|
||||||
public function run(): void
|
|
||||||
{
|
|
||||||
// $this->call([]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "nwidart/test",
|
|
||||||
"description": "",
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "Nicolas Widart",
|
|
||||||
"email": "n.widart@gmail.com"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"extra": {
|
|
||||||
"laravel": {
|
|
||||||
"providers": [],
|
|
||||||
"aliases": {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"autoload": {
|
|
||||||
"psr-4": {
|
|
||||||
"Modules\\Test\\": "",
|
|
||||||
"Modules\\Test\\App\\": "app/",
|
|
||||||
"Modules\\Test\\Database\\Factories\\": "database/factories/",
|
|
||||||
"Modules\\Test\\Database\\Seeders\\": "database/seeders/"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"autoload-dev": {
|
|
||||||
"psr-4": {
|
|
||||||
"Modules\\Test\\Tests\\": "tests/"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
return [
|
|
||||||
'name' => 'Test',
|
|
||||||
];
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "Test",
|
|
||||||
"alias": "test",
|
|
||||||
"description": "",
|
|
||||||
"keywords": [],
|
|
||||||
"priority": 0,
|
|
||||||
"providers": [
|
|
||||||
"Modules\\Test\\App\\Providers\\TestServiceProvider"
|
|
||||||
],
|
|
||||||
"files": []
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
{
|
|
||||||
"private": true,
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"dev": "vite",
|
|
||||||
"build": "vite build"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"axios": "^1.1.2",
|
|
||||||
"laravel-vite-plugin": "^0.7.5",
|
|
||||||
"sass": "^1.69.5",
|
|
||||||
"postcss": "^8.3.7",
|
|
||||||
"vite": "^4.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
@extends('test::layouts.master')
|
|
||||||
|
|
||||||
@section('content')
|
|
||||||
<h1>Hello World</h1>
|
|
||||||
|
|
||||||
<p>Module: {!! config('test.name') !!}</p>
|
|
||||||
@endsection
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<meta name="csrf-token" content="{{ csrf_token() }}">
|
|
||||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
|
||||||
|
|
||||||
<title>Test Module - {{ config('app.name', 'Laravel') }}</title>
|
|
||||||
|
|
||||||
<meta name="description" content="{{ $description ?? '' }}">
|
|
||||||
<meta name="keywords" content="{{ $keywords ?? '' }}">
|
|
||||||
<meta name="author" content="{{ $author ?? '' }}">
|
|
||||||
|
|
||||||
<!-- Fonts -->
|
|
||||||
<link rel="preconnect" href="https://fonts.bunny.net">
|
|
||||||
<link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />
|
|
||||||
|
|
||||||
{{-- Vite CSS --}}
|
|
||||||
{{-- {{ module_vite('build-test', 'resources/assets/sass/app.scss') }} --}}
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
@yield('content')
|
|
||||||
|
|
||||||
{{-- Vite JS --}}
|
|
||||||
{{-- {{ module_vite('build-test', 'resources/assets/js/app.js') }} --}}
|
|
||||||
</body>
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Support\Facades\Route;
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| API Routes
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| Here is where you can register API routes for your application. These
|
|
||||||
| routes are loaded by the RouteServiceProvider within a group which
|
|
||||||
| is assigned the "api" middleware group. Enjoy building your API!
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
Route::middleware(['auth:sanctum'])->prefix('v1')->name('api.')->group(function () {
|
|
||||||
Route::get('test', fn (Request $request) => $request->user())->name('test');
|
|
||||||
});
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
|
||||||
use Modules\Test\App\Http\Controllers\TestController;
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Web Routes
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| Here is where you can register web routes for your application. These
|
|
||||||
| routes are loaded by the RouteServiceProvider within a group which
|
|
||||||
| contains the "web" middleware group. Now create something great!
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
Route::group([], function () {
|
|
||||||
Route::resource('test', TestController::class)->names('test');
|
|
||||||
});
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { defineConfig } from 'vite';
|
|
||||||
import laravel from 'laravel-vite-plugin';
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
build: {
|
|
||||||
outDir: '../../public/build-test',
|
|
||||||
emptyOutDir: true,
|
|
||||||
manifest: true,
|
|
||||||
},
|
|
||||||
plugins: [
|
|
||||||
laravel({
|
|
||||||
publicDirectory: '../../public',
|
|
||||||
buildDirectory: 'build-test',
|
|
||||||
input: [
|
|
||||||
__dirname + '/resources/assets/sass/app.scss',
|
|
||||||
__dirname + '/resources/assets/js/app.js'
|
|
||||||
],
|
|
||||||
refresh: true,
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
//export const paths = [
|
|
||||||
// 'Modules/$STUDLY_NAME$/resources/assets/sass/app.scss',
|
|
||||||
// 'Modules/$STUDLY_NAME$/resources/assets/js/app.js',
|
|
||||||
//];
|
|
||||||
@@ -1,3 +1,59 @@
|
|||||||
# laravel
|
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
|
||||||
|
|
||||||
поделки на ларавеле
|
<p align="center">
|
||||||
|
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
|
||||||
|
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
|
||||||
|
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
|
||||||
|
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
## About Laravel
|
||||||
|
|
||||||
|
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
|
||||||
|
|
||||||
|
- [Simple, fast routing engine](https://laravel.com/docs/routing).
|
||||||
|
- [Powerful dependency injection container](https://laravel.com/docs/container).
|
||||||
|
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
|
||||||
|
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
|
||||||
|
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
|
||||||
|
- [Robust background job processing](https://laravel.com/docs/queues).
|
||||||
|
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
|
||||||
|
|
||||||
|
Laravel is accessible, powerful, and provides tools required for large, robust applications.
|
||||||
|
|
||||||
|
## Learning Laravel
|
||||||
|
|
||||||
|
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. You can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application.
|
||||||
|
|
||||||
|
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
|
||||||
|
|
||||||
|
## Laravel Sponsors
|
||||||
|
|
||||||
|
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
|
||||||
|
|
||||||
|
### Premium Partners
|
||||||
|
|
||||||
|
- **[Vehikl](https://vehikl.com)**
|
||||||
|
- **[Tighten Co.](https://tighten.co)**
|
||||||
|
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
|
||||||
|
- **[64 Robots](https://64robots.com)**
|
||||||
|
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
|
||||||
|
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
|
||||||
|
- **[Redberry](https://redberry.international/laravel-development)**
|
||||||
|
- **[Active Logic](https://activelogic.com)**
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
|
||||||
|
|
||||||
|
## Code of Conduct
|
||||||
|
|
||||||
|
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
|
||||||
|
|
||||||
|
## Security Vulnerabilities
|
||||||
|
|
||||||
|
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Console\Commands;
|
|
||||||
|
|
||||||
use Illuminate\Console\Command;
|
|
||||||
use Illuminate\Support\Facades\Log;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Базовый класс для описания команд по расписанию
|
|
||||||
* Создан, в частности, чтобы предоставить универсальный функционал для всех команд, запускаемых по расписанию
|
|
||||||
*/
|
|
||||||
abstract class BaseScheduleCommand extends Command
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Метод выполнения команды
|
|
||||||
*
|
|
||||||
* @param callable $execFunc функция с логикой выполнения команды
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
protected function executeCommand(callable $execFunc): void
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
$execFunc();
|
|
||||||
|
|
||||||
} catch (\Throwable $th) {
|
|
||||||
$this->logExecErr($th);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод логирования ошибки выполнения скриптов по расписанию
|
|
||||||
*
|
|
||||||
* @param \Throwable $th
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
private function logExecErr(\Throwable $th): void
|
|
||||||
{
|
|
||||||
$context = [
|
|
||||||
//Скрипт откуда запустилась задача
|
|
||||||
'command' => static::class,
|
|
||||||
//Скрипт, в котором произошла ошибка
|
|
||||||
'file' => $th->getFile(),
|
|
||||||
'line' => $th->getLine(),
|
|
||||||
];
|
|
||||||
\Log::channel('schedule_err')->error($th->getMessage(), $context);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Console\Commands;
|
|
||||||
|
|
||||||
use Illuminate\Console\Command;
|
|
||||||
use App\Models\TestData;
|
|
||||||
|
|
||||||
class testDataCommand extends Command
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The name and signature of the console command.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $signature = 'data_base:test-data-command';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The console command description.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $description = 'Тестовая команда';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute the console command.
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
|
||||||
$testDataModel = new TestData;
|
|
||||||
$test = TestData::where('test_char', 'hellos')->get();
|
|
||||||
var_dump($test);
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -23,6 +23,8 @@ class Kernel extends ConsoleKernel
|
|||||||
// ->byAnonymous()
|
// ->byAnonymous()
|
||||||
// ->inLog('Shedule')
|
// ->inLog('Shedule')
|
||||||
// ->event('clear_old_Sanctum_tokens');
|
// ->event('clear_old_Sanctum_tokens');
|
||||||
|
|
||||||
|
//попытка поработать с командами по расписанию. Не успел протестить. В частности, в этом скрипте планируется в определенное время инициировать отправку всех заявок на такси
|
||||||
$schedule->command('taxi:send-today-orders-mail')->dailyAt('08:00');
|
$schedule->command('taxi:send-today-orders-mail')->dailyAt('08:00');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,7 +33,7 @@ class Kernel extends ConsoleKernel
|
|||||||
*/
|
*/
|
||||||
protected function commands(): void
|
protected function commands(): void
|
||||||
{
|
{
|
||||||
$this->load(__DIR__.'/Commands');
|
$this->load(__DIR__ . '/Commands');
|
||||||
|
|
||||||
require base_path('routes/console.php');
|
require base_path('routes/console.php');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Dto;
|
|
||||||
|
|
||||||
class ApiResponseDto
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
public readonly ?string $message = null,
|
|
||||||
// public readonly ?int $statusCode = 200,
|
|
||||||
public readonly mixed $data = null,
|
|
||||||
public readonly mixed $meta = null,
|
|
||||||
)
|
|
||||||
{
|
|
||||||
// return new self($this->message, $this->statusCode, $this->data, $this->meta);
|
|
||||||
}
|
|
||||||
|
|
||||||
// public static function success()
|
|
||||||
// {
|
|
||||||
// return new self($message, $data, $statusCode = 200);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// public static function error()
|
|
||||||
// {
|
|
||||||
// return new self($message, $data, $statusCode = 400);
|
|
||||||
// }
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Enums;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Бизнес действия, доступные для логирования через activity_log
|
|
||||||
* @author dgavrilov
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
#Гаврилов
|
|
||||||
//ПОЛУЧИТСЯ ЛИ ПЕРЕДАТЬ НА ФРОНТ ЭТОТ ENUM
|
|
||||||
//ГАВРИЛОВ
|
|
||||||
//ИДЕНТИЧНЫЙ СПРАВОЧНИК УКАЗАН НА СТОРОНЕ react в компоненте ENTITYHISTORY. ЕСТЬ ВОЗМОЖНОСТЬ ОБЪЕДИНИТЬ ИХ?
|
|
||||||
enum LogBusinessEvents: string
|
|
||||||
{
|
|
||||||
case Create = 'create';
|
|
||||||
case Edit = 'edit';
|
|
||||||
case Archive = 'archive';
|
|
||||||
case Restore = 'restore';
|
|
||||||
case Delete = 'delete';
|
|
||||||
case Cancel = 'cancel';
|
|
||||||
|
|
||||||
public function title(): string
|
|
||||||
{
|
|
||||||
return match($this)
|
|
||||||
{
|
|
||||||
self::Create => 'создание',
|
|
||||||
self::Edit => 'редактирование',
|
|
||||||
self::Archive => 'архивация',
|
|
||||||
self::Restore => 'восстановление',
|
|
||||||
self::Delete => 'удаление',
|
|
||||||
self::Cancel => 'отмена',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Exceptions;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
|
||||||
use Throwable;
|
|
||||||
|
|
||||||
class Handler extends ExceptionHandler
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The list of the inputs that are never flashed to the session on validation exceptions.
|
|
||||||
*
|
|
||||||
* @var array<int, string>
|
|
||||||
*/
|
|
||||||
protected $dontFlash = [
|
|
||||||
'current_password',
|
|
||||||
'password',
|
|
||||||
'password_confirmation',
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register the exception handling callbacks for the application.
|
|
||||||
*/
|
|
||||||
public function register(): void
|
|
||||||
{
|
|
||||||
$this->reportable(function (Throwable $e) {
|
|
||||||
//
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Facades;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Facade;
|
|
||||||
use App\Services\RedisNotificationService;
|
|
||||||
|
|
||||||
class RedisNotifications extends Facade
|
|
||||||
{
|
|
||||||
protected static function getFacadeAccessor()
|
|
||||||
{
|
|
||||||
return \App\Services\RedisNotificationService::class;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Facades;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Facade;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Фасад для доступа к user сервису без инъекции зависимостей
|
|
||||||
*
|
|
||||||
* @see \App\Services\UserService
|
|
||||||
*/
|
|
||||||
class UserContext extends Facade
|
|
||||||
{
|
|
||||||
protected static function getFacadeAccessor()
|
|
||||||
{
|
|
||||||
return \App\Services\UserService::class;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use App\Models\AccessModel;
|
|
||||||
|
|
||||||
class AccessListController extends Controller
|
|
||||||
{
|
|
||||||
public function getAccess($id = null)
|
|
||||||
{
|
|
||||||
$accessListModel = new AccessModel();
|
|
||||||
$accessListData = $accessListModel::where(['access_id' => $id])->select('access_id')->get();
|
|
||||||
if ($id) {
|
|
||||||
echo '<pre>'; var_dump($accessListData->toArray()); echo'</pre>';
|
|
||||||
} else {
|
|
||||||
var_dump($accessListModel::all());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public function postAccess(Request $rqst)
|
|
||||||
{
|
|
||||||
$accessListModel = new AccessModel();
|
|
||||||
$accessListModel->role = $rqst['role'];
|
|
||||||
$accessListModel->title = $rqst['title'];
|
|
||||||
$accessListModel->save();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function delAccess($id)
|
|
||||||
{
|
|
||||||
$accessListModel = new AccessModel();
|
|
||||||
//$accessListModel::where(['access_id' => $id])->delete();
|
|
||||||
$accessListModel::destroy($id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Spatie\Activitylog\Models\Activity;
|
|
||||||
// use App\Services\ModuleService;
|
|
||||||
use App\Services\UserService;
|
|
||||||
use App\Facades\UserContext;
|
|
||||||
use App\Services\ApiResponder;
|
|
||||||
use App\Dto\ApiResponseDto;
|
|
||||||
use App\Enums\LogBusinessAction;
|
|
||||||
use App\Models\User;
|
|
||||||
use Illuminate\Http\JsonResponse;
|
|
||||||
|
|
||||||
class AppHistoryController extends Controller
|
|
||||||
{
|
|
||||||
public function __construct(protected ApiResponder $apiResponder)
|
|
||||||
{}
|
|
||||||
|
|
||||||
public function getAppHistory($appName, $subjectId): JsonResponse
|
|
||||||
{
|
|
||||||
#Гаврилов
|
|
||||||
//ПОКА НЕ РЕАЛИЗОВЫВАЮ ОГРАНИЧЕНИЕ ДОСТУПА К ИСТОРИИ ПО РОЛЯМ (РОЛЬ ИСТОЧНИКА ЗАПРОСА НЕ ЗАПРАШИВАЕТСЯ И НЕ ВАЛИДИРУЕТСЯ, ТОЛЬКО НАЛИЧИЕ ДОСТУПА К ПРИЛОЖЕНИЮ)
|
|
||||||
if (array_key_exists($appName, UserContext::getUserAppPermissions()) === false) {
|
|
||||||
$this->apiResponder->setDto(new ApiResponseDto('Отсутствует доступ к ресурсу'));
|
|
||||||
return response()->json($this->apiResponder->error(), 403);
|
|
||||||
}
|
|
||||||
$entityHistory = Activity::where('log_name', $appName)
|
|
||||||
->where('subject_id', $subjectId)
|
|
||||||
->get()
|
|
||||||
->toArray();
|
|
||||||
|
|
||||||
$this->apiResponder->setDto(new ApiResponseDto(null, $this->formatHistory($entityHistory)));
|
|
||||||
//echo '<pre>'; var_dump($this->apiResponder->success()); echo'</pre>';
|
|
||||||
//return $this->apiResponder->success();
|
|
||||||
// return response()->json();
|
|
||||||
return $this->apiResponder->success();
|
|
||||||
|
|
||||||
// die();
|
|
||||||
|
|
||||||
// if (empty($entityHistory)) {
|
|
||||||
// $this->apiResponder->setDto(new ApiResponseDto());
|
|
||||||
// return response()->json($this->apiResponder->error());
|
|
||||||
// }
|
|
||||||
|
|
||||||
// $this->apiResponder->setDto(new ApiResponseDto('', ));
|
|
||||||
// return response()->json($this->apiResponder->error());
|
|
||||||
|
|
||||||
// die();
|
|
||||||
// //$appName = $moduleName ?? (new ModuleService())->getModuleName();
|
|
||||||
|
|
||||||
// //echo '<pre>'; var_dump(UserService->getUserAppPermissions()); echo'</pre>';
|
|
||||||
|
|
||||||
// echo '<pre>'; var_dump($rqst->subject_id); echo'</pre>';
|
|
||||||
// echo '<pre>'; var_dump($appName); echo'</pre>';
|
|
||||||
|
|
||||||
// if (!$appName) {
|
|
||||||
// #Гаврилов
|
|
||||||
// //ВОЗВРАЩАЕМ ОШИБКУ, ЕСЛИ ИСТОРИЯ НЕ НАЙДЕНА. ИЛИ НА УРОВНЕ ФРОНТА ПРОВЕРЯЕМ ПУСТАЯ ЛИ ИСТОРИЯ И ВЫВОДИМ ВСПЛЫВАЮЩЕЕ ОКНО что "ИСТОРИЯ ОТСУТСТВУЕТ"
|
|
||||||
// return '';
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
|
||||||
// return '';
|
|
||||||
// // $entityHistory = Activity::where('log_name', 'Taxi')
|
|
||||||
// // ->where('subject_id', $entityId)
|
|
||||||
// // ->get();
|
|
||||||
|
|
||||||
// // return $entityHistory;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private function formatHistory($historyData)
|
|
||||||
{
|
|
||||||
$formattedHistory = [];
|
|
||||||
foreach ($historyData as $historyAction) {
|
|
||||||
$historyChange = [];
|
|
||||||
#Гаврилов
|
|
||||||
//ДОЛЖНО ЛОГИРОВАТЬСЯ ID АУТЕНТИФИЦИРОВАННОГО ПОЛЬЗОВАТЕЛЯ. сЕЙЧАС ЗАПИСЫВАЕМ КОЛХОЗНО В PROPERTIES.
|
|
||||||
//ПРОВЕРЬ ЧТО ДЕЛАТЬ, ЕСЛИ ПОЛЬЗОВАТЕЛЬ - API?
|
|
||||||
$historyChange['changeAction'] = $historyAction['business_event'];
|
|
||||||
$user = User::find($historyAction['causer_id']);
|
|
||||||
$login = $user->login;
|
|
||||||
$historyChange['changeAuthor'] = $login;
|
|
||||||
$actionDate = new \DateTime($historyAction['created_at']);
|
|
||||||
$historyChange['changeDate'] = $actionDate->format('d.m.Y');
|
|
||||||
$historyChange['changeTime'] = $actionDate->format('H:i:s');
|
|
||||||
$historyChange['changeDetails'] = json_encode($historyAction['properties']['attributes'], JSON_UNESCAPED_UNICODE);
|
|
||||||
$formattedHistory[] = $historyChange;
|
|
||||||
}
|
|
||||||
|
|
||||||
//ГАВРИЛОВ. СОЗДАЙ СЕРВИС. В НЕМ РЕАЛ3ИЗУЙ МЕТОДЫ НАЗНАЧЕНИЯ ЗНАЧЕНИЙ КАЖДОМУ СВОЙСТВУ ОБЪЕКТА ИСТОРИИ . ИЗ КОНТРОЛЛЕРА СОЗДАВАЙ ЭКЗЕМПЛЯР КЛАССА СЕРВИСА. В КОНТРОЛЛЕРЕ СЕРВИСА ПО ОЧЕРЕДИ ВЫЗЫВАЙ ВСЕ МЕТОДЫ НАЗНАЧЕНИЯ СВОЙСТВ ИСТОРИИ.
|
|
||||||
|
|
||||||
|
|
||||||
return $formattedHistory;
|
|
||||||
//changeAction: string, //Совершенное действие: создание, удаление, редактирование, архивирование и т.д.
|
|
||||||
// changeAuthor: string, //Автор изменения: логин, сервисная УЗ
|
|
||||||
// changeDate: Date //Объект даты изменения. В объекте будет либо время (тогда показываем), либо время будет отсутствовать (тогда не показываем) //что будем передавать? объект new Date или библиотечный объект для работы с датами?
|
|
||||||
// changeTime?: string //Время изменений. Передавать не нужно, на этабе сборки компонента будет формироваться на основе пропса changeDate
|
|
||||||
// changeDetails?: HistoryEntityElDetails[]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use App\Services\AuthorizationService;
|
|
||||||
use App\Facades\UserContext;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Контроллер авторизации
|
|
||||||
*/
|
|
||||||
class AuthorizationController extends Controller
|
|
||||||
{
|
|
||||||
public function __construct(AuthorizationService $authorizationService)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getUserRole($moduleName)
|
|
||||||
{
|
|
||||||
$userPermissions = UserContext::getUserAppPermissions();
|
|
||||||
//Проверяем есть ли у пользователя в принципе доступ к приложению
|
|
||||||
if (array_key_exists($moduleName, $userPermissions) !== false) {
|
|
||||||
return response()->json(['userRole' => $userPermissions[$moduleName]], 403);
|
|
||||||
} else {
|
|
||||||
return response()->json(['message' => 'Приложение недоступно'], 403);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,11 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
abstract class Controller
|
||||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
|
||||||
use Illuminate\Routing\Controller as BaseController;
|
|
||||||
|
|
||||||
class Controller extends BaseController
|
|
||||||
{
|
{
|
||||||
use AuthorizesRequests, ValidatesRequests;
|
//
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,248 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Support\Facades\Auth;
|
|
||||||
use LdapRecord\Models\ActiveDirectory\User as LdapUserInfo;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Facades\UserContext;
|
|
||||||
use App\Services\AuthorizationService;
|
|
||||||
use App\Services\ApiResponder;
|
|
||||||
use App\Dto\ApiResponseDto;
|
|
||||||
|
|
||||||
class LoginController extends Controller
|
|
||||||
{
|
|
||||||
#Гаврилов
|
|
||||||
//КОГДА ПЕРЕЙДЕМ НА ГРУППЫ, ПОМЕНЯТЬ НА АДМИНСКУЮ ГРУППУ? ИЛИ ОСТАВИТЬ РАССЫЛКУ?
|
|
||||||
//ПЕРЕНЕСИ В .ENV И ВНИЗУ ПО КОДУ ГДЕ ОБРАЩАЕШЬСЯ К ЭТОМУ СВОЙСТВУ КЛАССА ПЕРЕПИШИ НА ПОЛУЧЕНИЕ СВОЙСТВА ИЗ ПЕРЕМЕННОЙ ОКРУЖЕНИЯ
|
|
||||||
/**
|
|
||||||
* @var string почтовая рассылка, куда входят админы
|
|
||||||
*/
|
|
||||||
private $adminGroup = '# Magic_admins';
|
|
||||||
/**
|
|
||||||
* @var array массив групп, которые не должны участвовать в авторизации пользователя и поэтому могут не храниться
|
|
||||||
*/
|
|
||||||
#Гаврилов
|
|
||||||
//ИСПОЛЬЗУЙ МАССИВ НИЖЕ, ЧТОБЫ УДАЛЯТЬ ГРУППЫ И НЕ ХРАНИТЬ ИХ В ПРОФИЛЕ ПОЛЬЗОВАТЕЛЯ. ИЛИ ЗАБИТЬ ХЕР И ХРАНИТЬ ВСЕ? ТОГДА УДАЛИ МАССИВ НИЖЕ
|
|
||||||
private $unnecessaryGroups = array(
|
|
||||||
'MCO.',
|
|
||||||
'ARSNOVA.',
|
|
||||||
'CHATBOT.',
|
|
||||||
'FOA_PROJECTS.',
|
|
||||||
'MAXOPTRA.',
|
|
||||||
'WEBSIGNER.',
|
|
||||||
'ECM.',
|
|
||||||
'BASIS.',
|
|
||||||
'MCO_DOCUMENT.',
|
|
||||||
'FACTOR.',
|
|
||||||
'BIP.',
|
|
||||||
'NKK.',
|
|
||||||
'CHATS.',
|
|
||||||
'IB_BSC.',
|
|
||||||
'DASHAAI.',
|
|
||||||
'VDI.',
|
|
||||||
'CTX',
|
|
||||||
'AP.AE.',
|
|
||||||
'Way4',
|
|
||||||
'sg.',
|
|
||||||
'AD.TEDDY',
|
|
||||||
'AP.APPV_',
|
|
||||||
'AP.BI_',
|
|
||||||
'AP.Citrix_',
|
|
||||||
'AP.CSD_',
|
|
||||||
'AP.EFK_',
|
|
||||||
'AP.FlexiCapture_',
|
|
||||||
'AP.HPSM.ACCESS.1',
|
|
||||||
'AP.HPSM.ACCESS.3',
|
|
||||||
'AP.HPSM.APPR_BR.Collection.',
|
|
||||||
'AP.HPSM.APPR_BR.CS.',
|
|
||||||
'AP.HPSM.ACCESS.CC',
|
|
||||||
'AP.HPSM.ACCESS.123',
|
|
||||||
'AP.HPSM.ACCESS.1.2',
|
|
||||||
'AP.HPSM.APPR',
|
|
||||||
'AP.OCP',
|
|
||||||
'AP.IBS_',
|
|
||||||
'AP.Intranet_',
|
|
||||||
'AP.Intranet.',
|
|
||||||
'AP.Jenkins_',
|
|
||||||
'AP.Kibana.',
|
|
||||||
'AP.LICA.',
|
|
||||||
'AP.MailSteam.',
|
|
||||||
'AP.MCO_',
|
|
||||||
'AP.MDW.',
|
|
||||||
'AP.POCHTA_',
|
|
||||||
'AP.PREPROD',
|
|
||||||
'AP.Prometheus',
|
|
||||||
'AP.RDS_',
|
|
||||||
'AP.SAS_',
|
|
||||||
'AP.Seguranzza_',
|
|
||||||
'AP.TEST.LICA.',
|
|
||||||
'AP.Test.MCO_',
|
|
||||||
'AP.TEST',
|
|
||||||
'App_',
|
|
||||||
'BTA_',
|
|
||||||
'Calculations ',
|
|
||||||
'Cards_',
|
|
||||||
'CC.',
|
|
||||||
'CCS_',
|
|
||||||
'Citrix',
|
|
||||||
'Collection_HR_',
|
|
||||||
'Collection_All',
|
|
||||||
'CS_',
|
|
||||||
'CSD_',
|
|
||||||
'DA_',
|
|
||||||
'DB.',
|
|
||||||
'DB_',
|
|
||||||
'Deny_',
|
|
||||||
'Diasoft ',
|
|
||||||
'Digital ',
|
|
||||||
'DOR_',
|
|
||||||
'ECM_',
|
|
||||||
'FS.',
|
|
||||||
'FW.',
|
|
||||||
'INFO_',
|
|
||||||
'MDC.',
|
|
||||||
'NRM_Collection',
|
|
||||||
'PFA.',
|
|
||||||
'RenTest_',
|
|
||||||
'ReportingGroup ',
|
|
||||||
'RS.',
|
|
||||||
'SG.',
|
|
||||||
'SP.',
|
|
||||||
'SRV',
|
|
||||||
'SRVFI09_',
|
|
||||||
'SSO_',
|
|
||||||
'test',
|
|
||||||
'TR_',
|
|
||||||
'WWW_',
|
|
||||||
'MailStream',
|
|
||||||
'SRVTST',
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
public function __construct(private AuthorizationService $authorizationService, private ApiResponder $apiResponder)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
#Гаврилов
|
|
||||||
//ПЕРЕИМЕНУЙ КОНТРОЛЛЕР НА AUTHcoNTROLLER
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод завершения пользовательской сессии
|
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function logout()
|
|
||||||
{
|
|
||||||
//Удаляем все sanctum токены пользователя. Удаление всех токенов приведет к выходу пользователя со всех устройств, где он был залогирован в Magic
|
|
||||||
User::where('login', UserContext::getUserLogin())->first()->tokens()->delete();
|
|
||||||
session()->invalidate();
|
|
||||||
#Гаврилов
|
|
||||||
//ВЫЗОВ СКРИПТА НА СТАРОМ МЭДЖИКЕ ДЛЯ УДАЛЕНИЯ КУК АУТЕНТИФИКАЦИИ (ЛОГИН И ГРУППЫ)
|
|
||||||
return redirect('/login');
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
#Гаврилов
|
|
||||||
//РАЗНЕСИ ЛОГИКУ МЕЖДУ МЕТОДАМИ, А ТО ПОКА ВСЯ ЛОГИКА В ОДНОМ МЕТОД DLAPCHECK
|
|
||||||
public function ldapCheckUser (Request $request)
|
|
||||||
{
|
|
||||||
if ($request->_auth_login) {
|
|
||||||
if (Auth::attempt([
|
|
||||||
'samaccountname' => $request->_auth_login,
|
|
||||||
'password' => $request->_auth_password,
|
|
||||||
])) {
|
|
||||||
|
|
||||||
$userGroups = $this->getUserGroups($request->_auth_login);
|
|
||||||
session()->put('_auth_login', $request->_auth_login);
|
|
||||||
session()->put('_auth_groups', $userGroups);
|
|
||||||
//Если пользователь зашел впервые - записываем его логин в таблицу users. Она нужна для корректного взаимодействия с пакетом Sanctum
|
|
||||||
$user = User::firstOrCreate(
|
|
||||||
['login' => $request->_auth_login],
|
|
||||||
);
|
|
||||||
//Удаляем все предыдущие sanctum токены пользователя
|
|
||||||
User::where('login', $request->_auth_login)->first()->tokens()->delete();
|
|
||||||
//Определяем на какую страницу нужно бросить пользователя после успешной аутентификации. По умолчанию кидаем в меню
|
|
||||||
$redirectUrl = session()->has('_auth_prev_page') ? session()->get('_auth_prev_page') : ('/menu');
|
|
||||||
$isAdminFlag = in_array($this->adminGroup, $userGroups);
|
|
||||||
//Кладем в сессию информацию о том является ли пользователь админом
|
|
||||||
session()->put('is_admin', $isAdminFlag);
|
|
||||||
//Устанавливаем в пользовательский сервис параметры пользователя
|
|
||||||
UserContext::setUserLogin($request->_auth_login);
|
|
||||||
UserContext::setUserADGroups($userGroups);
|
|
||||||
UserContext::setUserEmails($userGroups);
|
|
||||||
UserContext::setIsAdminFlag($isAdminFlag);
|
|
||||||
$userPermissions = $this->authorizationService->getUserAppPermissions();
|
|
||||||
UserContext::setUserAppPermissions($userPermissions);
|
|
||||||
//Генерим Sanctum токен, чтобы поместить его в куки при редиректе
|
|
||||||
$token = $user->createToken('sanctum-token', [
|
|
||||||
'permissions' => $userPermissions
|
|
||||||
//Устанавливаем время жизни sanctum токена синхронно с временем жизни сессии из конфига
|
|
||||||
], now()->addHours(config('app.session_life_time') / 60))->plainTextToken;
|
|
||||||
return redirect($redirectUrl)
|
|
||||||
->withCookie('sanctum_token', $token, 60 * 24, '/', null, true, true);
|
|
||||||
} else {
|
|
||||||
#Гаврилов
|
|
||||||
//СООБЩЕНИЕ ОБ ОШИБКЕ ПРИ НЕУДАЧНОЙ АУТЕНТИФИКАЦИИ
|
|
||||||
return redirect('/login');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод фонового обновления санктум токена при получении 401 ошибки в ответе api ендпоинта
|
|
||||||
*
|
|
||||||
* @param Request $request
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function silentRefreshUserSanctumToken(Request $request)
|
|
||||||
{
|
|
||||||
//Если сессия истекла - возвращаем 401 ошибку и редирект на /login в axios
|
|
||||||
if (!Auth::check()) {
|
|
||||||
$this->apiResponder->setDto(new ApiResponseDto(null, ['token_refresh' => false]));
|
|
||||||
return response()->json($this->apiResponder->error(), 401);
|
|
||||||
}
|
|
||||||
$token = $request->cookie('sanctum_token');
|
|
||||||
$accessToken = \Laravel\Sanctum\PersonalAccessToken::findToken($token);
|
|
||||||
//Если токен "протух" - продлеваем его на час
|
|
||||||
if (now()->diffInMinutes($accessToken->expires_at, false) < 1) {
|
|
||||||
$accessToken->update(
|
|
||||||
[
|
|
||||||
'expires_at' => now()->addHours(1)
|
|
||||||
]
|
|
||||||
);
|
|
||||||
$this->apiResponder->setDto(new ApiResponseDto(null, ['token_refresh' => true]));
|
|
||||||
return response()->json($this->apiResponder->success());
|
|
||||||
} else {
|
|
||||||
//Если токен еще "свежий" - значит причина 401 ошибки в чем-то другом. Не обновляем токен, просто возвращаем 401 ошибку и редирект на /login в axios
|
|
||||||
$this->apiResponder->setDto(new ApiResponseDto(null, ['token_refresh' => false]));
|
|
||||||
return response()->json($this->apiResponder->error(), 401);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод получает группы пользователя из ldap
|
|
||||||
*
|
|
||||||
* @param string $userLogin логин пользователя, чьи группы получаем
|
|
||||||
* @return array
|
|
||||||
*/
|
|
||||||
public function getUserGroups($userLogin)
|
|
||||||
{
|
|
||||||
$userGroups = [];
|
|
||||||
$ldapUser = LdapUserInfo::findBy('samaccountname', $userLogin);
|
|
||||||
$ldapUser->memberOf;
|
|
||||||
if (isset($ldapUser->memberOf)) {
|
|
||||||
foreach ($ldapUser->memberOf as $ldapGroupInfo) {
|
|
||||||
$CN_group = substr($ldapGroupInfo, 0, stripos($ldapGroupInfo, ","));
|
|
||||||
$groupName = str_replace(array('CN=', '\\'), array('', ''), $CN_group);
|
|
||||||
$clearGroupName = trim($groupName);
|
|
||||||
if ($clearGroupName && $clearGroupName == str_replace($this->unnecessaryGroups, '', $clearGroupName)) {
|
|
||||||
$userGroups[] = $clearGroupName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $userGroups;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use App\Models;
|
|
||||||
|
|
||||||
class MenuController extends Controller
|
|
||||||
{
|
|
||||||
public function __construct()
|
|
||||||
{
|
|
||||||
$this->userLogin = 'dgavrilov';
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получение всех записей из таблицы с приложениями для меню
|
|
||||||
* TODO
|
|
||||||
* передавай флаг isActive и используй его для получения записей с приложениями меню архивных и не архивных
|
|
||||||
*
|
|
||||||
* @return mixed
|
|
||||||
*/
|
|
||||||
public function getApps()
|
|
||||||
{
|
|
||||||
//Приложения старого мэджик из скрипта Config_AD
|
|
||||||
$oldApps = $this->getOldApps();
|
|
||||||
#Гаврилов
|
|
||||||
//НОВЫЕ ПРИЛОЖЕНИЯ НЕ ИСПОЛЬЗУЕШЬ
|
|
||||||
//Приложения нового мэджик из базы данных
|
|
||||||
#Гаврилов
|
|
||||||
//отрисовывать только то, что может видеть пользователь
|
|
||||||
$newApps = Models\MagicApps::get()->toArray();
|
|
||||||
|
|
||||||
return response()->json($oldApps);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод получает конфиг со старыми приложениями Magic
|
|
||||||
*
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
public function getOldApps()
|
|
||||||
{
|
|
||||||
$oldAppConf = json_decode(file_get_contents('http://cs/magic/return_config.AD.php'));
|
|
||||||
|
|
||||||
return $oldAppConf;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод должен проверить есть ли избранные приложения у пользователя. Если есть, их необходимо обновить либо добавив, либо убрав то приложение, по которому кликнул пользователь. Если избранных приложений нет - вставить новую запись
|
|
||||||
*
|
|
||||||
* @return boolean
|
|
||||||
*/
|
|
||||||
public function updateUserFavApp(Request $rqst)
|
|
||||||
{
|
|
||||||
#Гаврилов
|
|
||||||
//ВНИЗУ ИСПОЛЬЗУЕТСЯ ЛОГИН DGAVRILOV, ПЕРЕПИШИ НА ЛОГИН ПОЛЬЗОВАТЕЛЯ MAGIC
|
|
||||||
$userFavApp = $this->getUserFavApp('dgavrilov');
|
|
||||||
$appName = $rqst->all()['appName'];
|
|
||||||
$newFavAppList = null;
|
|
||||||
//Если массив с избранными приложениями пустой - пользователь не добавил ни 1 приложения мэджик в избранное
|
|
||||||
if (!$userFavApp) {
|
|
||||||
$newFavAppList = $appName;
|
|
||||||
} else {
|
|
||||||
$currentFavApp = $userFavApp;
|
|
||||||
if (in_array($appName, $currentFavApp) !== false) {
|
|
||||||
$newFavAppList = implode(';', array_filter($currentFavApp, function($el) use($appName) {return $el !== $appName;}));
|
|
||||||
} else {
|
|
||||||
$newFavAppList = implode(';', array_merge($currentFavApp, [$appName]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($newFavAppList) {
|
|
||||||
#Гаврилов
|
|
||||||
//ПРИ ВЫЗОВЕ ИЗ REACT НЕ ОБНОВЛЯЕТСЯ ПОЛЕ UPDATE_AT
|
|
||||||
$this->insertFavApp($newFavAppList);
|
|
||||||
//Если список приложений пуст - просто удаляем запись с избранными приложениями пользователя
|
|
||||||
} else {
|
|
||||||
$this->delAllUserFavApp('dgavrilov');
|
|
||||||
}
|
|
||||||
return $this->getUserFavApp('dgavrilov');
|
|
||||||
}
|
|
||||||
|
|
||||||
#Гаврилов
|
|
||||||
//try catch для отслеживания ошибок вставки записей в БД?
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод вставки новой записи с избранными приложениями
|
|
||||||
*
|
|
||||||
* @return boolean
|
|
||||||
*/
|
|
||||||
public function insertFavApp($appName)
|
|
||||||
{
|
|
||||||
Models\UserFavApp::updateOrCreate(
|
|
||||||
['user_login' => $this->userLogin],
|
|
||||||
['fav_apps' => $appName]
|
|
||||||
);
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод удаляет запись с избранными приложениями пользователя
|
|
||||||
*
|
|
||||||
* @param string $userLogin логин пользователя
|
|
||||||
* @return boolean
|
|
||||||
*/
|
|
||||||
public function delAllUserFavApp($userLogin)
|
|
||||||
{
|
|
||||||
Models\UserFavApp::where('user_login', $userLogin)->delete();
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод получает избранные приложения пользователя
|
|
||||||
*
|
|
||||||
* @param string $userLogin логин пользователя
|
|
||||||
* @return array
|
|
||||||
*/
|
|
||||||
public function getUserFavApp(string $userLogin): array
|
|
||||||
{
|
|
||||||
#Гаврилов
|
|
||||||
//ЗДЕСЬ ВМЕСТО DGAVRILOV ДОЛЖНО БЫТЬ ОБРАЩЕНИЕ К КУКАСАМ, ЧТОБЫ БРАТЬ ЛОГИН ОТТУДА
|
|
||||||
$userFavApp = Models\UserFavApp::where('user_login', $userLogin)->first();
|
|
||||||
|
|
||||||
return $userFavApp ? explode(';', $userFavApp['fav_apps']) : [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Http\Response;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
class TestController extends Controller
|
|
||||||
{
|
|
||||||
public function getRoles()
|
|
||||||
{
|
|
||||||
$roles = DB::connection('mysql')->table('arch_lk_access_list')->select(['*'])->get();
|
|
||||||
return view('roles', ['roles' => $roles]);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public function getAccess($id)
|
|
||||||
{
|
|
||||||
$roles = DB::connection('mysql')->table('arch_lk_access_list')->select(['*'])->where('access_id', '=', $id)->get();
|
|
||||||
$response = new Response(json_encode($roles[0]));
|
|
||||||
$response->header('Content-type', 'text/plain');
|
|
||||||
$response->header('Access-Control-Allow-Methods', 'POST');
|
|
||||||
|
|
||||||
return $response;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public function redirect()
|
|
||||||
{
|
|
||||||
// return redirect()->away('https://google.com');
|
|
||||||
//return redirect()->action([TestController::class, 'getAccess'], ['id' => 3]);
|
|
||||||
return redirect()->route('getAccessById', ['id' => 2]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getParam(Request $rqst)
|
|
||||||
{
|
|
||||||
//echo '<pre>'; var_dump($rqst->cookie('test_cookie')); echo'</pre>';
|
|
||||||
//return response('test')->cookie('test_cookie', $rqst->id);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function setRole(Request $rqst)
|
|
||||||
{
|
|
||||||
$lastInsert = DB::connection('mysql')->table('arch_lk_access_list')->insertGetId(['role' => $rqst->roleName, 'title' => $rqst->roleTitle]);
|
|
||||||
return redirect()->route('get_role');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function delRole(Request $rqst)
|
|
||||||
{
|
|
||||||
$lastInsert = DB::connection('mysql')->table('arch_lk_access_list')->where('access_id', '=', $rqst->access_id)->delete();
|
|
||||||
return redirect()->route('get_role');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use App\Models\TestData;
|
|
||||||
|
|
||||||
class TestDataController extends Controller
|
|
||||||
{
|
|
||||||
public function insertNewData(Request $rqst)
|
|
||||||
{
|
|
||||||
$model = new TestData;
|
|
||||||
$model->test_int = $rqst->int;
|
|
||||||
$model->test_char = $rqst->char;
|
|
||||||
|
|
||||||
$model->save();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
|
||||||
|
|
||||||
use App\Models\TestFormModel;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
|
|
||||||
class TestFormController extends Controller
|
|
||||||
{
|
|
||||||
public function getForm()
|
|
||||||
{
|
|
||||||
return view('test_form');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function setForm(Request $rqst)
|
|
||||||
{
|
|
||||||
$testTable = new TestFormModel;
|
|
||||||
$testTable->first_name = $rqst->first_name;
|
|
||||||
$testTable->last_name = $rqst->last_name;
|
|
||||||
$testTable->department_name = $rqst->department_name;
|
|
||||||
$testTable->save();
|
|
||||||
|
|
||||||
return redirect('/test_table');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http;
|
|
||||||
|
|
||||||
use App\Http\Middleware\CheckUserAppAccess;
|
|
||||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
|
||||||
|
|
||||||
class Kernel extends HttpKernel
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The application's global HTTP middleware stack.
|
|
||||||
*
|
|
||||||
* These middleware are run during every request to your application.
|
|
||||||
*
|
|
||||||
* @var array<int, class-string|string>
|
|
||||||
*/
|
|
||||||
protected $middleware = [
|
|
||||||
// \App\Http\Middleware\TrustHosts::class,
|
|
||||||
\App\Http\Middleware\TrustProxies::class,
|
|
||||||
\Illuminate\Http\Middleware\HandleCors::class,
|
|
||||||
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
|
|
||||||
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
|
|
||||||
\App\Http\Middleware\TrimStrings::class,
|
|
||||||
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
|
|
||||||
];
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The application's route middleware groups.
|
|
||||||
*
|
|
||||||
* @var array<string, array<int, class-string|string>>
|
|
||||||
*/
|
|
||||||
protected $middlewareGroups = [
|
|
||||||
'web' => [
|
|
||||||
\App\Http\Middleware\EncryptCookies::class,
|
|
||||||
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
|
||||||
\Illuminate\Session\Middleware\StartSession::class,
|
|
||||||
\App\Http\Middleware\AuthenticateMagic::class,
|
|
||||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
|
||||||
\App\Http\Middleware\VerifyCsrfToken::class,
|
|
||||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
|
||||||
],
|
|
||||||
|
|
||||||
'api' => [
|
|
||||||
\App\Http\Middleware\EncryptCookies::class,
|
|
||||||
//\Illuminate\Session\Middleware\StartSession::class,
|
|
||||||
//\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
|
|
||||||
'throttle:api',
|
|
||||||
//\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
|
||||||
//\Illuminate\Session\Middleware\AuthenticateSession::class, // Опционально
|
|
||||||
//\Illuminate\Auth\Middleware\Authenticate::class.':sanctum', // Глобальная аутентификация
|
|
||||||
//Кастомный посредник аутентификации, который наследует стандартному посреднику аутентификации с передачей guarda sanctum. Сначала в кастомном посреднике будет проведена аутентификация sanctum, если будет выброшена ошибка, она будет обработана кастомным посредником (с возвратом сообщения об ошибке и корректного статуса). Без этой реализации стандартный посредник аутентификации пытался редиректить на роут login, которого не должно быть при обращении к api ендпоинту
|
|
||||||
\App\Http\Middleware\AuthenticateMagicApi::class.':sanctum',
|
|
||||||
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
|
|
||||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The application's middleware aliases.
|
|
||||||
*
|
|
||||||
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
|
|
||||||
*
|
|
||||||
* @var array<string, class-string|string>
|
|
||||||
*/
|
|
||||||
protected $middlewareAliases = [
|
|
||||||
'auth' => \App\Http\Middleware\Authenticate::class,
|
|
||||||
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
|
|
||||||
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
|
|
||||||
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
|
|
||||||
'can' => \Illuminate\Auth\Middleware\Authorize::class,
|
|
||||||
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
|
|
||||||
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
|
|
||||||
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
|
|
||||||
'signed' => \App\Http\Middleware\ValidateSignature::class,
|
|
||||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
|
||||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
|
||||||
//Посредник проверки доступных ролей в приложении
|
|
||||||
'checkPermission' => \App\Http\Middleware\CheckUserPermission::class,
|
|
||||||
//Посредник проверки доступа к приложению
|
|
||||||
'checkAppAccess' => \App\Http\Middleware\CheckUserAppAccess::class,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
|
|
||||||
class Authenticate extends Middleware
|
|
||||||
{
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the path the user should be redirected to when they are not authenticated.
|
|
||||||
*/
|
|
||||||
protected function redirectTo(Request $request): ?string
|
|
||||||
{
|
|
||||||
return $request->expectsJson() ? null : route('login');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Closure;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Support\Facades\Auth;
|
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
|
||||||
use App\Facades\UserContext;
|
|
||||||
use App\Models\User;
|
|
||||||
use Illuminate\Support\Facades\Redis;
|
|
||||||
use Laravel\Sanctum\PersonalAccessToken;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Глобальный посредник аутентификации на платформе Magic для всех роутов платформы
|
|
||||||
*/
|
|
||||||
class AuthenticateMagic
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Handle an incoming request.
|
|
||||||
*
|
|
||||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
||||||
*/
|
|
||||||
public function handle(Request $request, Closure $next): Response
|
|
||||||
{
|
|
||||||
|
|
||||||
//TODO ПРОВЕРИТЬ
|
|
||||||
//Если сессия не стартовала возможно пользователь сразу обращается к api ендпоинту (ПРОВЕРИТЬ)
|
|
||||||
if (session()->isStarted()) {
|
|
||||||
if (session()->has('_auth_login')) {
|
|
||||||
//гаврилов. получение токена
|
|
||||||
// $token = $request->user();
|
|
||||||
// $userId = User::where('login', $token->getAttributes()['samaccountname'][0])->get()->toArray()[0]['id'];
|
|
||||||
// $tokenExpires = PersonalAccessToken::where('tokenable_id', $userId)->get()->toArray()[0]['expires_at'];
|
|
||||||
// echo '<pre>'; var_dump(new \DateTime($tokenExpires)); echo'</pre>';
|
|
||||||
// echo '<pre>'; var_dump(PersonalAccessToken::where('tokenable_id', $userId)->get()->toArray()[0]['expires_at']); echo'</pre>';
|
|
||||||
//Если токен истекает менее через 60 минут, продлеваем его на 2 часа. Ситуации, что сессия протухла, а токен продолжает жить не может случиться, так как апи запросы с фронта отправляют куку аутентификации, которая проверяется при $this->authenticate. Если она протухла, возвратится 401 ошибку.
|
|
||||||
// if ($token->expires_at->diffInMinutes(now()) < 60) {
|
|
||||||
// $token->update(
|
|
||||||
// [
|
|
||||||
// 'expires_at' => now()->addHours(2)
|
|
||||||
// ]
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
|
|
||||||
UserContext::setUserLogin(session()->get('_auth_login'));
|
|
||||||
$userGroups = session()->get('_auth_groups');
|
|
||||||
UserContext::setUserADGroups($userGroups);
|
|
||||||
UserContext::setUserEmails($userGroups);
|
|
||||||
UserContext::setIsAdminFlag(session()->get('is_admin'));
|
|
||||||
//На этапе посредника мы не проводим повторное определение ролей пользователя, это было сделано в LoginController в процессе авторизации после успешной аутентификации. Здесь мы уже берем его доступы из таблицы с токенами
|
|
||||||
$user = User::where('login', UserContext::getUserLogin())->first();
|
|
||||||
UserContext::setUserId($user->id);
|
|
||||||
UserContext::setUserAppPermissions($user->tokens()->latest()->first()->abilities['permissions']);
|
|
||||||
#Гаврилов
|
|
||||||
//ЧТО ЗА КОМАНДА НИЖЕ?
|
|
||||||
Redis::setex('notifications', 60, 123);
|
|
||||||
return $next($request);
|
|
||||||
} else {
|
|
||||||
//Получаем адрес предыдущей страницы, на которую хотел попасть пользователь, чтобы направить его после успешной аутентификации на этот адрес
|
|
||||||
$prevPageUrl = explode('/', $_SERVER['REDIRECT_URL']);
|
|
||||||
//Удаляем из URL редиректа пустые сегменты и сегмент с названием приложения (оно подставляется при редиректе само)
|
|
||||||
unset($prevPageUrl[0], $prevPageUrl[1]);
|
|
||||||
//Кладем в сессию адрес страницы. только если это не страница выхода, иначе после аутентификации пользователя сразу выбросит
|
|
||||||
session()->put('_auth_prev_page', implode('/', $prevPageUrl) == 'logout' ? '/menu' : implode('/', $prevPageUrl));
|
|
||||||
return redirect('/login');
|
|
||||||
//редирект на страницу login с сообщением об ошибке
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return redirect('/login');
|
|
||||||
//redirect на страницу login после которой точно сессия застартует, так как это webроут, а не api
|
|
||||||
}
|
|
||||||
// return $next($request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Кастомный посредник для обработки неудачной аутентификации Sanctum при обращении к api ендпоинтам. Стандартный посредник аутентификации пытается редиректить на роут login, чего быть не должно при работе с api
|
|
||||||
* @author dgavrilov
|
|
||||||
*/
|
|
||||||
|
|
||||||
namespace app\Http\Middleware;
|
|
||||||
|
|
||||||
use Closure;
|
|
||||||
use Illuminate\Auth\Middleware\Authenticate as BaseAuthenticate;
|
|
||||||
use Illuminate\Auth\AuthenticationException;
|
|
||||||
use App\Facades\UserContext;
|
|
||||||
|
|
||||||
class AuthenticateMagicApi extends BaseAuthenticate
|
|
||||||
{
|
|
||||||
public function handle($request, Closure $next, ...$guards)
|
|
||||||
{
|
|
||||||
// if ($request->is('api/silent_token_refresh')) {
|
|
||||||
// return $next($request);
|
|
||||||
// }
|
|
||||||
//Если пользователь в рамках сессии обращается к api ендпоинтам из приложения, он не всегда может установить заголовок с sanctum токеном (например, переходя по ссылкке <a href='.../api/delItem/id'>). В этом случае, проверяем куки и устанавливаем заголовок оттуда, так как при аутентификации пользовательский логин кладется в куки. Это позволяет нам не устанвливать заголовк в каждом fetch запросе на фронте
|
|
||||||
if ($request->is('api/*') && ($token = $request->cookie('sanctum_token'))) {
|
|
||||||
$request->headers->set("Authorization", "Bearer $token");
|
|
||||||
}
|
|
||||||
//Переопределяем поведение в случае возникновения ошибки при стандартной аутентификации. Стандартное поведение перебрасывает на страницу login, мы же возвращаем 401 ошибку, так как понимаем, что пользователь обратился по api
|
|
||||||
//DGAVRILOV. ПОВЕДЕНИЕ, ОПИСАННОЕ ВЫШЕ, ПРИВОДИТ К ОШИБКЕ. ЕСЛИ ПОЛЬЗОВАТЕЛЬ ОТПРАВИЛ API ЗАПРОС С ФРОНТА И ЕГО СЕССИЯ ПРОТУХЛА, ВОЗВРАЩАЕТСЯ 401 ОШИБКА ВО ВКЛАДКЕ NETWORK, НО ПОЛЬЗОВАТЕЛЯ НЕ ПЕРЕБРАСЫВАЕТ НА СТРАНИЦУ /LOGIN. ЕСЛИ ПОПРАВИТЬ ПОСРЕДНИК WEB АУТЕНТИФИКАЦИИ, ТО ЭТОЙ ПРОБЛЕМЫ НЕ БУДЕТ? БУДЕТ ПЕРЕБРАСЫВАТЬ НА СТРАНИЦУ LOGIN СО СТРАНИЦЫ, ОТКУДА СОВЕРЩАЛСЯ ВЫЗО API ЕНДПОИНТА? СКОРЕЕ ВСЕГО НЕТ, НУЖНО БУДЕТ ПРИ ВЫЗОВЕ API КАК-ТО ПЕРЕХВАТЫВАТЬ 401 ОШИБКУ И ОТПРАВЛЯТЬ НА СТРАНИЦУ /LOGIN
|
|
||||||
try {
|
|
||||||
//Стандартная аутентификация по санктум токену (проверяется срок жизни)
|
|
||||||
$this->authenticate($request, $guards);
|
|
||||||
//$token = $request->user()->currentAccessToken();
|
|
||||||
//Если токен истекает менее через 60 минут, продлеваем его на 2 часа. Ситуации, что сессия протухла, а токен продолжает жить не может случиться, так как апи запросы с фронта отправляют куку аутентификации, которая проверяется при $this->authenticate. Если она протухла, возвратится 401 ошибку.
|
|
||||||
// if ($token->expires_at->diffInMinutes(now()) < 60) {
|
|
||||||
// $token->update(
|
|
||||||
// [
|
|
||||||
// 'expires_at' => now()->addHours(2)
|
|
||||||
// ]
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
//После успешной аутентификации Sanctum обогащаем UserService параметрами пользователя (логин, роли приложения)
|
|
||||||
#Гаврилов
|
|
||||||
//ПОКА НЕ ДОБАВЛЯЮ ГРУППЫ AD B EMAILS, ТАК КАК В WEB КОНТУРЕ ОНИ ОПРЕДЕЛЯЮТСЯ ПРИ AD АУТЕНТИФИКАЦИИ И ПОЛУЧЕННЫЕ ЗНАЧЕНИЯ СКЛАДЫВАЮТСЯ В SESSION. В API КОНТУРЕ ДОСТУПА К СЕССИИ НЕТ - ПРОВОДИТЬ AD АУТЕНТИФИКАЦИЮ НЕ ПОЛУЧИТС БЕЗ ПАРОЛЯ ПОЛЬЗОВАТЕЛЯ, КОТОРЫЙ НИГДЕ НЕ ХРАНИТСЯ. ПОЭТОМУ, ЕСЛИ ПОНАДОБИТСЯ ДОСТАВАТЬ В API КОНТУРЕ ГРУППЫ ПОЛЬЗОВАТЕЛЯ, ПРИ AD АУТЕНТИФИКАЦИИ ПОНАДОБИТСЯ КЛАСТЬ AD ГРУППЫ ПОЛЬЗОВАТЕЛЯ И ЕГО EMAILS В ПОЛЕ ABILITIES ТАБЛИЦЫ PERSONAL ACCESS TOKENS ПО АНАЛОГИИ С PERISSIONS
|
|
||||||
#Гаврилов
|
|
||||||
//НУЖНО ЛИ ОБОГАЩАТЬ USERcoNTEXT НИЖЕ, ЕСЛИ ПРИ WEB АУТЕНТИФИКАЦИИ КОНТЕКСТ УЖЕ ДОЛЖЕН БЫЛ БЫТЬ ОБОГАЩЕН. вЕРОЯТНО, ЭТО НУЖНО ДЛЯ ОБРАБОТКИ ЧИСТО API ЗАПРОСОВ (БЕЗ ВХОДА В СИСТЕМУ), НО НАДО ПРОВЕРИТЬ
|
|
||||||
UserContext::setUserLogin($request->user()->login);
|
|
||||||
UserContext::setUserAppPermissions($request->user()->currentAccessToken()->abilities['permissions']);
|
|
||||||
} catch (AuthenticationException $auth) {
|
|
||||||
if ($request->is('api/*')) {
|
|
||||||
return response()->json([
|
|
||||||
#Гаврилов
|
|
||||||
//СКОРРЕКТИРУЙ ИНФОРМАЦИЮ О ВОЗВРАЩАЕМОЙ ОШИБКЕ?
|
|
||||||
'error' => 'Unauthenticated',
|
|
||||||
'message' => 'Invalid or missing authentication token'
|
|
||||||
], 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw $auth;
|
|
||||||
}
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Closure;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
|
||||||
use App\Facades\UserContext;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Посредник проверки доступа пользователя к приложению
|
|
||||||
*/
|
|
||||||
class CheckUserAppAccess
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Handle an incoming request.
|
|
||||||
*
|
|
||||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
||||||
*/
|
|
||||||
public function handle(Request $request, Closure $next): Response
|
|
||||||
{
|
|
||||||
$moduleName = explode('/', $request->route()->getPrefix());
|
|
||||||
$moduleName = end($moduleName) ?? null;
|
|
||||||
if ($moduleName) {
|
|
||||||
if (array_key_exists($moduleName, UserContext::getUserAppPermissions()) !== false) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//Если ошибка при обращении к api ендпоинту
|
|
||||||
if ($request->expectsJson()) {
|
|
||||||
return response()->json(['message' => "Ошибка! Приложение недоступно"], 403);
|
|
||||||
//Если ошибка при обращении к web роуту
|
|
||||||
} else {
|
|
||||||
#Гаврилов
|
|
||||||
//ЕСЛИ ВЫЗЫВАЕТСЯ WEB РОУТ НЕ С ФРОНТА, ТО ПРОИСХОДИТ РЕДИРЕКТ БЕЗ УКАЗАНИЯ ТЕКСТА ОШИБКИ. нАПРИМЕР, ПРИ РЕДИРЕКТЕ НИЖЕ НА СТРАНИЦУ МЕНЮ, ПОЛЬЗОВАТЕЛЬ НЕ УВИДИТ НИКАКОГО ОПОВЕЩЕНИЯ ОБ ОШИБКЕ.
|
|
||||||
return redirect('/menu');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Closure;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
|
||||||
use App\Models\User;
|
|
||||||
use App\Facades\UserContext;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Посредник проверки доступа пользовательской роли к роуту или ендпоинту
|
|
||||||
*/
|
|
||||||
class CheckUserPermission
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Handle an incoming request.
|
|
||||||
*
|
|
||||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
||||||
*/
|
|
||||||
public function handle(Request $request, Closure $next, string $requirement): Response
|
|
||||||
{
|
|
||||||
//Роли, которым доступен функционал
|
|
||||||
$accessRoles = explode(';', $requirement);
|
|
||||||
$userPermissions = UserContext::getUserAppPermissions();
|
|
||||||
//Всем роутам модуля добавляем префикс, поэтому можем ориентироваться на него, чтобы получить имя модуля, откуда пришел запрос
|
|
||||||
$moduleName = explode('/', $request->route()->getPrefix());
|
|
||||||
$moduleName = end($moduleName) ?? null;
|
|
||||||
|
|
||||||
if ($moduleName) {
|
|
||||||
if (array_key_exists($moduleName, UserContext::getUserAppPermissions()) !== false) {
|
|
||||||
if (in_array($userPermissions[$moduleName], $accessRoles)) {
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
// else {
|
|
||||||
// return redirect('/menu');
|
|
||||||
// #Гаврилов
|
|
||||||
// //РЕДИРЕКТ НА СТРАНИЦУ 403
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
// else {
|
|
||||||
// return redirect('/menu');
|
|
||||||
// #Гаврилов
|
|
||||||
// //РЕДИРЕКТ НА СТРАНИЦУ 403
|
|
||||||
// //redirect();
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
// else {
|
|
||||||
// return redirect('/menu');
|
|
||||||
// #Гаврилов
|
|
||||||
// //КУДА РЕДИРЕКТИТЬ или что возвращать, если имя модуля не определено?
|
|
||||||
// }
|
|
||||||
|
|
||||||
//Если ошибка при обращении к api ендпоинту
|
|
||||||
if ($request->expectsJson()) {
|
|
||||||
return response()->json(['message' => "Ошибка! Функционал недоступен для вашей роли"], 403);
|
|
||||||
//Если ошибка при обращении к web роуту
|
|
||||||
} else {
|
|
||||||
#Гаврилов
|
|
||||||
//ЕСЛИ ВЫЗЫВАЕТСЯ WEB РОУТ НЕ С ФРОНТА, ТО ПРОИСХОДИТ РЕДИРЕКТ БЕЗ УКАЗАНИЯ ТЕКСТА ОШИБКИ. нАПРИМЕР, ПРИ РЕДИРЕКТЕ НИЖЕ НА СТРАНИЦУ МЕНЮ, ПОЛЬЗОВАТЕЛЬ НЕ УВИДИТ НИКАКОГО ОПОВЕЩЕНИЯ ОБ ОШИБКЕ.
|
|
||||||
return redirect('/menu');
|
|
||||||
}
|
|
||||||
#Гаврилов
|
|
||||||
//РЕДИРЕКТ НА СТРАНИЦУ 403
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
|
|
||||||
|
|
||||||
class EncryptCookies extends Middleware
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The names of the cookies that should not be encrypted.
|
|
||||||
*
|
|
||||||
* @var array<int, string>
|
|
||||||
*/
|
|
||||||
protected $except = [
|
|
||||||
//
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
|
|
||||||
|
|
||||||
class PreventRequestsDuringMaintenance extends Middleware
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The URIs that should be reachable while maintenance mode is enabled.
|
|
||||||
*
|
|
||||||
* @var array<int, string>
|
|
||||||
*/
|
|
||||||
protected $except = [
|
|
||||||
//
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use App\Providers\RouteServiceProvider;
|
|
||||||
use Closure;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Support\Facades\Auth;
|
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
|
||||||
|
|
||||||
class RedirectIfAuthenticated
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Handle an incoming request.
|
|
||||||
*
|
|
||||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
||||||
*/
|
|
||||||
public function handle(Request $request, Closure $next, string ...$guards): Response
|
|
||||||
{
|
|
||||||
$guards = empty($guards) ? [null] : $guards;
|
|
||||||
|
|
||||||
foreach ($guards as $guard) {
|
|
||||||
if (Auth::guard($guard)->check()) {
|
|
||||||
return redirect(RouteServiceProvider::HOME);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $next($request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
|
|
||||||
|
|
||||||
class TrimStrings extends Middleware
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The names of the attributes that should not be trimmed.
|
|
||||||
*
|
|
||||||
* @var array<int, string>
|
|
||||||
*/
|
|
||||||
protected $except = [
|
|
||||||
'current_password',
|
|
||||||
'password',
|
|
||||||
'password_confirmation',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Illuminate\Http\Middleware\TrustHosts as Middleware;
|
|
||||||
|
|
||||||
class TrustHosts extends Middleware
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Get the host patterns that should be trusted.
|
|
||||||
*
|
|
||||||
* @return array<int, string|null>
|
|
||||||
*/
|
|
||||||
public function hosts(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
$this->allSubdomainsOfApplicationUrl(),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Illuminate\Http\Middleware\TrustProxies as Middleware;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
|
|
||||||
class TrustProxies extends Middleware
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The trusted proxies for this application.
|
|
||||||
*
|
|
||||||
* @var array<int, string>|string|null
|
|
||||||
*/
|
|
||||||
protected $proxies;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The headers that should be used to detect proxies.
|
|
||||||
*
|
|
||||||
* @var int
|
|
||||||
*/
|
|
||||||
protected $headers =
|
|
||||||
Request::HEADER_X_FORWARDED_FOR |
|
|
||||||
Request::HEADER_X_FORWARDED_HOST |
|
|
||||||
Request::HEADER_X_FORWARDED_PORT |
|
|
||||||
Request::HEADER_X_FORWARDED_PROTO |
|
|
||||||
Request::HEADER_X_FORWARDED_AWS_ELB;
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
|
|
||||||
|
|
||||||
class ValidateSignature extends Middleware
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The names of the query string parameters that should be ignored.
|
|
||||||
*
|
|
||||||
* @var array<int, string>
|
|
||||||
*/
|
|
||||||
protected $except = [
|
|
||||||
// 'fbclid',
|
|
||||||
// 'utm_campaign',
|
|
||||||
// 'utm_content',
|
|
||||||
// 'utm_medium',
|
|
||||||
// 'utm_source',
|
|
||||||
// 'utm_term',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
|
|
||||||
|
|
||||||
class VerifyCsrfToken extends Middleware
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The URIs that should be excluded from CSRF verification.
|
|
||||||
*
|
|
||||||
* @var array<int, string>
|
|
||||||
*/
|
|
||||||
protected $except = [
|
|
||||||
//
|
|
||||||
'/access/*',
|
|
||||||
'/access',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Job;
|
|
||||||
|
|
||||||
use Illuminate\Bus\Queueable;
|
|
||||||
use Illuminate\Queue\SerializesModels;
|
|
||||||
use Illuminate\Queue\InteractsWithQueue;
|
|
||||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
|
||||||
use Illuminate\Support\Facades\Log;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Базовый класс для выполнения джобы
|
|
||||||
*/
|
|
||||||
class BaseJob implements ShouldQueue
|
|
||||||
{
|
|
||||||
|
|
||||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод обработки ошибки при выполнении джобы
|
|
||||||
*
|
|
||||||
* @param \Throwable $th
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function failed(\Throwable $th): void
|
|
||||||
{
|
|
||||||
$context = [
|
|
||||||
//Скрипт откуда запустилась задача
|
|
||||||
'command' => static::class,
|
|
||||||
//Скрипт, в котором произошла ошибка
|
|
||||||
'file' => $th->getFile(),
|
|
||||||
'line' => $th->getLine(),
|
|
||||||
];
|
|
||||||
\Log::channel('job_err')->error($th->getMessage(), $context);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Mail;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Базовый класс объекта параметров отправляемого мэджиком писем
|
|
||||||
*/
|
|
||||||
class BaseMailerObj
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
public array $to, //адресаты письма
|
|
||||||
public string $subject, //тема письма
|
|
||||||
public string $body, //основной текст письма
|
|
||||||
public string $appName, //кто будет в копии
|
|
||||||
public array $copy = [], //шапка письма, например, для заголовка
|
|
||||||
public ?string $header = '', //подвал письма, например для технической информации
|
|
||||||
public ?string $footer = '', //название приложения назмещается под названием платформы Magic в футере письма
|
|
||||||
public string $mailLayout = 'mail\mailer_default', //используемый blade шаблон для отправки
|
|
||||||
){
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
#Гаврилов
|
|
||||||
//УДАЛИ ЕСЛИ НЕ ПОНАДОБИТСЯ
|
|
||||||
// /**
|
|
||||||
// * Фабричный метод для создания экземпляра родительского класса
|
|
||||||
// *
|
|
||||||
// * @param [type] $to
|
|
||||||
// * @param [type] $subject
|
|
||||||
// * @param [type] $body
|
|
||||||
// * @param [type] $appName
|
|
||||||
// * @param array $copy
|
|
||||||
// * @param string|null $header
|
|
||||||
// * @param string|null $footer
|
|
||||||
// * @param string $mailLayout
|
|
||||||
// * @return void
|
|
||||||
// */
|
|
||||||
// public static function create($to, $subject, $body, $appName, array $copy = [], ?string $header = '', ?string $footer = '', string $mailLayout = 'mail\mailer_default')
|
|
||||||
// {
|
|
||||||
// return new self(
|
|
||||||
// $to,
|
|
||||||
// $subject,
|
|
||||||
// $body,
|
|
||||||
// $appName,
|
|
||||||
// $copy,
|
|
||||||
// $header,
|
|
||||||
// $footer,
|
|
||||||
// $mailLayout
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Mail;
|
|
||||||
|
|
||||||
use Illuminate\Bus\Queueable;
|
|
||||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
||||||
use Illuminate\Mail\Mailable;
|
|
||||||
use Illuminate\Mail\Mailables\Content;
|
|
||||||
use Illuminate\Mail\Mailables\Envelope;
|
|
||||||
use Illuminate\Queue\SerializesModels;
|
|
||||||
use App\Mail\BaseMailerObj;
|
|
||||||
|
|
||||||
class Mailer extends Mailable
|
|
||||||
{
|
|
||||||
#Гаврилов
|
|
||||||
//ЗАЧЕМ ОНИ СЮДА ДОБАВИЛИСЬ? ТЕСТИРОВАЛ ОТПРАВКУ ОЧЕРЕДЕЙ? УДАЛИ ЕСЛИ НЕ НУЖНЫ ОТСЮДА И ИЗ USE
|
|
||||||
use Queueable, SerializesModels;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @var array данные для письма
|
|
||||||
*/
|
|
||||||
public $mailData;
|
|
||||||
/**
|
|
||||||
* @var string имя blade шаблона
|
|
||||||
*/
|
|
||||||
public $mailLayout;
|
|
||||||
/**
|
|
||||||
* @var string название приложения, которое отправляет сообщение
|
|
||||||
*/
|
|
||||||
public $appName;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Конструктор
|
|
||||||
*
|
|
||||||
* @param array $to - адресаты письма
|
|
||||||
* @param string $subject - тема письма
|
|
||||||
* @param string $body - основной текст письма
|
|
||||||
* @param array $copy - кто будет в копии
|
|
||||||
* @param string $header - шапка письма, например, для заголовка
|
|
||||||
* @param string $footer - подвал письма, например для технической информации
|
|
||||||
* @param string $appName название приложения назмещается под названием платформы Magic в футере письма
|
|
||||||
* @param string $mailLayout используемый blade шаблон для отправки
|
|
||||||
*/
|
|
||||||
public function __construct(BaseMailerObj $mailerObject)
|
|
||||||
{
|
|
||||||
//Преобразуем передаваемых адресатов, добавляя им логин
|
|
||||||
$this->mailData['to'] = $this->addDomain($mailerObject->to);
|
|
||||||
//$this->mailData['to'] = $to;
|
|
||||||
$this->mailData['copy'] = !empty($copy) ? $this->addDomain($mailerObject->copy) : [];
|
|
||||||
$this->mailData['subject'] = $mailerObject->subject;
|
|
||||||
$this->mailData['body'] = $mailerObject->body;
|
|
||||||
$this->mailData['header'] = $mailerObject->header;
|
|
||||||
$this->mailData['footer'] = $mailerObject->footer;
|
|
||||||
$this->checkTestEnv();
|
|
||||||
$this->appName = $mailerObject->appName;
|
|
||||||
$this->mailLayout = $mailerObject->mailLayout;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Метод корректирует свойства отправляемого письма, если среда разработки тестовая
|
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
private function checkTestEnv()
|
|
||||||
{
|
|
||||||
//Если тестировщик аутентифицирован, берется его логин из сессии, в противном случае берется закрепленный в глобальных конфигах тестовый адрес (который разработчик указывает для своего локального тестирования сам). Можно в будущем улучшить логику с определением тестового емейла, например, передавая к api ендпоинту заголовок с тестовым емейлом, но на старте пока так
|
|
||||||
// if (auth()->user()->login) {
|
|
||||||
if (session()->has('_auth_login')) {
|
|
||||||
$userLogin = session()->get('_auth_login');
|
|
||||||
} else {
|
|
||||||
$userLogin = config('app.mail_test_addressee');
|
|
||||||
}
|
|
||||||
// echo '<pre>'; var_dump($userLogin); echo'</pre>';
|
|
||||||
// $test = config('app.test_env');
|
|
||||||
// $test2 = config('app.mail_test_addressee');
|
|
||||||
// echo '<pre>'; var_dump($test); echo'</pre>';
|
|
||||||
// echo '<pre>'; var_dump($test2); echo'</pre>';
|
|
||||||
//}
|
|
||||||
// $userLogin = auth()->user()->login ? auth()->user()->login : (session()->has('_auth_login') ? session()->get('_auth_login')) : config('MAIL_TEST_ADRESSEE');
|
|
||||||
//Если работаем из под тестовой среды
|
|
||||||
if (config('app.test_env')) {
|
|
||||||
//Информация для тестирования будет добавлена в футер сообщения. В нее включаем информацию об адресатах и копии, если бы письмо отправлялось на проде
|
|
||||||
$testInfo = "На проде письмо отправится: " . implode(", ", $this->mailData['to']) . ". В копии: " . implode(", ", $this->mailData['copy']);
|
|
||||||
$this->mailData['footer'] .= $testInfo;
|
|
||||||
//Копию очищаем
|
|
||||||
$this->cc('');
|
|
||||||
//echo '<pre>'; var_dump(['dgavrilov@rencredit.ru']); echo'</pre>';
|
|
||||||
//echo '<pre>'; var_dump($this->addDomain([$userLogin])); echo'</pre>';
|
|
||||||
$this->to($this->addDomain([$userLogin]));
|
|
||||||
//$this->to(['dgavrilov@rencredit.ru']);
|
|
||||||
} else {
|
|
||||||
//ГАВРИЛОВ. ДОБАВЬ ДОМЕН К ЛОГИНАМ
|
|
||||||
$this->to($this->mailData['to']);
|
|
||||||
$this->to($this->mailData['copy']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Хэлпер преобразует всех адресатов, добавляя им почтовый домен
|
|
||||||
*
|
|
||||||
* @param array $addresseesArr адресаты
|
|
||||||
* @return array
|
|
||||||
*/
|
|
||||||
private function addDomain(array $addresseesArr): array
|
|
||||||
{
|
|
||||||
$domain = config('mail.mail_domain');
|
|
||||||
|
|
||||||
return array_map(function($el) use($domain) {return $el . "@" . $domain;}, $addresseesArr);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the message envelope.
|
|
||||||
*/
|
|
||||||
public function envelope(): Envelope
|
|
||||||
{
|
|
||||||
return new Envelope(
|
|
||||||
subject: $this->mailData['subject'],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the message content definition.
|
|
||||||
*/
|
|
||||||
public function content(): Content
|
|
||||||
{
|
|
||||||
return new Content(
|
|
||||||
// view: 'view.name',
|
|
||||||
view: $this->mailLayout,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the attachments for the message.
|
|
||||||
*
|
|
||||||
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
|
|
||||||
*/
|
|
||||||
public function attachments(): array
|
|
||||||
{
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
|
|
||||||
class AccessModel extends Model
|
|
||||||
{
|
|
||||||
use HasFactory;
|
|
||||||
|
|
||||||
protected $connection = 'mysql';
|
|
||||||
protected $table = 'tm_lk_access_list';
|
|
||||||
public $timestamps = false;
|
|
||||||
protected $primaryKey = 'access_id';
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
use App\Models\MagicApps;
|
|
||||||
|
|
||||||
class AppRoles extends Model
|
|
||||||
{
|
|
||||||
protected $table = 'app_roles';
|
|
||||||
use HasFactory;
|
|
||||||
|
|
||||||
public function magicApp()
|
|
||||||
{
|
|
||||||
return $this->belongsTo(MagicApps::class, 'app_id', 'id');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
use App\Models\AppRoles;
|
|
||||||
|
|
||||||
class MagicApps extends Model
|
|
||||||
{
|
|
||||||
protected $table = 'magic_apps';
|
|
||||||
use HasFactory;
|
|
||||||
|
|
||||||
public function appRoles()
|
|
||||||
{
|
|
||||||
return $this->hasMany(AppRoles::class, 'app_id', 'id')
|
|
||||||
->orderBy('role_priority', 'asc');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
|
|
||||||
class TestData extends Model
|
|
||||||
{
|
|
||||||
use HasFactory;
|
|
||||||
protected $table = 'test_data';
|
|
||||||
protected $connection = 'mysql';
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
|
|
||||||
class TestFormModel extends Model
|
|
||||||
{
|
|
||||||
use HasFactory;
|
|
||||||
|
|
||||||
protected $connection = 'mysql';
|
|
||||||
}
|
|
||||||
+17
-19
@@ -6,45 +6,43 @@ namespace App\Models;
|
|||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||||
use Illuminate\Notifications\Notifiable;
|
use Illuminate\Notifications\Notifiable;
|
||||||
use Laravel\Sanctum\HasApiTokens;
|
|
||||||
|
|
||||||
class User extends Authenticatable
|
class User extends Authenticatable
|
||||||
{
|
{
|
||||||
use HasApiTokens, HasFactory, Notifiable;
|
/** @use HasFactory<\Database\Factories\UserFactory> */
|
||||||
|
use HasFactory, Notifiable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The attributes that are mass assignable.
|
* The attributes that are mass assignable.
|
||||||
*
|
*
|
||||||
* @var array<int, string>
|
* @var list<string>
|
||||||
*/
|
*/
|
||||||
// protected $fillable = [
|
|
||||||
// 'name',
|
|
||||||
// 'email',
|
|
||||||
// 'password',
|
|
||||||
// ];
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'login',
|
'name',
|
||||||
|
'email',
|
||||||
|
'password',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The attributes that should be hidden for serialization.
|
* The attributes that should be hidden for serialization.
|
||||||
*
|
*
|
||||||
* @var array<int, string>
|
* @var list<string>
|
||||||
*/
|
*/
|
||||||
// protected $hidden = [
|
protected $hidden = [
|
||||||
// 'password',
|
'password',
|
||||||
// 'remember_token',
|
'remember_token',
|
||||||
// ];
|
];
|
||||||
protected $hidden = [];
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The attributes that should be cast.
|
* Get the attributes that should be cast.
|
||||||
*
|
*
|
||||||
* @var array<string, string>
|
* @return array<string, string>
|
||||||
*/
|
*/
|
||||||
protected $casts = [
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
'email_verified_at' => 'datetime',
|
'email_verified_at' => 'datetime',
|
||||||
'password' => 'hashed',
|
'password' => 'hashed',
|
||||||
];
|
];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
|
|
||||||
class UserFavApp extends Model
|
|
||||||
{
|
|
||||||
use HasFactory;
|
|
||||||
|
|
||||||
public $incrementing = true;
|
|
||||||
public $timestamps = true;
|
|
||||||
protected $table = 'user_fav_app';
|
|
||||||
protected $connection = "mysql";
|
|
||||||
protected $fillable = ['user_login', 'fav_apps'];
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Providers;
|
|
||||||
|
|
||||||
use Illuminate\Support\ServiceProvider;
|
|
||||||
use App\Services\ApiResponder;
|
|
||||||
|
|
||||||
class ApiResponderProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Register services.
|
|
||||||
*/
|
|
||||||
public function register(): void
|
|
||||||
{
|
|
||||||
$this->app->bind(ApiResponder::class, function($app){
|
|
||||||
return new ApiResponder();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bootstrap services.
|
|
||||||
*/
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,9 +3,6 @@
|
|||||||
namespace App\Providers;
|
namespace App\Providers;
|
||||||
|
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
use Spatie\Activitylog\Facades\CauserResolver;
|
|
||||||
use Illuminate\Support\Facades\View;
|
|
||||||
use App\Services\ModuleService;
|
|
||||||
|
|
||||||
class AppServiceProvider extends ServiceProvider
|
class AppServiceProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
@@ -14,8 +11,7 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
*/
|
*/
|
||||||
public function register(): void
|
public function register(): void
|
||||||
{
|
{
|
||||||
//Регистрируем передачу во все blade шаблоны функционал сервиса по определению имени модуля из текущего роута
|
//
|
||||||
View::share('moduleName', app(ModuleService::class));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,8 +19,6 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
*/
|
*/
|
||||||
public function boot(): void
|
public function boot(): void
|
||||||
{
|
{
|
||||||
// Глобально отключаем определение causer для корректной работы пакета activity_log. По умолчанию пакет ожидает получить экземпляр модели Models\User для прописывания в таблицу activity_log значения causer_type и causer_id. Эти значения нельзя руками прописать при логировании. Никакие танцы с бубнами не помогали кроме строки ниже. Данные по инициатору изменения решил записывать в поле properties
|
//
|
||||||
//UPD: Решил отказаться, так как все равно для корректной работы аутентификации пришел к фиксации записи в модели users, для отображения истории бизнес-сущностей удобнее будет получать пользователя, совершившего действие, из отдельного поля в модели, а не парсить json из поля properties
|
|
||||||
// CauserResolver::resolveUsing(fn () => null);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Providers;
|
|
||||||
|
|
||||||
// use Illuminate\Support\Facades\Gate;
|
|
||||||
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Провайдер для регистрации сервиса аутентификации
|
|
||||||
*/
|
|
||||||
class AuthServiceProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The model to policy mappings for the application.
|
|
||||||
*
|
|
||||||
* @var array<class-string, class-string>
|
|
||||||
*/
|
|
||||||
protected $policies = [
|
|
||||||
//
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register any authentication / authorization services.
|
|
||||||
*/
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Providers;
|
|
||||||
|
|
||||||
use Illuminate\Support\ServiceProvider;
|
|
||||||
use App\Services\AuthorizationService;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Провайдер для регистрации сервиса авторизации
|
|
||||||
*/
|
|
||||||
class AuthorizationServiceProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Register services.
|
|
||||||
*/
|
|
||||||
public function register(): void
|
|
||||||
{
|
|
||||||
$this->app->bind(AuthorizationService::class, function($app) {
|
|
||||||
return new AuthorizationService();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bootstrap services.
|
|
||||||
*/
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Providers;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Broadcast;
|
|
||||||
use Illuminate\Support\ServiceProvider;
|
|
||||||
|
|
||||||
class BroadcastServiceProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Bootstrap any application services.
|
|
||||||
*/
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
Broadcast::routes();
|
|
||||||
|
|
||||||
require base_path('routes/channels.php');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Providers;
|
|
||||||
|
|
||||||
use Illuminate\Auth\Events\Registered;
|
|
||||||
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
|
|
||||||
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
|
|
||||||
use Illuminate\Support\Facades\Event;
|
|
||||||
|
|
||||||
class EventServiceProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The event to listener mappings for the application.
|
|
||||||
*
|
|
||||||
* @var array<class-string, array<int, class-string>>
|
|
||||||
*/
|
|
||||||
protected $listen = [
|
|
||||||
Registered::class => [
|
|
||||||
SendEmailVerificationNotification::class,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register any events for your application.
|
|
||||||
*/
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine if events and listeners should be automatically discovered.
|
|
||||||
*/
|
|
||||||
public function shouldDiscoverEvents(): bool
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Providers;
|
|
||||||
|
|
||||||
use App\Services\RedisNotificationService;
|
|
||||||
use Illuminate\Support\ServiceProvider;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Провайдер для работы с сервисом Redis для хранения нотификаций для отображения на фронте
|
|
||||||
*/
|
|
||||||
class RedisNotificationProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Register services.
|
|
||||||
*/
|
|
||||||
public function register(): void
|
|
||||||
{
|
|
||||||
$this->app->bind(RedisNotificationService::class, function($app){
|
|
||||||
return new RedisNotificationService;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bootstrap services.
|
|
||||||
*/
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user