Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DuffterMatze's avatar

Single user login

Hello everyone

In my application i want to make sure the sure is only loged in on one device at the same time.

I then created a field 'singleUserToken' in my user database which is updated to a random 16 characters long string. This one i also store in the session of the user. I also added a check to the Authenticate Middleware to check if the session key is the same as the one stored in the database, if not the session is deleted.

It works so far, but the problem is, that the logout happens after the second click. When the user loges in on a second device it is possible to click one link on the first device which works fine, after that the second link will result in the logout. I hope you understand my problem :D`

public function postSignIn(LoginUserRequest $request)
    {
        $this->validate($request, [
            'username' => 'required|min:4',
            'password' => 'required|min:4'
        ]);

        if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']]))
        {
            $singleUserToken = randomString(16);
            session(['singleUserToken' => $singleUserToken]);

            $user = Auth::user();
            $user->singleUserToken = $singleUserToken;
            $user->update();

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

        $error = 'Benutzername oder Passwort unbekannt!';
        return redirect()->back()->withErrors($error);
    }
public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('/');
            }
        }

        if (Auth::user()->singleUserToken != session('singleUserToken'))
        {
            Session::flush();
        }

        return $next($request);
    }
0 likes
0 replies

Please or to participate in this conversation.