Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch Authentication from one user to another using Laravel

Tags:

php

laravel

Firstly, I login as user X, and I have a function like:

public function loginAs($userId)
{
    Auth::loginUsingId($userId); // now use Y user
    return response()->json(['logged' => Auth::check(), 'user' => Auth::user()]);

}

and when I try to print out Auth::check() it returns TRUE which is fine so far I am logged now as user Y, the thing is that I do first login as an X user and then switch to another Y user but when I do call some other functoins it seems that the current user logged is still X, and I want to be Y the current user logged... This might have to do something with session or I dont know exactly how to do this thing, would be grateful if someone has any sample or have any idea how to achieve such things in Laravel 5.

like image 615
Artan Avatar asked Dec 15 '15 17:12

Artan


2 Answers

Can you elaborate? I was able to switch users using the following:

use Auth;

class TempController extends Controller
{

    public function index() {
        $user = User::find(1);
        Auth::login($user);
        var_dump(Auth::user()->id); // returns 1
        Auth::logout(); 

        var_dump(Auth::user()); // returns null

        $user = User::find(2);
        Auth::login($user);
        var_dump(Auth::user()->id); // returns 2
        Auth::logout();

    }
}

routes.php

Route::get('/temp', 'TempController@index');

If you run this, you can see the logged in user's id changes.

like image 88
Deciple Avatar answered Sep 17 '22 17:09

Deciple


You should use impersonating There is a weblog post about that http://blog.mauriziobonani.com/easily-impersonate-any-user-in-a-laravel-application/

like image 21
Sina Miandashti Avatar answered Sep 19 '22 17:09

Sina Miandashti