0

My User model may be anonymous (eg. no e-mail registered, $user->isAnonymous()). By using the api.auth middleware both anonymous and fully registered users can access a given route. Now I want to restrict a route, so that anonymous users can not access it.

(Important to notice that "anonymous users" are still authenticated, anonymous does not refer to unauthenticated)

The question is, where should I place this logic to best conform with the Dingo package? Am I looking at making my own middleware, extending Dingo, or maybe making a custom provider for Dingo?

Bonus question: I think the best result would have one middleware (eg. api.auth) only authorize those users that are not anonymous, and the second middleware (eg. auth.all) authorize both anonymous and non-anonymous users.

Zoon
  • 1,068
  • 2
  • 11
  • 26

1 Answers1

2

I would go for nested middlewares like this

Route::group(['middleware' => 'auth:api'], function(){
    Route::get(...); //all authenticated users can see this

    Route::group(['middleware' => 'known'], function() {
        //assuming the middleware name is 'known' in kernel.php
        Route::get(....); //Only known users (non-anonymous) will get in here
    });
});

For the middleware you could do

public function handle($request, Closure $next)
{
    if (Auth::check()){
        if(!Auth::user()->email) {
            return redirect('/'); //no email. kick them out!
        }
    }
    return $next($request);
}

Or anything similar.

EddyTheDove
  • 12,979
  • 2
  • 37
  • 45
  • Thanks! Definitely the simplest approach to the problem, and simple is often the way to go. I will just leave it out there for the rest of the day to see if anyone has a better idea. – Zoon Mar 09 '17 at 00:03