Hemanth
(Hemanthguruhj)
1
I have just created Registration and Login forms using yii2 and mongoDb, Now i want to assign session for login user using id.
What can i do for this. I studied in this http://www.yiiframework.com/doc-2.0/yii-web-session.html But i couldn’t understand.
auticxdi
(Mkungonda)
2
Why not to use Yii2 User class to doing all heavy lifting for you?
action login in siteController [ called by submitted login form ]
public function actionLogin() {
$this->layout = 'login';
if ( !\Yii::$app->user->isGuest )
{
return $this->redirect( ['site/main']);
}
$model = new LoginForm();
if ( $model->load( Yii::$app->request->post() ) && $model->login() )
{
return $this->redirect( ['main' ] );
} else
{
return $this->render( 'login', [
'model' => $model,
] );
}
}
model LoginForm, method that getting called by $model->login() :
public function login() {
if ( $this->validate() ) {
$user = $this->getUser();
$user->last_log = date('d.m.Y');
$UserAtt = new UserAttendance;
$UserAtt->stampAttendance($user->id);
if($user->save()){
return Yii::$app->user->login( $this->getUser(), $this->rememberMe ? 3600 : 0 );
} else {
return false;
}
} else {
return false;
}
}
bulit in login method in user model
public function login(IdentityInterface $identity, $duration = 0)
{
if ($this->beforeLogin($identity, false, $duration)) {
$this->switchIdentity($identity, $duration);
$id = $identity->getId();
$ip = Yii::$app->getRequest()->getUserIP();
if ($this->enableSession) {
$log = "User '$id' logged in from $ip with duration $duration.";
} else {
$log = "User '$id' logged in from $ip. Session not enabled.";
}
Yii::info($log, __METHOD__);
$this->afterLogin($identity, false, $duration);
}
return !$this->getIsGuest();
}