Laravel每个用户一个会话 [英] Laravel one session per user

查看:105
本文介绍了Laravel每个用户一个会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何仅允许每个用户一个会话. 因此,如果某人在已经登录用户帐户后尝试登录,则第一个会话将被销毁,并且将被注销以仅允许当前会话.

I'm trying to figure out how to only allow one session per user. So if someone tries to log in when he already logged in his user account, the first session will be destroyed and will be logged out to allow the current session only.

我正在关注:如何在Laravel中保持每个用户的单个会话.但是我不知道该把这些代码放在哪里:

I'm following this: How to keep single session per user in Laravel . But i don't know where I should put these lines of codes:

/**
 * Swap a user session with a current one
 * 
 * @param \App\User $user
 * @return boolean
 */
protected function swapUserSession($user)
{
    if (!($user instanceof \App\User)) {
        return false;
    }

    $new_session_id = Session::getId(); //get new session_id after user sign in
    $last_session = Session::getHandler()->read($user->last_session_id); // retrive last session

    if ($last_session) {
        Session::getHandler()->destroy($user->last_session_id);
    }

    $user->last_session_id = $new_session_id;
    $user->save();

    return true;
}

我当前正在使用Laravel 5.1,所以我可以找到的唯一用于Auth的控制器是AuthController.php,但它说要放在LoginController.php上

I'm currently using Laravel 5.1, so The only controller I can find for the Auth is AuthController.php but it says to put it on the LoginController.php

推荐答案

如果使用文件驱动程序,则可以将以下方法添加到App \ Http \ Controllers \ Auth \ AuthController.php(在Laravel 5.2中进行测试)

If you're using the file driver you can add the following method to App\Http\Controllers\Auth\AuthController.php (tested in Laravel 5.2)

/**
 * Only allow one concurrent session per user
 *
 * @param  Request  $request
 * @param  User  $user
 * @return Response
 */
protected function authenticated(Request $request, User $user)
{
    Session::put('user_id', $user->id);

    $files = array_diff(scandir(storage_path('framework/sessions')), array('.', '..', '.gitignore'));

    foreach ($files as $file) {
        $filepath = storage_path('framework/sessions/' . $file);
        $session = unserialize(file_get_contents($filepath));

        if ($session['user_id'] === $user->id && $session['_token'] !== Session::get('_token')) {
            unlink($filepath);
        }
    }

    return redirect()->intended($this->redirectPath());
}

这篇关于Laravel每个用户一个会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆