glembo
glembo

Reputation: 426

Laravel 5.6 shopping cart based on session token authentication issue

I created a custom e-commerce system based on laravel. The shopping cart is identified by the session token of laravel (session['_token']) and is devided in a cart table and a cartProduct table. The whole system is working as expected.

Unfortunately the session['_token'] is changed as soon as the users has succesfully logged in. After this the whole cart of the old session is not correct idetified because the token has changed.

Now my questions:

If you need further information about the system please let me know in the comments and I will provide you with details.

cart - table: enter image description here

cart_products - table: enter image description here

Upvotes: 0

Views: 2045

Answers (2)

Lukas Pierce
Lukas Pierce

Reputation: 1259

The main idea safe old session id before attempt login

  1. Change action name in route

    Route::post("/login", 'LoginController@doLogin');
    
  2. Modify LoginController

    class LoginController extends Controller {
    
       use AuthenticatesUsers;
    
       private $old_session_id;
    
       public function doLogin(Request $request) {
         //remember old session id
         $this->old_session_id = $request->session()->getId();
    
         //call AuthenticatesUsers trait method
         return $this->login($request);
       }
    
       //override trait method
       protected function authenticated(Request $request, $user) {
          //sync cart
          $cart = Cart::whereSessionId($this->old_session_id)->first();
       }
    
    }
    

Upvotes: 0

glembo
glembo

Reputation: 426

I found a working solution. I modified the LoginController and updated the sendLoginResponse method to my needs:

protected function sendLoginResponse(Request $request)
    {
        // save old session token (shopping cart is related to this one)

        $old_session_token = session()->get('_token');

        // regenerate new session (prevent session fixation)
        $request->session()->regenerate();

        // get new session token
        $new_session_token = session()->get('_token');

        // update session token in cart table

        $shopping_cart = Cart::where('session_token', $old_session_token)->first();

        $shopping_cart->session_token = $new_session_token;

        $shopping_cart->save();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }

This code updates the old token with the new one.

Upvotes: 1

Related Questions