diff --git a/app/Facades/UserContext.php b/app/Facades/UserContext.php
new file mode 100644
index 0000000..c30bd64
--- /dev/null
+++ b/app/Facades/UserContext.php
@@ -0,0 +1,18 @@
+json(['userRole' => $userPermissions[$moduleName]], 403);
+ } else {
+ return response()->json(['message' => 'Приложение недоступно'], 403);
+ }
+ }
+}
diff --git a/app/Http/Controllers/LoginController.php b/app/Http/Controllers/LoginController.php
new file mode 100644
index 0000000..b3a149e
--- /dev/null
+++ b/app/Http/Controllers/LoginController.php
@@ -0,0 +1,246 @@
+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;
+ }
+}
diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php
new file mode 100644
index 0000000..31a98c8
--- /dev/null
+++ b/app/Http/Middleware/Authenticate.php
@@ -0,0 +1,18 @@
+expectsJson() ? null : route('login');
+ }
+}
diff --git a/app/Http/Middleware/AuthenticateMagic.php b/app/Http/Middleware/AuthenticateMagic.php
new file mode 100644
index 0000000..bff4767
--- /dev/null
+++ b/app/Http/Middleware/AuthenticateMagic.php
@@ -0,0 +1,73 @@
+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 '
'; var_dump(new \DateTime($tokenExpires)); echo'
';
+ // echo ''; var_dump(PersonalAccessToken::where('tokenable_id', $userId)->get()->toArray()[0]['expires_at']); echo'';
+ //Если токен истекает менее через 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);
+ }
+}
diff --git a/app/Http/Middleware/AuthenticateMagicApi.php b/app/Http/Middleware/AuthenticateMagicApi.php
new file mode 100644
index 0000000..5571805
--- /dev/null
+++ b/app/Http/Middleware/AuthenticateMagicApi.php
@@ -0,0 +1,61 @@
+is('api/silent_token_refresh')) {
+ // return $next($request);
+ // }
+ //Если пользователь в рамках сессии обращается к api ендпоинтам из приложения, он не всегда может установить заголовок с sanctum токеном (например, переходя по ссылкке ). В этом случае, проверяем куки и устанавливаем заголовок оттуда, так как при аутентификации пользовательский логин кладется в куки. Это позволяет нам не устанвливать заголовк в каждом 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);
+ }
+}
diff --git a/app/Http/Middleware/CheckUserAppAccess.php b/app/Http/Middleware/CheckUserAppAccess.php
new file mode 100644
index 0000000..11af61c
--- /dev/null
+++ b/app/Http/Middleware/CheckUserAppAccess.php
@@ -0,0 +1,43 @@
+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');
+ }
+ }
+}
diff --git a/app/Http/Middleware/CheckUserPermission.php b/app/Http/Middleware/CheckUserPermission.php
new file mode 100644
index 0000000..b6cbf47
--- /dev/null
+++ b/app/Http/Middleware/CheckUserPermission.php
@@ -0,0 +1,67 @@
+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
+ }
+}
diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php
new file mode 100644
index 0000000..0b8c917
--- /dev/null
+++ b/app/Http/Middleware/VerifyCsrfToken.php
@@ -0,0 +1,19 @@
+
+ */
+ protected $except = [
+ //
+ '/access/*',
+ '/access',
+ ];
+}
diff --git a/app/Models/User.php b/app/Models/User.php
index 749c7b7..a967f84 100644
--- a/app/Models/User.php
+++ b/app/Models/User.php
@@ -6,43 +6,45 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
+use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
- /** @use HasFactory<\Database\Factories\UserFactory> */
- use HasFactory, Notifiable;
+ use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
- * @var list
+ * @var array
*/
+ // protected $fillable = [
+ // 'name',
+ // 'email',
+ // 'password',
+ // ];
protected $fillable = [
- 'name',
- 'email',
- 'password',
+ 'login',
];
+
/**
* The attributes that should be hidden for serialization.
*
- * @var list
+ * @var array
*/
- protected $hidden = [
- 'password',
- 'remember_token',
- ];
+ // protected $hidden = [
+ // 'password',
+ // 'remember_token',
+ // ];
+ protected $hidden = [];
/**
- * Get the attributes that should be cast.
+ * The attributes that should be cast.
*
- * @return array
+ * @var array
*/
- protected function casts(): array
- {
- return [
- 'email_verified_at' => 'datetime',
- 'password' => 'hashed',
- ];
- }
+ protected $casts = [
+ 'email_verified_at' => 'datetime',
+ 'password' => 'hashed',
+ ];
}
diff --git a/app/Providers/AuthorizationServiceProvider.php b/app/Providers/AuthorizationServiceProvider.php
new file mode 100644
index 0000000..d833d37
--- /dev/null
+++ b/app/Providers/AuthorizationServiceProvider.php
@@ -0,0 +1,30 @@
+app->bind(AuthorizationService::class, function($app) {
+ return new AuthorizationService();
+ });
+ }
+
+ /**
+ * Bootstrap services.
+ */
+ public function boot(): void
+ {
+ //
+ }
+}
diff --git a/app/Providers/UserServiceProvider.php b/app/Providers/UserServiceProvider.php
new file mode 100644
index 0000000..c537596
--- /dev/null
+++ b/app/Providers/UserServiceProvider.php
@@ -0,0 +1,30 @@
+app->singleton(UserService::class, function($app){
+ return new UserService;
+ });
+ }
+
+ /**
+ * Bootstrap services.
+ */
+ public function boot(): void
+ {
+ //
+ }
+}
diff --git a/app/Services/AuthorizationService.php b/app/Services/AuthorizationService.php
new file mode 100644
index 0000000..640a3c2
--- /dev/null
+++ b/app/Services/AuthorizationService.php
@@ -0,0 +1,86 @@
+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();
+ // }
+
+}
diff --git a/app/Services/UserService.php b/app/Services/UserService.php
new file mode 100644
index 0000000..e25cbc0
--- /dev/null
+++ b/app/Services/UserService.php
@@ -0,0 +1,198 @@
+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;
+ }
+
+}
diff --git a/config/auth.php b/config/auth.php
index 7d1eb0d..7a44b14 100644
--- a/config/auth.php
+++ b/config/auth.php
@@ -7,15 +7,15 @@ return [
| Authentication Defaults
|--------------------------------------------------------------------------
|
- | This option defines the default authentication "guard" and password
- | reset "broker" for your application. You may change these values
+ | This option controls the default authentication "guard" and password
+ | reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
- 'guard' => env('AUTH_GUARD', 'web'),
- 'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
+ 'guard' => 'web',
+ 'passwords' => 'users',
],
/*
@@ -25,11 +25,11 @@ return [
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
- | which utilizes session storage plus the Eloquent user provider.
+ | here which uses session storage and the Eloquent user provider.
|
- | All authentication guards have a user provider, which defines how the
+ | All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
- | system used by the application. Typically, Eloquent is utilized.
+ | mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
@@ -38,6 +38,11 @@ return [
'guards' => [
'web' => [
'driver' => 'session',
+ 'provider' => 'ldap',
+ ],
+ // guard для аутентификации при запросе ендпоинтов API, а также для нормального логирования информации события обращения к API ендпоинтам
+ 'sanctum' => [
+ 'driver' => 'sanctum',
'provider' => 'users',
],
],
@@ -47,12 +52,12 @@ return [
| User Providers
|--------------------------------------------------------------------------
|
- | All authentication guards have a user provider, which defines how the
+ | All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
- | system used by the application. Typically, Eloquent is utilized.
+ | mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
- | providers to represent the model / table. These providers may then
+ | sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
@@ -60,11 +65,15 @@ return [
*/
'providers' => [
+ 'ldap' => [
+ 'driver' => 'ldap',
+ 'model' => LdapRecord\Models\ActiveDirectory\User::class,
+ ],
+ //Провайдер для записи в БД минимальных данных пользователя: логина и его id. Нужен для корректной работы Sanctum
'users' => [
'driver' => 'eloquent',
- 'model' => env('AUTH_MODEL', App\Models\User::class),
+ 'model' => App\Models\User::class,
],
-
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
@@ -76,9 +85,9 @@ return [
| Resetting Passwords
|--------------------------------------------------------------------------
|
- | These configuration options specify the behavior of Laravel's password
- | reset functionality, including the table utilized for token storage
- | and the user provider that is invoked to actually retrieve users.
+ | You may specify multiple password reset configurations if you have more
+ | than one user table or model in the application and you want to have
+ | separate password reset settings based on the specific user types.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
@@ -93,7 +102,7 @@ return [
'passwords' => [
'users' => [
'provider' => 'users',
- 'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
+ 'table' => 'password_reset_tokens',
'expire' => 60,
'throttle' => 60,
],
@@ -104,12 +113,12 @@ return [
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
- | Here you may define the number of seconds before a password confirmation
- | window expires and users are asked to re-enter their password via the
+ | Here you may define the amount of seconds before a password confirmation
+ | times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
- 'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
+ 'password_timeout' => 10800,
];
diff --git a/config/ldap.php b/config/ldap.php
new file mode 100644
index 0000000..0772558
--- /dev/null
+++ b/config/ldap.php
@@ -0,0 +1,81 @@
+ 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'),
+ ],
+
+];
diff --git a/config/sanctum.php b/config/sanctum.php
new file mode 100644
index 0000000..1b5eb0e
--- /dev/null
+++ b/config/sanctum.php
@@ -0,0 +1,85 @@
+ 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,
+ ],
+
+];
diff --git a/database/tables_for_magic2.0/users.sql b/database/tables_for_magic2.0/users.sql
new file mode 100644
index 0000000..e32cdb9
--- /dev/null
+++ b/database/tables_for_magic2.0/users.sql
@@ -0,0 +1,15 @@
+-- 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;
\ No newline at end of file
diff --git a/database/tables_for_magic2.0/users_202602271736.sql b/database/tables_for_magic2.0/users_202602271736.sql
new file mode 100644
index 0000000..0e9954a
--- /dev/null
+++ b/database/tables_for_magic2.0/users_202602271736.sql
@@ -0,0 +1,3 @@
+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');
diff --git a/resources/js/components/MagicLogin.tsx b/resources/js/components/MagicLogin.tsx
new file mode 100644
index 0000000..e5f0740
--- /dev/null
+++ b/resources/js/components/MagicLogin.tsx
@@ -0,0 +1,34 @@
+import React from "react";
+import { useEffect, useState } from "react";
+import { getCsrfToken } from './../services/getCsrfService';
+
+function MagicLogin ()
+{
+ //Состояние с введенным логином
+ const [userLogin, setUserLogin] = useState('');
+
+ return (
+
+ );
+}
+
+export default MagicLogin;
diff --git a/resources/js/magicLogin.tsx b/resources/js/magicLogin.tsx
new file mode 100644
index 0000000..c9f9a34
--- /dev/null
+++ b/resources/js/magicLogin.tsx
@@ -0,0 +1,7 @@
+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();
diff --git a/resources/js/services/getCsrfService.tsx b/resources/js/services/getCsrfService.tsx
new file mode 100644
index 0000000..12e160d
--- /dev/null
+++ b/resources/js/services/getCsrfService.tsx
@@ -0,0 +1,20 @@
+/**
+ * Сервис для полуения 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;
+}
diff --git a/resources/views/magic_login.blade.php b/resources/views/magic_login.blade.php
new file mode 100644
index 0000000..0086908
--- /dev/null
+++ b/resources/views/magic_login.blade.php
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+ Laravel + React
+
+
+ @viteReactRefresh
+
+ @vite(['resources/css/magicLogin.css', 'resources/js/magicLogin.tsx'])
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/routes/api.php b/routes/api.php
new file mode 100644
index 0000000..56edb38
--- /dev/null
+++ b/routes/api.php
@@ -0,0 +1,29 @@
+get('/user', function (Request $request) {
+ return $request->user();
+});
+
+
+
+/**
+ * Получение пользовательской роли
+ */
+Route::get('user_role/{moduleName}', [Controllers\AuthorizationController::class, 'getUserRole'])->where('moduleName', '^[a-z0-9_]+$');
diff --git a/routes/web.php b/routes/web.php
index 86a06c5..5ac14bf 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -1,7 +1,56 @@
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']);