0

I am using a session separately other than the default authentication sessions. If an user try to access my secured page, he should have the session set. If anyone without that session try to access means, they will be redirected to error page. I am using Laravel 5.3

The user can view the below two pages only if the session variable named 'secured_user' is set. Otherwise they will be redirect to the error page

Route::get('/secured-page1', 'ValidationController@CheckSecuredLogin_1');

Route::get('/secured-page2', 'ValidationController@CheckSecuredLogin_2');
sujivasagam
  • 1,659
  • 1
  • 14
  • 26
  • Please provide code samples of what you ve tried and how you implemented the second session. – Frnak Nov 17 '16 at 10:13

3 Answers3

2

The best option would be a policy.

You can create certain constrains and couple it with your models. Policies are especially suitable for changing your logic later on.

See here: Create Policy

Within you PagesPolicy, you can add this function:

public function before(User $user, $ability)
{
    if ($user->isSuperAdmin()) {
        return true;
    }
}

public function seeSecurePage(User $user)
{
    // Your custom Code and session handling
    if(session("secured_user")) return true;
    return false;
}

and in your controller.

$user->can("seeSecurePage","Pages");

If "can" fails, it will automatically redirect to error 403.

P.S.: Another possibility are Gates

Mruf
  • 766
  • 7
  • 16
1

You should use Laravel Middlewares to achieve this, I think middlewares are made for the work you need:

First create a new middleware by running the artisan command:

php artisan make:middleware CheckSesison

Then the CheckSession would look like this:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckSession
{
    public function handle($request, Closure $next)
    {
        if ($session_value != 'YOUR_DESIRED_VALUE') {
            return redirect('home');
        }

        return $next($request);
    }

}

Now in your routes file you can use laravel's route middleware() method to implement it like this:

Route::get('/secured-page1', 'ValidationController@CheckSecuredLogin_1')
    ->middleware(CheckSession::class);

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
0

In addition to the awnser above, you could also use middleware that's used on the routes and even group them if required. It is a simple, quick and clean solution. Inside the middelware you simple check if the session you require is there and depending on the result you take any action necessary. Laravel middleware docs

killstreet
  • 1,251
  • 2
  • 15
  • 37