问题
I am using the following code (in the code section of a page) to redirect users to the login page if they are not logged in:
function onStart()
{
$user = $this->account->user();
if(!$user)
{
return Redirect::to('/login');
}
}
How can I avoid doing this in every page and perform this checking in one place for all the pages that need authentication?
回答1:
You can use the Session Component
as suggested but then you need two layouts :
a) Layout for registered Users >> Add session component to this layout and set security = "user"
with the redirect option
b) Layout for public pages ( non-registered ) >> Add another session component >> security = "guest"
Another option could be to create a Middleware for those routes;
public function handle($request, Closure $next)
{
App::before(function () {
if (App::runningInBackend() || App::runningInConsole()) {
return;
}
if ( !Auth::getUser() ) {
return Redirect::to('/login');
}
});
return $next($request);
}
Keep it simple, if you're using the RainLab Plugin and just need to check a user is logged in, the session component would do the job.
回答2:
cant you use the session component? to redirect non logged in users.
回答3:
You can use the same functions in the layout. The layouts onInit()
sounds like a good option.
You can read more about it here
回答4:
the Plugin.php
has an boot
function that is called as the plugin is loaded. You'll need to check if the current page isn't in the backend else you won't be able to get in the CMS without loggin in in the front end. Also check if it isn't login because that will cause infinite loops.
This code should work.
public function boot ()
{
$user = $this->account->user();
if ( ! $user && ! Request::is('backend/*') && ! Request::is('login') )
{
return Redirect::to('/login');
}
}
来源:https://stackoverflow.com/questions/42552191/octobercms-how-to-check-if-user-logged-in-for-all-pages