当使用用户 ID 而不是账号密码登录系统时,如何退出其它设备的登录状态?
背景:
从5.6开始提供了logoutOtherDevices()来清除当前用户的其他会话,原理是通过对密码进行重新Hash::make后对比password_hash(会写入数据库,看updated_at字段就知道。),清除session_attributes中password_hash与本次密码Hash不同的Session。
问题:
当直接使用Auth::loginUsingId(1, $remember = false);登录系统时,可没有密码用于Hash,那么如何清除本用户在其它设备的登录状态?(或者说如何找出本用户的SessionID?正在试验中……)
方法:
Auth::loginUsingId(1, $remember = false); //登录指定用户 ID 的用户到应用上
<?php
namespace Illuminate\Auth;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Contracts\Auth\SupportsBasicAuth;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Session\Session;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class SessionGuard implements StatefulGuard, SupportsBasicAuth
{
……
/**
* Invalidate other sessions for the current user.
*
* The application must be using the AuthenticateSession middleware.
*
* @param string $password
* @param string $attribute
* @return bool|null
*/
public function logoutOtherDevices($password, $attribute = 'password')
{
if (! $this->user()) {
return;
}
$result = tap($this->user()->forceFill([
$attribute => Hash::make($password),
]))->save();
if ($this->recaller() ||
$this->getCookieJar()->hasQueued($this->getRecallerName())) {
$this->queueRecallerCookie($this->user());
}
$this->fireOtherDeviceLogoutEvent($this->user());
return $result;
}
……
}
推荐文章: