OctoberCMS: How to check if user logged in for all pages

强颜欢笑 提交于 2020-01-02 07:19:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!