Compare commits
5 Commits
auth
..
469ebc8aaf
| Author | SHA1 | Date | |
|---|---|---|---|
| 469ebc8aaf | |||
| d53a9e6274 | |||
| ec04ae8d69 | |||
| feb2b840eb | |||
| 9766a1afad |
@@ -0,0 +1,30 @@
|
|||||||
|
<?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,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,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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,246 +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');
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
#Гаврилов
|
|
||||||
//РАЗНЕСИ ЛОГИКУ МЕЖДУ МЕТОДАМИ, А ТО ПОКА ВСЯ ЛОГИКА В ОДНОМ МЕТОД LDAPCHECK
|
|
||||||
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,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,73 +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 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']);
|
|
||||||
#Гаврилов
|
|
||||||
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,43 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
|
||||||
|
|
||||||
use Closure;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
|
||||||
use App\Facades\UserContext;
|
|
||||||
|
|
||||||
//ЭТОТ ПОСРЕДНИК ПРИМЕНЯЕТСЯ В WEB РОУТАХ И В API ЕНДПОИНТАХ ПОКА ТОЛЬКО ПРИЛОЖЕНИЯ ТАКСИ, НО ПО ЛОГИКЕ, ЕГО НУЖНО ИСПОЛЬЗОВАТЬ ВО ВСЕХ БУДУЩИХ МОДУЛЯХ. С ЕГО ПОМОЩЬЮ ПРОВЕРЯЕТСЯ КАЖДЫЙ ЗАПРОС К МОДУЛЮ - ВООБЩЕ ЕСТЬ ДОСТУП У ПОЛЬЗОВАТЕЛЯ ИЛИ НЕТ
|
|
||||||
//В KERNEL У ЭТОГО ПОСРЕДНИКА ПРОПИСАН АЛИАС, КОТОРЫЙ УКАЗЫВАЕТСЯ УЖЕ В MODULE/ROUTES/WEB.PHP И API.PHP
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Посредник проверки доступа пользователя к приложению
|
|
||||||
*/
|
|
||||||
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 РОУТ НЕ С ФРОНТА, ТО ПРОИСХОДИТ РЕДИРЕКТ БЕЗ УКАЗАНИЯ ТЕКСТА ОШИБКИ. нАПРИМЕР, ПРИ РЕДИРЕКТЕ НИЖЕ НА СТРАНИЦУ МЕНЮ, ПОЛЬЗОВАТЕЛЬ НЕ УВИДИТ НИКАКОГО ОПОВЕЩЕНИЯ ОБ ОШИБКЕ
|
|
||||||
//ЭТУ ПРОБЛЕМУ Я ИСПРАВЛЯЛ, ЧЕРЕЗ ГЕНЕРАЦИЮ НОТИФИКАЦИЙ НА БЭКЕ И ДОБАВЛЕНИЯ ИХ В ОПРЕДЕЛЕННУЮ ОЧЕРЕДЬ REDIS, КОТОРУЮ ЧИТАЕТ КАЖДАЯ СТРАНИЦА ПРИ ПЕРВИЧНОМ РЕНДЕРИНГЕ. НАДО ПОСМОТРЕТЬ ГДЕ Я УЖЕ ТАКОЕ РЕАЛИЗОВЫВАЛ
|
|
||||||
return redirect('/menu');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,67 +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 РОУТ НЕ С ФРОНТА, ТО ПРОИСХОДИТ РЕДИРЕКТ БЕЗ УКАЗАНИЯ ТЕКСТА ОШИБКИ. нАПРИМЕР, ПРИ РЕДИРЕКТЕ НИЖЕ НА СТРАНИЦУ МЕНЮ, ПОЛЬЗОВАТЕЛЬ НЕ УВИДИТ НИКАКОГО ОПОВЕЩЕНИЯ ОБ ОШИБКЕ.
|
|
||||||
//ЭТУ ПРОБЛЕМУ Я ИСПРАВЛЯЛ, ЧЕРЕЗ ГЕНЕРАЦИЮ НОТИФИКАЦИЙ НА БЭКЕ И ДОБАВЛЕНИЯ ИХ В ОПРЕДЕЛЕННУЮ ОЧЕРЕДЬ REDIS, КОТОРУЮ ЧИТАЕТ КАЖДАЯ СТРАНИЦА ПРИ ПЕРВИЧНОМ РЕНДЕРИНГЕ. НАДО ПОСМОТРЕТЬ ГДЕ Я УЖЕ ТАКОЕ РЕАЛИЗОВЫВАЛ
|
|
||||||
return redirect('/menu');
|
|
||||||
}
|
|
||||||
#Гаврилов
|
|
||||||
//РЕДИРЕКТ НА СТРАНИЦУ 403
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
+20
-22
@@ -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
|
||||||
'email_verified_at' => 'datetime',
|
{
|
||||||
'password' => 'hashed',
|
return [
|
||||||
];
|
'email_verified_at' => 'datetime',
|
||||||
|
'password' => 'hashed',
|
||||||
|
];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Providers;
|
||||||
|
|
||||||
|
use Illuminate\Cache\RateLimiting\Limit;
|
||||||
|
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\RateLimiter;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
class RouteServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The path to your application's "home" route.
|
||||||
|
*
|
||||||
|
* Typically, users are redirected here after authentication.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
public const HOME = '/home';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Define your route model bindings, pattern filters, and other route configuration.
|
||||||
|
*/
|
||||||
|
public function boot(): void
|
||||||
|
{
|
||||||
|
RateLimiter::for('api', function (Request $request) {
|
||||||
|
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->routes(function () {
|
||||||
|
Route::middleware('api')
|
||||||
|
->prefix('api')
|
||||||
|
->group(base_path('routes/api.php'));
|
||||||
|
|
||||||
|
Route::middleware('web')
|
||||||
|
->group(base_path('routes/web.php'));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Providers;
|
|
||||||
|
|
||||||
use Illuminate\Support\ServiceProvider;
|
|
||||||
use App\Services\UserService;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Провайдер для регистрации сервиса работы с данными юзера (установка логина, групп, подмена значений в случае работы на тестовой среде)
|
|
||||||
*/
|
|
||||||
class UserServiceProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Register services.
|
|
||||||
*/
|
|
||||||
public function register(): void
|
|
||||||
{
|
|
||||||
$this->app->singleton(UserService::class, function($app){
|
|
||||||
return new UserService;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bootstrap services.
|
|
||||||
*/
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Services;
|
|
||||||
|
|
||||||
use App\Models\MagicApps;
|
|
||||||
use App\Facades\UserContext;
|
|
||||||
|
|
||||||
class AuthorizationService
|
|
||||||
{
|
|
||||||
private $appWithRoles;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получаем приложения вместе с ролями
|
|
||||||
*
|
|
||||||
* @return array
|
|
||||||
*/
|
|
||||||
public function getUserAppPermissions(): array
|
|
||||||
{
|
|
||||||
$this->appWithRoles = MagicApps::with('appRoles')->get()->toArray();
|
|
||||||
//Итоговый массив с доступами пользователя к приложению и ролью
|
|
||||||
$userAppAccess = [];
|
|
||||||
foreach ($this->appWithRoles as $appData) {
|
|
||||||
//Определяем по какому массиву проверять доступ к приложению - почтовые рассылки или группы AD
|
|
||||||
if (empty($appData['access_groups_email'])) {
|
|
||||||
$appAccess = explode(';', $appData['access_groups_ad']);
|
|
||||||
$userAccessGroups = UserContext::getUserADGroups();
|
|
||||||
} else {
|
|
||||||
$appAccess = explode(';', $appData['access_groups_email']);
|
|
||||||
$userAccessGroups = UserContext::getUserEmails();
|
|
||||||
}
|
|
||||||
//Если пересечения групп доступа приложения и групп доступа пользователя отсутствуют, считаем, что доступа нет
|
|
||||||
if (empty(array_intersect($appAccess, $userAccessGroups))) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
//Если ролевая модель отсутствует для приложения как таковая, прописывам значение null
|
|
||||||
if (empty($appData['app_roles'])) {
|
|
||||||
$userAppAccess[$appData['app_name']] = null;
|
|
||||||
} else {
|
|
||||||
//Если ролевая модель существует, ставим значение false, которое будет заменено ролью пользователя. Сохранение false на выходе, в свою очередь, сигнализирует, что роль пользователя не определилась
|
|
||||||
$userAppAccess[$appData['app_name']] = false;
|
|
||||||
foreach ($appData['app_roles'] as $roleData) {
|
|
||||||
if($this->checkRoleAccess($appData['role_driver'], explode(';', $roleData['role_access']))) {
|
|
||||||
$userAppAccess[$appData['app_name']] = $roleData['app_role'];
|
|
||||||
//Все роли идут по приоритету важности, поэтому останавливаемся на самой важной и возвращаем ее, остальные роли не перебираем. Я пока не уверен как лучше организовать отображение функционала ролей в приложениях: весь нужный функционал "класть" в одну роль и отображать строго тот функционал, который относится к роли. Или распределять функционал между ролями и, если пользователь входит в несколько ролей, отображать весь функционал всех ролей, куда он может входить. В случае последнего варианта, нужно будет хранить все доступные роли пользователя, а не только самую важную по приортету.
|
|
||||||
//Также пока непонятно, реализовывать ли возможность переключаться между ролями на продакшн среде. Если реализовывать, так же придется хранить все роли, куда входит пользователь. Но в этом случае есть риски запутаться в логировании, например, если пользователь под ролью админ переключится на пользователя юзер и совершит от него действие
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $userAppAccess;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Возвращаем результат проверки доступности роли
|
|
||||||
*
|
|
||||||
* @param string $roleAccessDriver название драйвера доступа роли
|
|
||||||
* @param array $roleData массив с перечисленными рассылками/логинами/группами, которым доступна роль
|
|
||||||
* @return bool
|
|
||||||
*/
|
|
||||||
public function checkRoleAccess(string $roleAccessDriver, array $roleData): bool
|
|
||||||
{
|
|
||||||
switch ($roleAccessDriver) {
|
|
||||||
case 'login':
|
|
||||||
return in_array(UserContext::getUserLogin(), $roleData);
|
|
||||||
break;
|
|
||||||
case 'email':
|
|
||||||
return !empty(array_intersect(UserContext::getUserEmails(), $roleData));
|
|
||||||
break;
|
|
||||||
case 'ADgroup':
|
|
||||||
return !empty(array_intersect(UserContext::getUserADGroups(), $roleData));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//УДАЛИТЬ
|
|
||||||
// public function getUserAppRoles(array $userGroups)
|
|
||||||
// {
|
|
||||||
// $userEmails = session()->get('_auth_groups');
|
|
||||||
// $userLogin = session()->get('_auth_login');
|
|
||||||
// $magicApps = $this->getAppRoles();
|
|
||||||
// }
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,198 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Services;
|
|
||||||
|
|
||||||
use Exception;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Сервис работы с данными юзера (установка/получение логина, групп, подмена значений в случае работы на тестовой среде)
|
|
||||||
*/
|
|
||||||
class UserService
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* @var string пользовательский логин
|
|
||||||
*/
|
|
||||||
public string $userLogin;
|
|
||||||
/**
|
|
||||||
* @var array пользовательские группы AD
|
|
||||||
*/
|
|
||||||
public array $userADGroups;
|
|
||||||
/**
|
|
||||||
* @var array почтовые рассылки куда входит пользователь
|
|
||||||
*/
|
|
||||||
public array $userEmails;
|
|
||||||
/**
|
|
||||||
* @var boolean является ли пользователь админом приложения Magic
|
|
||||||
*/
|
|
||||||
public bool $isAdmin;
|
|
||||||
/**
|
|
||||||
* @var array доступы пользователя к приложениям
|
|
||||||
*/
|
|
||||||
public array $userAppPermissions;
|
|
||||||
/**
|
|
||||||
* @var int идентификатор пользователя из таблицы users
|
|
||||||
*/
|
|
||||||
public int $userId;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Установка пользовательского логина
|
|
||||||
*
|
|
||||||
* @param string $login логин для подмены превоначального значения, взятого из сессии
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function setUserLogin(string $login): void
|
|
||||||
{
|
|
||||||
$this->userLogin = $login;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Установка пользовательского логина
|
|
||||||
*
|
|
||||||
* @param array $appRoles доступы пользователя к приложениям Magic
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function setUserAppPermissions(array $appRoles): void
|
|
||||||
{
|
|
||||||
$this->userAppPermissions = $appRoles;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Установка пользовательского идентификатора из таблицы users
|
|
||||||
*
|
|
||||||
* @param int $userId идентификатор пользователя
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function setUserId(int $userId): void
|
|
||||||
{
|
|
||||||
$this->userId = $userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Установка групп AD пользователя
|
|
||||||
*
|
|
||||||
* @param array $userGroups все группы из AD где состоит пользователь (emails, AD и т.д.)
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function setUserADGroups(array $userGroups): void
|
|
||||||
{
|
|
||||||
$this->userADGroups = array_filter($userGroups, function($el){return substr($el, 0, 1) !== '#';});
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Установка почтовых рассылок куда входит пользователь
|
|
||||||
*
|
|
||||||
* @param array $userGroups все групы пользователя AD, в которых он состоит (почтовые ящики, AD и т.д.)
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function setUserEmails(array $userGroups): void
|
|
||||||
{
|
|
||||||
$this->userEmails = array_filter($userGroups, function($el){return substr($el, 0, 1) === '#';});
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Устанавливаем флаг является ли пользователь админом приложения Magic
|
|
||||||
*
|
|
||||||
* @param boolean $flag
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function setIsAdminFlag(bool $flag): void
|
|
||||||
{
|
|
||||||
$this->isAdmin = $flag;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Добавление группы AD в массив групп пользователя
|
|
||||||
*
|
|
||||||
* @param string $group группа для добавления в массив установленных при аутентификации групп AD пользователя
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function addUserADGroup(string $group): void
|
|
||||||
{
|
|
||||||
$this->userADGroups[] = $group;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Добавление email в массив емейлов пользователя
|
|
||||||
*
|
|
||||||
* @param string $email почтовая рассылка для добавления в массив установленных при аутентификации почтовых ящиков пользователя
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function addUserEmail(string $email): void
|
|
||||||
{
|
|
||||||
$this->userEmails[] = $email;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Возвращаем доступы пользователя к приложениям Magic
|
|
||||||
*
|
|
||||||
* @return array
|
|
||||||
*/
|
|
||||||
public function getUserAppPermissions(): array
|
|
||||||
{
|
|
||||||
return $this->userAppPermissions;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получаем пользовательский логин
|
|
||||||
*
|
|
||||||
* @return string
|
|
||||||
*/
|
|
||||||
public function getUserLogin(): string
|
|
||||||
{
|
|
||||||
return $this->userLogin;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получаем пользовательский логин
|
|
||||||
*
|
|
||||||
* @return int
|
|
||||||
*/
|
|
||||||
public function getUserId(): int
|
|
||||||
{
|
|
||||||
return $this->userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получаем пользовательский логин
|
|
||||||
*
|
|
||||||
* @return array
|
|
||||||
*/
|
|
||||||
public function getUserADGroups(): array
|
|
||||||
{
|
|
||||||
return $this->userADGroups;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получаем email рассылки куда он входит
|
|
||||||
*
|
|
||||||
* @return array
|
|
||||||
*/
|
|
||||||
public function getUserEmails(): array
|
|
||||||
{
|
|
||||||
return $this->userEmails;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получаем значение флага является ли пользователь админом приложения Magic
|
|
||||||
*
|
|
||||||
* @return boolean
|
|
||||||
*/
|
|
||||||
public function getIsAdminFlag(): bool
|
|
||||||
{
|
|
||||||
return $this->isAdmin;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
+19
-28
@@ -7,15 +7,15 @@ return [
|
|||||||
| Authentication Defaults
|
| Authentication Defaults
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
|
||||||
| This option controls the default authentication "guard" and password
|
| This option defines the default authentication "guard" and password
|
||||||
| reset options for your application. You may change these defaults
|
| reset "broker" for your application. You may change these values
|
||||||
| as required, but they're a perfect start for most applications.
|
| as required, but they're a perfect start for most applications.
|
||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
'defaults' => [
|
'defaults' => [
|
||||||
'guard' => 'web',
|
'guard' => env('AUTH_GUARD', 'web'),
|
||||||
'passwords' => 'users',
|
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
|
||||||
],
|
],
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -25,11 +25,11 @@ return [
|
|||||||
|
|
|
|
||||||
| Next, you may define every authentication guard for your application.
|
| Next, you may define every authentication guard for your application.
|
||||||
| Of course, a great default configuration has been defined for you
|
| Of course, a great default configuration has been defined for you
|
||||||
| here which uses session storage and the Eloquent user provider.
|
| which utilizes session storage plus the Eloquent user provider.
|
||||||
|
|
|
|
||||||
| All authentication drivers have a user provider. This defines how the
|
| All authentication guards have a user provider, which defines how the
|
||||||
| users are actually retrieved out of your database or other storage
|
| users are actually retrieved out of your database or other storage
|
||||||
| mechanisms used by this application to persist your user's data.
|
| system used by the application. Typically, Eloquent is utilized.
|
||||||
|
|
|
|
||||||
| Supported: "session"
|
| Supported: "session"
|
||||||
|
|
|
|
||||||
@@ -38,11 +38,6 @@ return [
|
|||||||
'guards' => [
|
'guards' => [
|
||||||
'web' => [
|
'web' => [
|
||||||
'driver' => 'session',
|
'driver' => 'session',
|
||||||
'provider' => 'ldap',
|
|
||||||
],
|
|
||||||
// guard для аутентификации при запросе ендпоинтов API, а также для нормального логирования информации события обращения к API ендпоинтам
|
|
||||||
'sanctum' => [
|
|
||||||
'driver' => 'sanctum',
|
|
||||||
'provider' => 'users',
|
'provider' => 'users',
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
@@ -52,12 +47,12 @@ return [
|
|||||||
| User Providers
|
| User Providers
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
|
||||||
| All authentication drivers have a user provider. This defines how the
|
| All authentication guards have a user provider, which defines how the
|
||||||
| users are actually retrieved out of your database or other storage
|
| users are actually retrieved out of your database or other storage
|
||||||
| mechanisms used by this application to persist your user's data.
|
| system used by the application. Typically, Eloquent is utilized.
|
||||||
|
|
|
|
||||||
| If you have multiple user tables or models you may configure multiple
|
| If you have multiple user tables or models you may configure multiple
|
||||||
| sources which represent each model / table. These sources may then
|
| providers to represent the model / table. These providers may then
|
||||||
| be assigned to any extra authentication guards you have defined.
|
| be assigned to any extra authentication guards you have defined.
|
||||||
|
|
|
|
||||||
| Supported: "database", "eloquent"
|
| Supported: "database", "eloquent"
|
||||||
@@ -65,15 +60,11 @@ return [
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
'providers' => [
|
'providers' => [
|
||||||
'ldap' => [
|
|
||||||
'driver' => 'ldap',
|
|
||||||
'model' => LdapRecord\Models\ActiveDirectory\User::class,
|
|
||||||
],
|
|
||||||
//Провайдер для записи в БД минимальных данных пользователя: логина и его id. Нужен для корректной работы Sanctum
|
|
||||||
'users' => [
|
'users' => [
|
||||||
'driver' => 'eloquent',
|
'driver' => 'eloquent',
|
||||||
'model' => App\Models\User::class,
|
'model' => env('AUTH_MODEL', App\Models\User::class),
|
||||||
],
|
],
|
||||||
|
|
||||||
// 'users' => [
|
// 'users' => [
|
||||||
// 'driver' => 'database',
|
// 'driver' => 'database',
|
||||||
// 'table' => 'users',
|
// 'table' => 'users',
|
||||||
@@ -85,9 +76,9 @@ return [
|
|||||||
| Resetting Passwords
|
| Resetting Passwords
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
|
||||||
| You may specify multiple password reset configurations if you have more
|
| These configuration options specify the behavior of Laravel's password
|
||||||
| than one user table or model in the application and you want to have
|
| reset functionality, including the table utilized for token storage
|
||||||
| separate password reset settings based on the specific user types.
|
| and the user provider that is invoked to actually retrieve users.
|
||||||
|
|
|
|
||||||
| The expiry time is the number of minutes that each reset token will be
|
| The expiry time is the number of minutes that each reset token will be
|
||||||
| considered valid. This security feature keeps tokens short-lived so
|
| considered valid. This security feature keeps tokens short-lived so
|
||||||
@@ -102,7 +93,7 @@ return [
|
|||||||
'passwords' => [
|
'passwords' => [
|
||||||
'users' => [
|
'users' => [
|
||||||
'provider' => 'users',
|
'provider' => 'users',
|
||||||
'table' => 'password_reset_tokens',
|
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
|
||||||
'expire' => 60,
|
'expire' => 60,
|
||||||
'throttle' => 60,
|
'throttle' => 60,
|
||||||
],
|
],
|
||||||
@@ -113,12 +104,12 @@ return [
|
|||||||
| Password Confirmation Timeout
|
| Password Confirmation Timeout
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
|
||||||
| Here you may define the amount of seconds before a password confirmation
|
| Here you may define the number of seconds before a password confirmation
|
||||||
| times out and the user is prompted to re-enter their password via the
|
| window expires and users are asked to re-enter their password via the
|
||||||
| confirmation screen. By default, the timeout lasts for three hours.
|
| confirmation screen. By default, the timeout lasts for three hours.
|
||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
'password_timeout' => 10800,
|
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Default Broadcaster
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| This option controls the default broadcaster that will be used by the
|
||||||
|
| framework when an event needs to be broadcast. You may set this to
|
||||||
|
| any of the connections defined in the "connections" array below.
|
||||||
|
|
|
||||||
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'default' => env('BROADCAST_DRIVER', 'null'),
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Broadcast Connections
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may define all of the broadcast connections that will be used
|
||||||
|
| to broadcast events to other systems or over websockets. Samples of
|
||||||
|
| each available type of connection are provided inside this array.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'connections' => [
|
||||||
|
|
||||||
|
'pusher' => [
|
||||||
|
'driver' => 'pusher',
|
||||||
|
'key' => env('PUSHER_APP_KEY'),
|
||||||
|
'secret' => env('PUSHER_APP_SECRET'),
|
||||||
|
'app_id' => env('PUSHER_APP_ID'),
|
||||||
|
'options' => [
|
||||||
|
'cluster' => env('PUSHER_APP_CLUSTER'),
|
||||||
|
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
|
||||||
|
'port' => env('PUSHER_PORT', 443),
|
||||||
|
'scheme' => env('PUSHER_SCHEME', 'https'),
|
||||||
|
'encrypted' => true,
|
||||||
|
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
|
||||||
|
],
|
||||||
|
'client_options' => [
|
||||||
|
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
|
||||||
|
],
|
||||||
|
],
|
||||||
|
|
||||||
|
'ably' => [
|
||||||
|
'driver' => 'ably',
|
||||||
|
'key' => env('ABLY_KEY'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'redis' => [
|
||||||
|
'driver' => 'redis',
|
||||||
|
'connection' => 'default',
|
||||||
|
],
|
||||||
|
|
||||||
|
'log' => [
|
||||||
|
'driver' => 'log',
|
||||||
|
],
|
||||||
|
|
||||||
|
'null' => [
|
||||||
|
'driver' => 'null',
|
||||||
|
],
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Cross-Origin Resource Sharing (CORS) Configuration
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may configure your settings for cross-origin resource sharing
|
||||||
|
| or "CORS". This determines what cross-origin operations may execute
|
||||||
|
| in web browsers. You are free to adjust these settings as needed.
|
||||||
|
|
|
||||||
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'paths' => ['api/*', 'sanctum/csrf-cookie'],
|
||||||
|
|
||||||
|
'allowed_methods' => ['*'],
|
||||||
|
|
||||||
|
'allowed_origins' => ['*'],
|
||||||
|
|
||||||
|
'allowed_origins_patterns' => [],
|
||||||
|
|
||||||
|
'allowed_headers' => ['*'],
|
||||||
|
|
||||||
|
'exposed_headers' => [],
|
||||||
|
|
||||||
|
'max_age' => 0,
|
||||||
|
|
||||||
|
'supports_credentials' => false,
|
||||||
|
|
||||||
|
];
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
return [
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Default LDAP Connection Name
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| Here you may specify which of the LDAP connections below you wish
|
|
||||||
| to use as your default connection for all LDAP operations. Of
|
|
||||||
| course you may add as many connections you'd like below.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'default' => env('LDAP_CONNECTION', 'default'),
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| LDAP Connections
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| Below you may configure each LDAP connection your application requires
|
|
||||||
| access to. Be sure to include a valid base DN - otherwise you may
|
|
||||||
| not receive any results when performing LDAP search operations.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'connections' => [
|
|
||||||
|
|
||||||
'default' => [
|
|
||||||
'hosts' => [env('LDAP_HOST', '127.0.0.1')],
|
|
||||||
'username' => env('LDAP_USERNAME', 'cn=user,dc=local,dc=com'),
|
|
||||||
'password' => env('LDAP_PASSWORD', 'secret'),
|
|
||||||
'port' => env('LDAP_PORT', 389),
|
|
||||||
'base_dn' => env('LDAP_BASE_DN', 'dc=local,dc=com'),
|
|
||||||
'timeout' => env('LDAP_TIMEOUT', 5),
|
|
||||||
'use_ssl' => env('LDAP_SSL', false),
|
|
||||||
'use_tls' => env('LDAP_TLS', false),
|
|
||||||
'use_sasl' => env('LDAP_SASL', false),
|
|
||||||
'sasl_options' => [
|
|
||||||
// 'mech' => 'GSSAPI',
|
|
||||||
],
|
|
||||||
],
|
|
||||||
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| LDAP Logging
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| When LDAP logging is enabled, all LDAP search and authentication
|
|
||||||
| operations are logged using the default application logging
|
|
||||||
| driver. This can assist in debugging issues and more.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'logging' => [
|
|
||||||
'enabled' => env('LDAP_LOGGING', true),
|
|
||||||
'channel' => env('LOG_CHANNEL', 'stack'),
|
|
||||||
'level' => env('LOG_LEVEL', 'info'),
|
|
||||||
],
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| LDAP Cache
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| LDAP caching enables the ability of caching search results using the
|
|
||||||
| query builder. This is great for running expensive operations that
|
|
||||||
| may take many seconds to complete, such as a pagination request.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'cache' => [
|
|
||||||
'enabled' => env('LDAP_CACHE', false),
|
|
||||||
'driver' => env('CACHE_DRIVER', 'file'),
|
|
||||||
],
|
|
||||||
|
|
||||||
];
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Laravel\Sanctum\Sanctum;
|
|
||||||
|
|
||||||
return [
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Stateful Domains
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| Requests from the following domains / hosts will receive stateful API
|
|
||||||
| authentication cookies. Typically, these should include your local
|
|
||||||
| and production domains which access your API via a frontend SPA.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
#Гаврилов
|
|
||||||
//ЗДЕСЬ НУЖНО БУДЕТ ПЕРЕЧИСЛИТЬ ДОМЕНЫ (МЭДЖИКА например) ПЕРЕД ВЫНОСОМ В ПРОД
|
|
||||||
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
|
|
||||||
'%s%s',
|
|
||||||
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
|
|
||||||
Sanctum::currentApplicationUrlWithPort()
|
|
||||||
))),
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Sanctum Guards
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| This array contains the authentication guards that will be checked when
|
|
||||||
| Sanctum is trying to authenticate a request. If none of these guards
|
|
||||||
| are able to authenticate the request, Sanctum will use the bearer
|
|
||||||
| token that's present on an incoming request for authentication.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'guard' => ['web'],
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Expiration Minutes
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| This value controls the number of minutes until an issued token will be
|
|
||||||
| considered expired. This will override any values set in the token's
|
|
||||||
| "expires_at" attribute, but first-party sessions are not affected.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'expiration' => null,
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Token Prefix
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| Sanctum can prefix new tokens in order to take advantage of numerous
|
|
||||||
| security scanning initiatives maintained by open source platforms
|
|
||||||
| that notify developers if they commit tokens into repositories.
|
|
||||||
|
|
|
||||||
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Sanctum Middleware
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| When authenticating your first-party SPA with Sanctum you may need to
|
|
||||||
| customize some of the middleware Sanctum uses while processing the
|
|
||||||
| request. You may change the middleware listed below as required.
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
'middleware' => [
|
|
||||||
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
|
|
||||||
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
|
|
||||||
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
|
|
||||||
],
|
|
||||||
|
|
||||||
];
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
-- custom.users definition
|
|
||||||
|
|
||||||
CREATE TABLE `users` (
|
|
||||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
|
||||||
`login` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Логин пользователя',
|
|
||||||
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
|
|
||||||
`email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
|
|
||||||
`email_verified_at` timestamp NULL DEFAULT NULL,
|
|
||||||
`password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
|
|
||||||
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
|
|
||||||
`created_at` timestamp NULL DEFAULT NULL,
|
|
||||||
`updated_at` timestamp NULL DEFAULT NULL,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
UNIQUE KEY `users_email_unique` (`email`)
|
|
||||||
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
INSERT INTO custom.users (login,name,email,email_verified_at,password,remember_token,created_at,updated_at) VALUES
|
|
||||||
('dgavrilov',NULL,NULL,NULL,NULL,NULL,'2025-11-09 16:50:05','2025-11-09 16:50:05'),
|
|
||||||
('developer',NULL,NULL,NULL,NULL,NULL,'2025-11-20 13:45:05','2025-11-20 13:45:05');
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Authentication Language Lines
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The following language lines are used during authentication for various
|
||||||
|
| messages that we need to display to the user. You are free to modify
|
||||||
|
| these language lines according to your application's requirements.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'failed' => 'These credentials do not match our records.',
|
||||||
|
'password' => 'The provided password is incorrect.',
|
||||||
|
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Pagination Language Lines
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The following language lines are used by the paginator library to build
|
||||||
|
| the simple pagination links. You are free to change them to anything
|
||||||
|
| you want to customize your views to better match your application.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'previous' => '« Previous',
|
||||||
|
'next' => 'Next »',
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Password Reset Language Lines
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The following language lines are the default lines which match reasons
|
||||||
|
| that are given by the password broker for a password update attempt
|
||||||
|
| has failed, such as for an invalid token or invalid new password.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'reset' => 'Your password has been reset.',
|
||||||
|
'sent' => 'We have emailed your password reset link.',
|
||||||
|
'throttled' => 'Please wait before retrying.',
|
||||||
|
'token' => 'This password reset token is invalid.',
|
||||||
|
'user' => "We can't find a user with that email address.",
|
||||||
|
|
||||||
|
];
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Validation Language Lines
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The following language lines contain the default error messages used by
|
||||||
|
| the validator class. Some of these rules have multiple versions such
|
||||||
|
| as the size rules. Feel free to tweak each of these messages here.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'accepted' => 'The :attribute field must be accepted.',
|
||||||
|
'accepted_if' => 'The :attribute field must be accepted when :other is :value.',
|
||||||
|
'active_url' => 'The :attribute field must be a valid URL.',
|
||||||
|
'after' => 'The :attribute field must be a date after :date.',
|
||||||
|
'after_or_equal' => 'The :attribute field must be a date after or equal to :date.',
|
||||||
|
'alpha' => 'The :attribute field must only contain letters.',
|
||||||
|
'alpha_dash' => 'The :attribute field must only contain letters, numbers, dashes, and underscores.',
|
||||||
|
'alpha_num' => 'The :attribute field must only contain letters and numbers.',
|
||||||
|
'array' => 'The :attribute field must be an array.',
|
||||||
|
'ascii' => 'The :attribute field must only contain single-byte alphanumeric characters and symbols.',
|
||||||
|
'before' => 'The :attribute field must be a date before :date.',
|
||||||
|
'before_or_equal' => 'The :attribute field must be a date before or equal to :date.',
|
||||||
|
'between' => [
|
||||||
|
'array' => 'The :attribute field must have between :min and :max items.',
|
||||||
|
'file' => 'The :attribute field must be between :min and :max kilobytes.',
|
||||||
|
'numeric' => 'The :attribute field must be between :min and :max.',
|
||||||
|
'string' => 'The :attribute field must be between :min and :max characters.',
|
||||||
|
],
|
||||||
|
'boolean' => 'The :attribute field must be true or false.',
|
||||||
|
'can' => 'The :attribute field contains an unauthorized value.',
|
||||||
|
'confirmed' => 'The :attribute field confirmation does not match.',
|
||||||
|
'current_password' => 'The password is incorrect.',
|
||||||
|
'date' => 'The :attribute field must be a valid date.',
|
||||||
|
'date_equals' => 'The :attribute field must be a date equal to :date.',
|
||||||
|
'date_format' => 'The :attribute field must match the format :format.',
|
||||||
|
'decimal' => 'The :attribute field must have :decimal decimal places.',
|
||||||
|
'declined' => 'The :attribute field must be declined.',
|
||||||
|
'declined_if' => 'The :attribute field must be declined when :other is :value.',
|
||||||
|
'different' => 'The :attribute field and :other must be different.',
|
||||||
|
'digits' => 'The :attribute field must be :digits digits.',
|
||||||
|
'digits_between' => 'The :attribute field must be between :min and :max digits.',
|
||||||
|
'dimensions' => 'The :attribute field has invalid image dimensions.',
|
||||||
|
'distinct' => 'The :attribute field has a duplicate value.',
|
||||||
|
'doesnt_end_with' => 'The :attribute field must not end with one of the following: :values.',
|
||||||
|
'doesnt_start_with' => 'The :attribute field must not start with one of the following: :values.',
|
||||||
|
'email' => 'The :attribute field must be a valid email address.',
|
||||||
|
'ends_with' => 'The :attribute field must end with one of the following: :values.',
|
||||||
|
'enum' => 'The selected :attribute is invalid.',
|
||||||
|
'exists' => 'The selected :attribute is invalid.',
|
||||||
|
'extensions' => 'The :attribute field must have one of the following extensions: :values.',
|
||||||
|
'file' => 'The :attribute field must be a file.',
|
||||||
|
'filled' => 'The :attribute field must have a value.',
|
||||||
|
'gt' => [
|
||||||
|
'array' => 'The :attribute field must have more than :value items.',
|
||||||
|
'file' => 'The :attribute field must be greater than :value kilobytes.',
|
||||||
|
'numeric' => 'The :attribute field must be greater than :value.',
|
||||||
|
'string' => 'The :attribute field must be greater than :value characters.',
|
||||||
|
],
|
||||||
|
'gte' => [
|
||||||
|
'array' => 'The :attribute field must have :value items or more.',
|
||||||
|
'file' => 'The :attribute field must be greater than or equal to :value kilobytes.',
|
||||||
|
'numeric' => 'The :attribute field must be greater than or equal to :value.',
|
||||||
|
'string' => 'The :attribute field must be greater than or equal to :value characters.',
|
||||||
|
],
|
||||||
|
'hex_color' => 'The :attribute field must be a valid hexadecimal color.',
|
||||||
|
'image' => 'The :attribute field must be an image.',
|
||||||
|
'in' => 'The selected :attribute is invalid.',
|
||||||
|
'in_array' => 'The :attribute field must exist in :other.',
|
||||||
|
'integer' => 'The :attribute field must be an integer.',
|
||||||
|
'ip' => 'The :attribute field must be a valid IP address.',
|
||||||
|
'ipv4' => 'The :attribute field must be a valid IPv4 address.',
|
||||||
|
'ipv6' => 'The :attribute field must be a valid IPv6 address.',
|
||||||
|
'json' => 'The :attribute field must be a valid JSON string.',
|
||||||
|
'lowercase' => 'The :attribute field must be lowercase.',
|
||||||
|
'lt' => [
|
||||||
|
'array' => 'The :attribute field must have less than :value items.',
|
||||||
|
'file' => 'The :attribute field must be less than :value kilobytes.',
|
||||||
|
'numeric' => 'The :attribute field must be less than :value.',
|
||||||
|
'string' => 'The :attribute field must be less than :value characters.',
|
||||||
|
],
|
||||||
|
'lte' => [
|
||||||
|
'array' => 'The :attribute field must not have more than :value items.',
|
||||||
|
'file' => 'The :attribute field must be less than or equal to :value kilobytes.',
|
||||||
|
'numeric' => 'The :attribute field must be less than or equal to :value.',
|
||||||
|
'string' => 'The :attribute field must be less than or equal to :value characters.',
|
||||||
|
],
|
||||||
|
'mac_address' => 'The :attribute field must be a valid MAC address.',
|
||||||
|
'max' => [
|
||||||
|
'array' => 'The :attribute field must not have more than :max items.',
|
||||||
|
'file' => 'The :attribute field must not be greater than :max kilobytes.',
|
||||||
|
'numeric' => 'The :attribute field must not be greater than :max.',
|
||||||
|
'string' => 'The :attribute field must not be greater than :max characters.',
|
||||||
|
],
|
||||||
|
'max_digits' => 'The :attribute field must not have more than :max digits.',
|
||||||
|
'mimes' => 'The :attribute field must be a file of type: :values.',
|
||||||
|
'mimetypes' => 'The :attribute field must be a file of type: :values.',
|
||||||
|
'min' => [
|
||||||
|
'array' => 'The :attribute field must have at least :min items.',
|
||||||
|
'file' => 'The :attribute field must be at least :min kilobytes.',
|
||||||
|
'numeric' => 'The :attribute field must be at least :min.',
|
||||||
|
'string' => 'The :attribute field must be at least :min characters.',
|
||||||
|
],
|
||||||
|
'min_digits' => 'The :attribute field must have at least :min digits.',
|
||||||
|
'missing' => 'The :attribute field must be missing.',
|
||||||
|
'missing_if' => 'The :attribute field must be missing when :other is :value.',
|
||||||
|
'missing_unless' => 'The :attribute field must be missing unless :other is :value.',
|
||||||
|
'missing_with' => 'The :attribute field must be missing when :values is present.',
|
||||||
|
'missing_with_all' => 'The :attribute field must be missing when :values are present.',
|
||||||
|
'multiple_of' => 'The :attribute field must be a multiple of :value.',
|
||||||
|
'not_in' => 'The selected :attribute is invalid.',
|
||||||
|
'not_regex' => 'The :attribute field format is invalid.',
|
||||||
|
'numeric' => 'The :attribute field must be a number.',
|
||||||
|
'password' => [
|
||||||
|
'letters' => 'The :attribute field must contain at least one letter.',
|
||||||
|
'mixed' => 'The :attribute field must contain at least one uppercase and one lowercase letter.',
|
||||||
|
'numbers' => 'The :attribute field must contain at least one number.',
|
||||||
|
'symbols' => 'The :attribute field must contain at least one symbol.',
|
||||||
|
'uncompromised' => 'The given :attribute has appeared in a data leak. Please choose a different :attribute.',
|
||||||
|
],
|
||||||
|
'present' => 'The :attribute field must be present.',
|
||||||
|
'present_if' => 'The :attribute field must be present when :other is :value.',
|
||||||
|
'present_unless' => 'The :attribute field must be present unless :other is :value.',
|
||||||
|
'present_with' => 'The :attribute field must be present when :values is present.',
|
||||||
|
'present_with_all' => 'The :attribute field must be present when :values are present.',
|
||||||
|
'prohibited' => 'The :attribute field is prohibited.',
|
||||||
|
'prohibited_if' => 'The :attribute field is prohibited when :other is :value.',
|
||||||
|
'prohibited_unless' => 'The :attribute field is prohibited unless :other is in :values.',
|
||||||
|
'prohibits' => 'The :attribute field prohibits :other from being present.',
|
||||||
|
'regex' => 'The :attribute field format is invalid.',
|
||||||
|
'required' => 'The :attribute field is required.',
|
||||||
|
'required_array_keys' => 'The :attribute field must contain entries for: :values.',
|
||||||
|
'required_if' => 'The :attribute field is required when :other is :value.',
|
||||||
|
'required_if_accepted' => 'The :attribute field is required when :other is accepted.',
|
||||||
|
'required_unless' => 'The :attribute field is required unless :other is in :values.',
|
||||||
|
'required_with' => 'The :attribute field is required when :values is present.',
|
||||||
|
'required_with_all' => 'The :attribute field is required when :values are present.',
|
||||||
|
'required_without' => 'The :attribute field is required when :values is not present.',
|
||||||
|
'required_without_all' => 'The :attribute field is required when none of :values are present.',
|
||||||
|
'same' => 'The :attribute field must match :other.',
|
||||||
|
'size' => [
|
||||||
|
'array' => 'The :attribute field must contain :size items.',
|
||||||
|
'file' => 'The :attribute field must be :size kilobytes.',
|
||||||
|
'numeric' => 'The :attribute field must be :size.',
|
||||||
|
'string' => 'The :attribute field must be :size characters.',
|
||||||
|
],
|
||||||
|
'starts_with' => 'The :attribute field must start with one of the following: :values.',
|
||||||
|
'string' => 'The :attribute field must be a string.',
|
||||||
|
'timezone' => 'The :attribute field must be a valid timezone.',
|
||||||
|
'unique' => 'The :attribute has already been taken.',
|
||||||
|
'uploaded' => 'The :attribute failed to upload.',
|
||||||
|
'uppercase' => 'The :attribute field must be uppercase.',
|
||||||
|
'url' => 'The :attribute field must be a valid URL.',
|
||||||
|
'ulid' => 'The :attribute field must be a valid ULID.',
|
||||||
|
'uuid' => 'The :attribute field must be a valid UUID.',
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Custom Validation Language Lines
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| Here you may specify custom validation messages for attributes using the
|
||||||
|
| convention "attribute.rule" to name the lines. This makes it quick to
|
||||||
|
| specify a specific custom language line for a given attribute rule.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'custom' => [
|
||||||
|
'attribute-name' => [
|
||||||
|
'rule-name' => 'custom-message',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Custom Validation Attributes
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
|
|
||||||
|
| The following language lines are used to swap our attribute placeholder
|
||||||
|
| with something more reader friendly such as "E-Mail Address" instead
|
||||||
|
| of "email". This simply helps us make our message more expressive.
|
||||||
|
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
'attributes' => [],
|
||||||
|
|
||||||
|
];
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
import React from "react";
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { getCsrfToken } from './../services/getCsrfService';
|
|
||||||
|
|
||||||
function MagicLogin ()
|
|
||||||
{
|
|
||||||
//Состояние с введенным логином
|
|
||||||
const [userLogin, setUserLogin] = useState<string>('');
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div id="login-container">
|
|
||||||
<div id="login-container__magic-name">Magic</div>
|
|
||||||
<div id="login-container__form">
|
|
||||||
<form action="login" method="POST" autoComplete="on">
|
|
||||||
<input
|
|
||||||
type="hidden"
|
|
||||||
name="_token"
|
|
||||||
value={getCsrfToken()}
|
|
||||||
/>
|
|
||||||
<input name="_auth_login" type="text" onChange={ (e) => setUserLogin(e.target.value) } placeholder="Логин" required/>
|
|
||||||
<input name="_auth_password" type="password" placeholder="Пароль" required/>
|
|
||||||
<button type="submit" onClick={ () => {
|
|
||||||
//При сабмите кладем логин в локалсторадж для того, чтобы при вызове api ендпоинтов передавать его в заголовках
|
|
||||||
//гаврилов
|
|
||||||
//ТОЧНО ЛИ ЭТО НУЖНО? МОЖЕТ, ЛУЧШЕ ВСЕ API ЕНДПОИНТЫ ПЕРЕПИСАТ ПОД ВЫЗОВ WEB РОУТОВ?
|
|
||||||
localStorage.setItem('magic_auth_login', userLogin);
|
|
||||||
} }>Вход</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default MagicLogin;
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { createRoot } from 'react-dom/client';
|
|
||||||
import MagicLogin from './components/MagicLogin.tsx';
|
|
||||||
import React from 'react';
|
|
||||||
|
|
||||||
const container = document.getElementById('root')!;
|
|
||||||
const root = createRoot(container);
|
|
||||||
root.render(<MagicLogin />);
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
/**
|
|
||||||
* Сервис для полуения csrt токена для размещения в формах
|
|
||||||
* @date 24.07.2025
|
|
||||||
* @author dgavrilov
|
|
||||||
*/
|
|
||||||
|
|
||||||
export const getCsrfToken = ():string => {
|
|
||||||
const METATAG:HTMLElement|null = document.querySelector('meta[name="csrf-token"]');
|
|
||||||
|
|
||||||
if (!METATAG) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
const CSRFTOKEN:string|null = METATAG.getAttribute('content');
|
|
||||||
if (!CSRFTOKEN) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
return CSRFTOKEN;
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="csrf-token" content="{{ csrf_token() }}">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<title>Laravel + React</title>
|
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
|
||||||
<!-- Без команды ниже корректно не обрабатывается React скрипт -->
|
|
||||||
@viteReactRefresh
|
|
||||||
<!-- файл со стилями resources/css/magicLogin.css не создан, так как не успел приступить к доделке меню -->
|
|
||||||
@vite(['resources/css/magicLogin.css', 'resources/js/magicLogin.tsx'])
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<div id="root"></div>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use \App\Http\Controllers;
|
|
||||||
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 and all of them will
|
|
||||||
| be assigned to the "api" middleware group. Make something great!
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
#Гаврилов
|
|
||||||
//РОУТ НИЖЕ НУЖЕН? НЕ ПОМНЮ ОТКУДА ОН ВЗЯЛСЯ. Пока оставляю, но надо разобраться для теста он или нужен на проде
|
|
||||||
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
|
|
||||||
return $request->user();
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Получение пользовательской роли
|
|
||||||
*/
|
|
||||||
Route::get('user_role/{moduleName}', [Controllers\AuthorizationController::class, 'getUserRole'])->where('moduleName', '^[a-z0-9_]+$');
|
|
||||||
@@ -1,56 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use \App\Http\Controllers;
|
|
||||||
use App\Http\Middleware\AuthenticateMagic;
|
|
||||||
|
|
||||||
/*
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
| Web Routes
|
|
||||||
|--------------------------------------------------------------------------
|
|
||||||
|
|
|
||||||
| Here is where you can register web routes for your application. These
|
|
||||||
| routes are loaded by the RouteServiceProvider and all of them will
|
|
||||||
| be assigned to the "web" middleware group. Make something great!
|
|
||||||
|
|
|
||||||
*/
|
|
||||||
|
|
||||||
#Гаврилов
|
|
||||||
//РЕДИРЕКТ НА СТРАНИЦУ ЛОГИН
|
|
||||||
Route::get('/', function () {
|
Route::get('/', function () {
|
||||||
return view('welcome');
|
return view('welcome');
|
||||||
});
|
});
|
||||||
//Роут вызова вьюхи аутентификации (без посредника аутентификации)
|
|
||||||
Route::get('/login', function () {
|
|
||||||
return view('magic_login');
|
|
||||||
})->withoutMiddleware([AuthenticateMagic::class])->name('magic_login');
|
|
||||||
Route::get('/logout', ([Controllers\LoginController::class, 'logout']))->name('magic_logout');
|
|
||||||
//Роут вызова процессе аутентификации (без посредника аутентификации)
|
|
||||||
Route::post('login', [Controllers\LoginController::class, 'ldapCheckUser'])->withoutMiddleware([AuthenticateMagic::class]);
|
|
||||||
|
|
||||||
//ГАВРИЛОВ. добавить without middleware AuthMagicApi?
|
|
||||||
//Фоновое обновление санктум токена, если api вернул 401 (санктум протух), а сессия еще "жива"
|
|
||||||
Route::get('/silent_token_refresh', [Controllers\LoginController::class, 'silentRefreshUserSanctumToken'])->withoutMiddleware([AuthenticateMagic::class]);
|
|
||||||
|
|
||||||
// Route::get('/role', [\App\Http\Controllers\TestController::class, 'getRoles'])->name('get_role');
|
|
||||||
//Route::get('/access', [\App\Http\Controllers\TestController::class, 'getAccess']);
|
|
||||||
|
|
||||||
// Route::controller(Controllers\TestController::class)->group(function ()
|
|
||||||
// {
|
|
||||||
// Route::get('/access/{id}', 'getAccess')->where(['id' => '[0-9]+'])->name('getAccessById');
|
|
||||||
// //Route::get('/access/{id}', 'getAccess')->where(['id' => '[0-9]+']);
|
|
||||||
// });
|
|
||||||
|
|
||||||
// Route::get('/testData/{int}/{char}', [Controllers\TestDataController::class, 'insertNewData'])->where(['int' => '[0-9]+', 'char' => '[a-z]+']);
|
|
||||||
|
|
||||||
// Route::get('/testParam/{id}', [\App\Http\Controllers\TestController::class, 'getParam'])->where(['id' => '[0-9]+']);
|
|
||||||
// Route::get('/redirect', [Controllers\TestController::class, 'redirect']);
|
|
||||||
// Route::post('/role', [\App\Http\Controllers\TestController::class, 'setRole']);
|
|
||||||
// Route::post('/role_del', [\App\Http\Controllers\TestController::class, 'delRole']);
|
|
||||||
|
|
||||||
// Route::get('/test_table', [Controllers\TestFormController::class, 'getForm']);
|
|
||||||
// Route::post('/test_table', [Controllers\TestFormController::class, 'setForm'])->name('test_set_form');
|
|
||||||
|
|
||||||
// Route::get('/access/{id?}', [Controllers\AccessListController::class, 'getAccess'])->where(['id' => '[0-9]+']);
|
|
||||||
// Route::delete('/access/{id}', [Controllers\AccessListController::class, 'delAccess'])->where(['id' => '[0-9]+'])->name('del_lk_tm_access');
|
|
||||||
// Route::post('/access', [Controllers\AccessListController::class, 'postAccess']);
|
|
||||||
|
|||||||
Reference in New Issue
Block a user