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('/');
    }
}
有帮助吗?

解决方案

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'

其他提示

If you want to redirect the user to a different if he is admin, you can do the check in the same Controller method.

if (Auth::attempt($data)
{
    if (Auth::user()->isAdmin())
        // admin
    else
        // not admin
}
else
    // login failed

In this case the isAdmin() is a method in the User Eloquent that checks if the user is admin.

If you want to do this check in other pages, you can create a filter that check if the user is admin like so:

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

    if ( ! Auth::user()->isAdmin())
    {
        return Redirect::to('/')
         ->withError('No Admin, sorry.');
    }

});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top