Restrict the pages in laravel when using socialite as login

41 Views Asked by At

In laravel have added socialite login for google,but i wanted them to be authenticated first before going to /studentTable route. And if they are not authenticated then they go back to login. Im new to laravel and is this possible?, i tried middleware('auth'); and middleware('guest') but it wont work in socialite.

Route::get('/studentTable',[StudentController::class, 'viewAllStudent'])->middleware('auth');


Route::get('/login',[UserController::class, 'loginFunction'])->name('login')->middleware('guest');

1

There are 1 best solutions below

0
Kevin On

When using socialite authentication, the auth middleware alone may not be enough, like in your case. Instead, you can create a custom middleware that checks for both socialite authentication and regular authentication.

php artisan make:middleware SocialiteAuthentication

Middleware:

public function handle($request, Closure $next)
{
    //assuming you have a role called student. If not remove the second condition
    if (! $request->user() || ! $request->user()->hasRole('student')) {
        return redirect('/login');
    }

    return $next($request);
}

Register the middleware in Kernel.php

'socialite-auth' => \App\Http\Middleware\SocialiteAuthentication::class,

Route:

Route::get('/studentTable', [StudentController::class, 'viewAllStudent'])->middleware('socialite-auth');