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

- 1 answer

Ad

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?

Ad

Answer

Ad

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.

Ad
source: stackoverflow.com
Ad