Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tutorial #282

Open
AAB94 opened this issue Mar 18, 2015 · 6 comments
Open

Tutorial #282

AAB94 opened this issue Mar 18, 2015 · 6 comments

Comments

@AAB94
Copy link

AAB94 commented Mar 18, 2015

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
Copy link

nbish11 commented Apr 15, 2015

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
Copy link

jk3us commented Apr 17, 2015

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
Copy link

nbish11 commented Apr 17, 2015

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

@dan1elhughes
Copy link

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

@nbish11
Copy link

nbish11 commented Jun 9, 2015

$klein->onHttpError(function ($code, $router) {
    $app = $router->app();
});

@dan1elhughes
Copy link

That works, thanks @nbish11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants