Search code examples
phplaravellaravel-5.4dingo-api

Middleware for "guest" type user, using Dingo API


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.


Solution

  • 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.