php Laravel 5 -从所有设备注销用户

vcirk6k6  于 2023-06-20  发布在  PHP
关注(0)|答案(5)|浏览(136)

用户已登录。他已经登录了三台不同的电脑。现在用户更改密码。
我想让他从所有设备上注销。默认情况下,如果我们在一台设备上更改密码,其他设备上不会发生任何事情。
首先想到的是在中间件(每个请求)中检查密码,这是不好的,会显着降低性能。
如何在Laravel 5中做到这一点?

*********************************大型网站如何从所有设备注销用户?

2ul0zpep

2ul0zpep1#

在最新版本的Laravel 5.6中
您可以从

auth()->logoutOtherDevices();

登录其他设备
More Info

avkwfej4

avkwfej42#

我做了类似的事情。首先,我在Redis中保存会话。对于每次登录,我在成功验证后保存会话ID,并将其与用户ID(它的数组)相关联。如果用户更改密码,您可以删除除当前用户会话(使用会话ID)之外的所有用户会话。如果用户注销,您可以从用户会话数组中删除会话ID。(我认为你可以使用MySQL或其他存储来保存用户和会话ID之间的关系)
用于保存我使用的会话ID(用户登录时)

$redis = \LRedis::connection();
$redis->sadd('user:sessions:' . $userId, Session::getId());

用于从用户会话阵列中删除会话ID(如果用户注销或手动注销)

$redis->srem('user:sessions:' . $userId, $sessionId);

删除Laravel会话(从其他设备注销用户)

$redis->del('laravel:' . $sessionId);

获取用户的所有会话ID

$redis->smembers('user:sessions:' . $userId);

对于从所有设备注销,请使用循环

$userSessions = $redis->smembers('user:sessions:' . $userId);
$currentSession = Session::getId()
foreach ($userSessions as $sessionId) {
    if ($currentSession == $sessionId) {
        continue;  //if you want don't remove current session
    }

    $redis->del('laravel:' . $sessionId);
    $redis->srem('user:sessions:' . $userId, $sessionId);
}
km0tfn4u

km0tfn4u3#

Laravel文档:
使其他设备上的会话无效
Laravel提供了一种机制,用于使用户在其他设备上活动的会话无效和“注销”,而不会使当前设备上的会话无效。
首先,您应该确保Illuminate\Session\Middleware\AuthenticateSession中间件存在于app/Http/Kernel.php类的Web中间件组中并且未注解:

'web' => [
    // ...
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    // ...
],

然后,您可以在Auth facade上使用logoutOtherDevices方法。此方法要求用户提供其当前密码,您的应用程序应通过输入表单接受该密码:

use Illuminate\Support\Facades\Auth;

Auth::logoutOtherDevices($password);

当调用logoutOtherDevices方法时,用户的其他会话将完全无效,这意味着他们将从之前验证过的所有防护中“注销”。

9rygscc1

9rygscc14#

使其他设备上的会话无效

Laravel provides a mechanism for invalidating and "logging out" a user's sessions that are active on other devices without invalidating the session on their current device.

First, you should make sure that the Illuminate\Session\Middleware\AuthenticateSession middleware is present and un-commented in your app/Http/Kernel.php class' web middleware group:

'web' => [
    // ...
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    // ...
],

Then, you may use the logoutOtherDevices method on the Auth facade. This method requires the user to provide their current password, which your application should accept through an input form:

use Illuminate\Support\Facades\Auth;

Auth::logoutOtherDevices(request('password'));

When the logoutOtherDevices method is invoked, the user's other sessions will be invalidated entirely, meaning they will be "logged out" of all guards they were previously authenticated by.
wbgh16ku

wbgh16ku5#

//Laravel logout user if role changed by admin in active session of user
//1) Create a new middleware that will check if the user's role has been changed and log them out if necessary. Run the following command to generate the middleware:

    php artisan make:middleware CheckUserRole

//2)Open the generated middleware file (app/Http/Middleware/CheckUserRole.php) and implement the handle method. The method should compare the user's current role with the role stored in the session. If they don't match, log out the user. Here's an example implementation:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CheckUserRole
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $user = Auth::user();

            // Check if the user's role has changed
            if ($user->role !== session('role')) {
                Auth::logout();
                return redirect('/login')->with('message', 'Your role has been changed. Please log in again.');
            }
        }

        return $next($request);
    }
}

//3) Register the middleware in the $routeMiddleware array of the app/Http/Kernel.php file. Add the following line to the array:

'role.check' => \App\Http\Middleware\CheckUserRole::class,

//4)Apply the middleware to the relevant routes or route groups. For example, you can apply it to the routes that handle role changes:

Route::middleware('role.check')->group(function () {
    // Routes for changing user roles
});

//5)When an admin changes a user's role, update the user's role and update the role value stored in the user's session. You can accomplish this in your controller or wherever you handle the role change logic. Here's an example:

// Update the user's role
$user->role = 'new_role';
$user->save();

// Update the role value in the session
session(['role' => 'new_role']);

//6) Open the RegisterController located at app/Http/Controllers/Auth/RegisterController.php.

Inside the create method, after the line that creates a new user, add the following code to set the user's role in the session:

// Create a new user
$user = User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
]);

// Set the user's role in the session
session(['role' => $user->role]);

//7)Next, open the LoginController located at app/Http/Controllers/Auth/LoginController.php.

//Inside the authenticated method, after the line that logs in the user, add the following code to set the user's role in the session: 
//Note: (authenticated method not present by default we need to create it.)

use Illuminate\Http\Request;

protected function authenticated(Request $request, $user)
{
    // Log in the user

    // Set the user's role in the session
    session(['role' => $user->role]);

    // Redirect the user
    return redirect()->intended($this->redirectPath());
}

相关问题