Today when I want to create user profile page for my website and want to create system users can manage his active sessions in this system need
- View active sessions Browsers and platform
- See what is current session
- remove unwanted active sessions
How we can do this?
I Find this solutions to save my users user_id
into session table
Yii2 database session - store additional attributes and user information
Logging out specified user, listing who's online by using DB sessions
But there is another problem in implementing this issue: how to classify user sessions based on their browser and platform, and I found this solution.
I added another column to the session database, and inside it, using this class and the code below I saved the browser information and user platform information.
'components' => [
//...
'session' => [
'class' => 'yii\web\DbSession',
'writeCallback' => function ($session) {
$user_browser = null;
if (!Yii::$app->user->isGuest) {
$browser = new \BrowserDetection();
$user_browser = "{$browser->getName()}-{$browser->getPlatform()}" . ($browser->is64bitPlatform() ? "(x64)" : "(x86)") . ($browser->isMobile() ? "-Mobile" : "-Desktop");
}
return [
'user_id' => Yii::$app->user->id,
'last_write' => new \yii\db\Expression('NOW()'),
'browser_platform' => $user_browser
];
}
],
// ...
]
note : you add other data to your session table
But to find the current session, I encountered a problem when I checked Yii::$app->session->id
and returned the empty string value and I found the solution in the link below.
Blank Session ID in Module's BeforeAction
in Yii2-Advanced I create frontend\components\baseController
and extend all controllers from it and create beforeAction()
and open session in it something like this:
namespace frontend\components;
class BaseController extends \yii\web\Controller
{
public function beforeAction($action)
{
if (parent::beforeAction($action))
{
Yii::$app->session->open();
return true;
}
return false;
}
}
At the end I create ActiveRecord model for session database and use it in profile page to show or remove user sessions
来源:https://stackoverflow.com/questions/45537969/how-to-create-user-session-manage-system-in-yii2-with-dbsession