klein / klein.php

A fast & flexible router
MIT License
2.66k stars 290 forks source link

Question, handling a client area #398

Open thijndehaas opened 5 years ago

thijndehaas commented 5 years ago

In my website I have a clientarea that should have the login and register page always accessible and the other pages only if logged in. If the user is not logged in the other pages should redirect. I'am struggling with this for a few hours already in Klein.

Of course I can do the check inside every route but with the session check before loading the routes I would like to prevent any accidental code executions by not even loading the client routes at all when the client is not logged in.

I currently have the following setup:

if (!$_SESSION['user']) {

    $router->with('/clientarea', function () {

        $router->respond(['POST', 'GET'], '@^$', function ($request, $response) {
            // login page
        });

        $router->respond(['POST', 'GET'], '/register', function ($request, $response) {
            // register page
        });

        // Here I would like to redirect all pages that are not the login or register page

    });

}
else {

     $router->with('/clientarea', function () {

        $router->respond(['POST', 'GET'], '@^$', function ($request, $response) use ($data, $twig) {
            header('Location: /clientarea');
            exit;
        });

        $router->respond(['POST', 'GET'], '/register', function ($request, $response) use ($data, $twig) {
            header('Location: /clientarea');
            exit;
        });

        $router->respond('GET', '/page1', function ($request, $response) use ($data, $twig) {
            // clientarea page 1
        });

        $router->respond('GET', '/page2', function ($request, $response) use ($data, $twig) {
            // clientarea page 2
        });

        $router->respond('GET', '/page3', function ($request, $response) use ($data, $twig) {
            // clientarea page 3
        });

     });

}
mkraha commented 5 years ago

I guess, You have to insert a login-check method on header of clientarea template.

infureal commented 5 years ago

I think you can write unique namespace for login/register. Like "/auth".

$router = new Klein();

$prefix = "/clientarea";

$router->with($prefix, function () use ($router) {

    $router->respond(function (Request $request, Response $response) {
        //redirect ALL responds
        return $response->redirect("YOUR URL HERE")->send();
    });

});

$router->with($prefix . "/auth", function () use ($router) {

    $router->respond(['POST', 'GET'], '@^$', function (Request $request, Response $response) {
        // login page
    });

    $router->respond(['POST', 'GET'], '/register', function (Request $request, Response $response) {
        // register page
    });

});

Anyway. @mkrahamath 's idea better. You must check login state for accessing to auth pages.

P.S. Sorry for my English :D