L
L
Latnos2021-07-20 22:14:49
Laravel
Latnos, 2021-07-20 22:14:49

How to log out from the specified laravel device?

60f71fb628632813127635.png
It is necessary to implement the functionality as in the picture.
Sessions are stored in the database.
The goal is to log out of the account on the selected device. Those are something similar to Auth::logoutOtherDevices($password), but for one device, not necessarily on the device from which the user is sitting.
Just deleting the session does not help, because it does not throw it out of the account

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Barmunk, 2021-07-21
@Barmunk

There are 3 ways, any one will do
1.

// https://laravel.com/docs/8.x/authentication#invalidating-sessions-on-other-devices

Auth::logoutOtherDevices($currentPassword);

2.
// php artisan make:middleware LogoutUsers
// app/Http/Kernel.php -> $middlewareGroups -> web

<?php
namespace App\Http\Middleware;

use Auth;
use Closure;

class LogoutUsers
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
       if (!auth()->check()) {
            return $next($request);
        }

        $user = Auth::user();

        if ($user->logout === false) {
            $user->update(['logout' => true]);
            Auth::logout();

            return redirect()->route('login');
        }

        return $next($request);
    }
}

3.
//текущий юзер
$user = Auth::user();

//выход конкретного юзера
$userToLogout = User::find(5);
Auth::setUser($userToLogout);
Auth::logout();

//возвращаем текущего юзера
Auth::setUser($user);

P
Peter Slobodyanyuk, 2021-07-25
@PeterLS

One of the options is to check the presence of a row in the database using Middleware (it is possible not at every page refresh, but every minute, for example):
select 1 from sessions where id = 'current_session_id' and user_id = 'current_user_id';
If there is no line (the session was previously deleted from the admin panel), reset the authorization.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question