klein / klein.php

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

Tutorial #282

Open AAB94 opened 9 years ago

AAB94 commented 9 years ago

Hi, just wondering if there are any tutorials for this library. I wanna use it to filter users as that is allow user access to a page based on his session. can you show some examples as to how your library works

nbish11 commented 9 years ago

If I find time, I'll create an "examples" page in the wiki, with a user authentication section. However, if you just need some code to get you started:

$klein = new Klein\Klein();

$klein->respond('/unauthorised', function () {
    return 'You do not have access to this page!';
});

$klein->with('/admin', function () use ($klein) {

    // this will be run when anyone 
    // navigates to a route beginning
    // with "/admin".
    $klein->respond(function ($request, $response) {
        $hasAccess = Auth::isAuthorized();

        // redirect if not authorized
        if ( ! $hasAccess) {
            $response->redirect('/unauthorized');
        }
    });

    $klein->respond('/?', function () {
        return 'Admin Home Page!';
    });
});

$klein->dispatch();

This code is untested.

jk3us commented 9 years ago

Instead of redirecting, it might be better to use $klein->abort(403), and set up a 403 block in the onHttpError handler:

$klein->with('/admin', function () use ($klein) {
    $klein->respond(function ($request, $response) use ($klein) {
        if( !Auth::isAuthorized()) {
            $klein->abort(403); // 403 = Forbidden
        }
    }
}

$klein->onHttpError(function ($code, $router) {
    switch ($code) {
        case 403:
            $router->response->body('You do not have access to this page!');
    }
}

I do wish the abort method were on the $response object instead of the $klein object, though.

nbish11 commented 9 years ago

Nice catch. :) I keep forgetting about the onHttpError() handler.

dan1elhughes commented 9 years ago

In onHttpError(), is there a way to access $app?

nbish11 commented 9 years ago
$klein->onHttpError(function ($code, $router) {
    $app = $router->app();
});
dan1elhughes commented 9 years ago

That works, thanks @nbish11