CakePHP Check Session exists in database

authentication, cakephp

Solution

Generally, you want to switch Session handling to Database, so you can delete stale sessions when you detect the same user logs in with a different `session_id`.

The steps, to give you an idea:

Switch Session handling to Database

Configure::write('Session.save', 'database');

Create `cake_sessions` table

cd app         
Console/cake schema create Sessions

You would then see the following:

Cake Schema Shell
---------------------------------------------------------------

The following table(s) will be dropped.
cake_sessions
Are you sure you want to drop the table(s)? (y/n) 
[n] > y
Dropping table(s).
cake_sessions updated.

The following table(s) will be created.
cake_sessions
Are you sure you want to create the table(s)? (y/n) 
[y] > y
Creating table(s).
cake_sessions updated.
End create.

Assuming you bind `session_id` to `user_id` by

$this->Session->write('user_id', 123456);

Iterate through `data` field at your session database and delete the row off if the same `user_id` enters your site and with a different `session_id`.

Unfortunately, CakePHP stores `data` as `serialize()`-ed data. You will have to either iterate through each of the rows at `cake_sessions` table to look for matching `user_id` contained in seralized `data` to delete.

Or, just to give you an idea, you can use the following SQL for an approximate method to delete the associated row:

DELETE FROM `cake_sessions` WHERE `cake_sessions`.`data` LIKE '%123456%';

That way the old user who has the old `session_id` will not be able to continue on the site as the logged in user.

Problem

Im Using CakePHP 2.2.1 and im trying to improve my User Authentication with the Auth Component. When Users try to log in from multiple locations they get individual session IDs, what i want to do is kill the old session so the user cannot log in from multiple locations at the same time. I converted how CakePHP saves its sessions using this post cakephp prevent user login from multiple locations at the same time but no answer was given on how to kill off the old session when the new one is created. I thought about creating a Session Model and using that to select the records but im not sure if thats a safe route to go with. I also read through the CakePHP documentation on the Session Component and CakeSession Datasource hoping there might be a hint but i wasnt able to find anything. Any advice would be greatly appreciated.

Original source