Home > database >  How to separate user session from admin session in Laravel?
How to separate user session from admin session in Laravel?

Time:12-22

How to separate user session from admin session in Laravel?

Can Laravel's Multi Auth achieve this?

Is there another way to separate sessions without using Multi Auth? I don't want to use Multi Auth because it looks complicated.

But I want to know whether sessions can be separated with Multi Auth? How about the following code?

// in a user page
$request->session()->put('name', 1);

// in an admin page
var_dump($request->session()->get('name'));

what will be output? 1 or null?

In general, separating user session from admin session is a common practice in web application?

Or, you should separate user session from admin session by adding prefix to session keys like this?

// in php
$_SESSION['user']['name'] = 1;
$_SESSION['admin']['name'] = 2;
unset($_SESSION['admin']);

// in Laravel
$request->session()->put('user.name', 1);
$request->session()->put('admin.name', 2);
$request->session()->forget('admin');

In Laravel's config/sessions.php, I can't find the option to separate user session from admin session. The session config file seems to provide just a single session configuration.

CodePudding user response:

Assuming you are just wanting to protect some views for admins only.

Here is a basic example of how to make an "Admin", Come up with any solution you want. E.g. create an extra column on your user table if you wish.

First create a method on your user model called isAdmin

private const ADMIN_IDS = [
    1,2,3,4
];

public function isAdmin()
{
    return in_array($this->id, self::ADMIN_IDS);
}

Then create a middleware https://laravel.com/docs/8.x/middleware#defining-middleware

<?php

namespace App\Http\Middleware;

use Closure;

class AdminMiddleware
{
    public function handle($request, Closure $next)
    {

        if (auth()->user()->isAdmin()) {
            return $next($request);
        }
        abort(401);
    }
}

Within App\Http\Kernel class add the 'admin' middleware we just created (see the second line)

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'admin' => \App\Http\Middleware\AdminMiddleware::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];


Route::get('/admin', function () {
    //
})->middleware(['auth', 'admin']);

  • Related