在laravel中间件中获取用户当前状态



我使用此软件包进行维护,但要定义哪些用户可以在停机期间访问网站,哪些用户不能访问网站,我有问题。

在过去的几天里,我一直在搜索,我读了很多,因为主控制器在中间件之后加载,所以它无法检测用户状态,无论是否登录。(我不知道,我只是反复看到)

无论如何,问题是:

我希望允许角色为Admin用户在停机时间访问网站,而visitorsother group of users则不允许。

到目前为止我做了什么

基于包文档,我在AppExemptionsAdminExemption.php中制作了带有以下数据的自定义文件:

<?php
namespace AppExemptions;
use Auth; use Config; use AppUser; use MisterPhilipMaintenanceModeExemptionsMaintenanceModeExemption;
class AdminExemption extends MaintenanceModeExemption {
public function isExempt()
{
if (Auth::check() && Auth::user()->role == 'Admin') {
return true;
}
else {
return false;
}
//if user is logged and it's admin show the site
//if user is logged and isn't admin hide the site
//if user isn't logged (is visitor) hide the site
} }

我在包配置文件configmaintenancemode.php中注册此文件

'exemptions' => [
AppExemptionsAdminExemption::class,
],

并在Kernel中将包类替换为laravel默认

protected $middleware = [
// AppHttpMiddlewareCheckForMaintenanceMode::class,
MisterPhilipMaintenanceModeHttpMiddlewareCheckForMaintenanceMode::class,
//others...
]

问题

Auth::check()auth()->user()Auth::user()中的任何一个都不能检测到已登录的用户,并假设该用户未登录(是访问者)。因此,该网站对所有人甚至管理员都关闭了。

问题

如何在AdminExemption.php文件中获取当前用户的真实状态?

状态

  1. 是用户(是管理员)show the site
  2. 是用户(不是管理员)don't show the site
  3. 不是用户(访问者)don't show the site

知道吗?

您已经在主中间件堆栈中注册了中间件,这将在它到达中间件组之前发生。您可能希望将内核中较低的中间件移到web中间件堆栈中。这是因为只有在存在会话的情况下,Laravel才会知道登录的用户,并且会话仅在web堆栈中启动。

protected $middlewareGroups = [
'web' => [
AppHttpMiddlewareEncryptCookies::class,
IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
IlluminateSessionMiddlewareStartSession::class,
// IlluminateSessionMiddlewareAuthenticateSession::class,
IlluminateViewMiddlewareShareErrorsFromSession::class,
AppHttpMiddlewareVerifyCsrfToken::class,
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
];

您需要将中间件放在StartSession中间件之后,但最好将其放在那里的最后,然后在您的中间件中应该可以使用登录状态。

最新更新