Laravel custom auth filter

SteB picture SteB · Feb 6, 2014 · Viewed 10.8k times · Source

I've added the standard auth filter to several routes using Route::Intended('/') in the controller (assuming login is successful).

filters.php:

Route::filter('auth', function(){
    if (Auth::guest()) return Redirect::guest('internal/login');
});

Controller:

if (Auth::attempt($data, false))
{
    return Redirect::intended('/');
}

How do I go about creating a custom auth filter that checks for a specific permission (isAdmin in this case)?

I've made the auth.admin filter the same as the standard auth filter to redirect to the login page, but do I need a second Login method on my controller or is there a way to tell which filter (if any) invoked the controller method?

if (Auth::attempt($data, false))
{
    if (RouteHasAdminFilter())
    {
        if (!Auth::User()->Admin)
            return Redirect::intended('/');
        else
            return Redirect::to('/');
    }
    else
    {
        return Redirect::intended('/');
    }
}

Answer

SteB picture SteB · Feb 9, 2014

Thanks to @diegofelix for putting me on the right track.

I've managed to write a filter that:

  • Prompts the user for their credentials
  • Redirects to the homepage for non-admin users
  • Allows an Admin user to go to the original URL


Route::filter('admin', function()  
{

    if (Auth::guest()) return Redirect::guest('internal/login');

    if (Auth::check())
    {
        if (!Auth::User()->Admin)
            return Redirect::to('/');
    }
    else
        return Redirect::to('/');
});

This filter requires no changes to the Login method on my controller, which still uses Redirect::intended('/').
The key to this is NOT to redirect for Admin users, simply letting the code "fall through" to the original page, only non-admin users are redirected.
I'm also still using the standard "auth" filter to pages that require non-admin authentication.

My routes use either:

'before' => 'auth'
'before' => 'admin'

If I remove the first line of my admin filter (which I copied from the standard auth filter), I could get the same effect by using both filters together like so:

'before' => 'auth|admin'