yii 2.0 get logged in user's Session ID - yii2

Am new to Yii, this is the login function (path /basic/controllers/siteController.php), once the users is logged in it will render the login template.
After a user is logged in,
How to get the SESSION ID and store to DB. ?
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
And the model code (path /models/LoginForm.php)
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}

$session = Yii::$app->session->getId();
Will grab the Id. There is a good article on sessions here http://www.bsourcecode.com/yiiframework2/session-handling-in-yii-framework-2-0/
And to save something like:
$model->session = $session;
$model->save();

Related

Yii2 basic validate password

on my users controller I create to use it like registration, I create
public function actionCreate()
{
$model = new Userlogin();
$model->password = null;
if ($model->load(Yii::$app->request->post()) ) {
$model->password = Yii::$app->getSecurity()->generatePasswordHash($model->password);
$model->save();
return $this->redirect(['view', 'id' => $model->uid]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
It's work , it hash the password , but I don't know how to validate the password and make it work in login I did read that I have to use this
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
// all good, logging user in
} else {
// wrong password
}
but I don't know how to use it or where I have to use it
create new action , name it login
be sure to get user hash password from db
public function actionLogin() {
$hash = User::find()->where('username='.$_POST['username'])->One();
if (Yii::$app->getSecurity()->validatePassword($_POST['password'], $hash->password_hash)) {
// all good, logging user in
} else {
// wrong password
}
}
I found the solution for someone if he is in the same situation
in create action
public function actionCreate()
{
$model = new Userlogin();
if ($model->load(Yii::$app->request->post()) ) {
$model->password = Yii::$app->security->generatePasswordHash($model->password);
$model->save();
return $this->redirect(['view', 'id' => $model->uid]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
and in user model change
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
to
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->getSecurity()->validatePassword($password, $this->password);
}
this solution from : https://stackoverflow.com/a/29508651/6562828
I'm using Userlogin as model for user but if anyone is using User model it's in user model
IMHO, the code :
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
// all good, logging user in
} else {
// wrong password
}
can be used for POST method when user do login, and inside "// all good, logging user in", you will do something with Web Session, saving session for specify user, then yay, user logged in,
after that, you can use Session for checking, "is user are logged in ?", etc,
here some good link about Yii Session Handling : http://www.yiiframework.com/doc-2.0/guide-runtime-sessions-cookies.html

Send mail on actionCreate

I have a system that works by the intranet and I would like to know how best to send an alert email in actionCreate?
I did as below, the email is sent correctly, but if the internet is offline an unfriendly error message appears.
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
} else {
// error in saving model
}
}
return $this->render('create', [
'model' => $model,
]);
}
Try this (don't save model if email not sended)
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
$transaction = $model->getDb()->beginTransaction();
try{
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
}
}
catch(Exception $e)
{
$transaction->rollBack();
throwe $e;
//unlik savedFile if exist
}
}
return $this->render('create', [
'model' => $model,
]);
}
or use mail queue to save mail in databases and send via cron

Get a better yii2 rbac extension

Am using yii2 can i get an extension which has a physical interface for managing role based user access (R.B.A.C.).
I have tried using
mdmsoft, dektrium, yii rbac plus but none has any explanation of how
to set up a physical one
I have create a physical interface for managing role based user simply using gii based on the tables provided by the defualt RBAC model provided by Yii2 and extendig the related action for inserting the proper value for assignments, roles, item and item_child. ..
eg: for create Assignments
public function actionCreate()
{
$model = new AuthAssignment();
$auth = Yii::$app->authManager;
if ($model->load(Yii::$app->request->post()) ) {
$auth->assign($auth->getRole($model->item_name), $model->user_id);
return $this->redirect(['view', 'item_name' => $model->item_name, 'user_id' => $model->user_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
and for create Item
public function actionCreate()
{
$model = new AuthItem();
$auth = Yii::$app->authManager;
if ($model->load(Yii::$app->request->post())) {
switch ($model->type) {
case AuthItem::TYPE_ROLE : // 1 = TYPE_ROLE
$role = $auth->createRole($model->name);
$role->data = $model->data;
//$role->ruleName = $model->rule_name;
$role->description = $model->description;
//$role->type = $model->type;
$auth->add($role);
break;
case AuthItem::TYPE_PERMISSION : // 2 = TYPE_PERMISSION
$permission = $auth->createPermission($model->name);
$permission->data = $model->data;
//$permission->ruleName = $model->rule_name;
$permission->description = $model->description;
//$permission->type = $model->type;
$auth->add($permission);
break;
default:
break;
}
return $this->redirect(['view', 'id' => $model->name]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}

Can't upload files reliably in Yii2

I got this method that's intended to upload a file, but sometimes it does so when $this->imageFile is not instantiated. I have no idea why.
public function upload()
{
$path = Url::to('#webroot/images/photos/');
$filename = strtolower($this->username) . '.jpg';
$this->imageFile->saveAs($path . $filename);
return true;
}
I call the method upload() in beforeSave() like this:
public function beforeSave($insert)
{
if(parent::beforeSave($insert)){
if($this->isNewRecord)
{
$this->password = Yii::$app->security->generatePasswordHash($this->password);
}
$this->upload();
return true;
}
else
{
return false;
}
}
I called this method like 100 times with mixed results. I have no idea why this method call doesn't give the same result. It should either never work or always work, but for some reason the code is not deterministic at all.
public function actionCreate()
{
$model = new Member();
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Another thing, when I use this code, I get a file, but the username is blank so I get a .jpeg file without a name.
public function actionCreate()
{
$model = new Member();
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
$model->upload();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
<?php
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
In the If clause you are redirecting to view and $model disappears between requests naturally. But in else you sending $model to view directly. It looks like the buggy section.
The other one, when you move the $model->upload() to actionCreate, you are placing it before If statement but you are loading the post to the model in if clause so, naturally user wasn't loading when you are trying to upload.
If you are prefer to send $model->upload() to action just be sure to call following method before upload. $model->load(Yii::$app->request->post())

Codeigniter Cannot save hashed password to database

I cannot save hashed password to my 'users' table, but if it's not hashed, the password saved. Can everybody help me?
Controller
public function add()
{
$this->data['title'] = 'add new user';
$this->data['subview'] = 'admin/user/add';
$validate = $this->user->validate;
$this->form_validation->set_rules($validate);
if ($this->form_validation->run() == TRUE){
$this->user->insert(array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->user->hash($this->input->post('password'))
));
$this->session->set_flashdata('message', msg_success('Data Saved'));
redirect('admin/user', 'refresh');
}
$this->load->view('admin/_layout_main', $this->data);
}
my Hash function in user_model
public function hash($string)
{
return hash('md5', $string . config_item('encryption_key'));
}
What's wrong with my code, or is there any other way to do it without any library? or How you do it basically to do this using codeigniter? Thanks
EDIT
this is my insert function from MY_Model
public function insert($data, $skip_validation = FALSE)
{
if ($skip_validation === FALSE)
{
$data = $this->validate($data);
}
if ($data !== FALSE)
{
$data = $this->trigger('before_create', $data);
$this->_database->insert($this->_table, $data);
$insert_id = $this->_database->insert_id();
$this->trigger('after_create', $insert_id);
return $insert_id;
}
else
{
return FALSE;
}
}
Im using Jamie Rumbelow Base Model for my base model, and I have follow his tutorial for insert into database