How to login correctly from different tables in Yii2.0

Hi,

Now when the admin logs in , he can see the congratulations page. Here in index.php I have written a below code.

<div class="jumbotron">
        <h1>Congratulations!</h1>

		<h2>Logged in from : <?php echo Yii::$app->user->id?>

It prints

 Logged in from : admin-1

I want that the result should be

Logged In from admin table

And also how to distinguish that user is of type admin and employee and then get the identity if user based on type.

Thats two different questions.

By testing whether \app\identity\User::$_user is an instance of app\model\Admin or app\model\Employee. You are free to add any methods that you like to app\identity\User.

Yii::$app->user->getIdentity() will return an instance of app\identity\User. So you could easily expose app\identity\User::$_user through a getter to access to original user model.

Hi,
When I tried logging with different tables I have a table called auth_assignment for RBAC. In that Table there is a field user_id where user_id is set to the foreign key with EmpId from employee table. Now as I have admins table with AdminId so should I add relation from user_id to AdminId of Admins table?

I tried to implement but it is not working properly.

One year laterā€¦

Why is user_id a foreign key to the Employee Table? Itā€™s been a while that Iā€™ve worked with that, but as can be seen here, the user_id is just a VARCHAR without any constraints or foreign keys on it. So if you use the implementation that I suggested a year ago (the patch file is still accessible), you can simply write the value that app\models\MultiUser::getId() returns into that field and the RBAC module should resolve it correctly to the corresponding user (and table).

In my case auth_assignment has field user_id which is set to int data type. and relation is specified with EmpId of Employee table. Following is the image showing the relationship specified.

I tried as you suggested for logging using two tables. Now I have the following actions in SiteController

 public function actionIndex()
    {

       return $this->redirect('index.php?r=site/login');
		$this->layout= "loginlayout";
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
		$this->layout= "loginlayout";
        if (!Yii::$app->user->isGuest) {
            return $this->redirect(['/dashboard/index']);
        }
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {



              return $this->redirect(['/dashboard/index']);
			}


		else
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {

		$this->layout= "loginlayout";
		Yii::$app->user->logout();
        return $this->goHome();
    }

Here when I launch the login page and enter valid username and password, then the same login page is redirected.

As you suggested I made changes to the RBAC database tables and MultiUser.php. I assigned role Admin to emp id 5 and role Field Officer to empid 2 and 4. I have the below groupdetails controller and rule to check if the user is Field Officer. If i login with empid 2 username and password, then it logs I canā€™t access create. The error I got is ā€œYou have no access to create groupsā€. I have assigned the role Field Officer to empid 2 in auth_assignment table. Why it is giving me error? In auth_assignment table the field user_id will contain the idā€™s of employee table?

<?php

namespace app\controllers;

use Yii;
use app\models\Groupdetails;
use app\models\GroupdetailsSearch;
use yii\web\Controller;

use yii\filters\VerbFilter;
use app\models\FieldofficerRule;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
/**
 * GroupdetailsController implements the CRUD actions for Groupdetails model.
 */
class GroupdetailsController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Groupdetails models.
     * @return mixed
     */
    public function actionIndex()
    {
		if (!Yii::$app->user->can('indexAll')) {
       $searchModel = new GroupdetailsSearch();
		}
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Groupdetails model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
		if(\Yii::$app->user->can('viewGroup', ['model' => $model]))
		{
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
		}
		else
		{
		   throw new ForbiddenHttpException("You can't view other groups details");
		}
    }

    /**
     * Creates a new Groupdetails model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {

		 if(\Yii::$app->user->can('createGroup'))
		{
		//$this->layout = 'layoutfile';
        $model = new Groupdetails();
		$model->scenario = 'create';



       if ($model->load(Yii::$app->request->post()) ) {





			$identity = Yii::$app->user->identity;
			$eid = $identity->id;

			$model->id = $eid;

			$model->filepath = UploadedFile::getInstance($model, 'filepath');

		    $model->Photo = Yii::$app->security->generateRandomString().'.'.$model->filepath->extension;

			$model->save(false);

		    $model->filepath->saveAs('uploadedgroupimages/'.$model->Photo);




            return $this->redirect(['view', 'id' => $model->GroupId]);
        } else {
            return $this->render('create', [
                'model' => $model,

            ]);
        }
		}
		else
		{
		   throw new ForbiddenHttpException("You have no access to create groups");
		}




    }

    /**
     * Updates an existing Groupdetails model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
		$model = $this->findModel($id);
		if(\Yii::$app->user->can('updateGroup', ['model' => $model]))
        {
		$oldimage = $model->Photo;


        if ($model->load(Yii::$app->request->post())) {



			$model->filepath = UploadedFile::getInstance($model, 'filepath');

			if($model->filepath == null)
			{
					$model->save(false);



			}
			else{

				unlink('uploadedgroupimages/'.$oldimage);

				$model->Photo = Yii::$app->security->generateRandomString().'.'.$model->filepath->extension;

			   	$model->save(false);

				$model->filepath->saveAs('uploadedgroupimages/'.$model->Photo);



            return $this->redirect(['view', 'id' => $model->GroupId]);
        }
		}else {
            return $this->render('update', [
                'model' => $model,

            ]);
        }
		}
		else
		{
		     throw new ForbiddenHttpException("You can't update other groups details");
		}

    }

    /**
     * Deletes an existing Groupdetails model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
		$model = $this->findModel($id);
		if(\Yii::$app->user->can('deleteGroup', ['model' => $model]))
		{




		 $oldimage = $model->Photo;

		 unlink('uploadedgroupimages/'.$oldimage);


		$model->delete();

        return $this->redirect(['index']);
		}
		else
		{
		  throw new ForbiddenHttpException("You can't delete other groups details");
		}

    }

    /**
     * Finds the Groupdetails model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Groupdetails the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Groupdetails::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

Also my Field Officer rule is as follows:

<?php

namespace app\rbac;

use yii\rbac\Rule;
use app\models\Groupdetails;

/**
 * Checks if authorID matches user passed via params
 */
class FieldofficerRule extends Rule
{
    public $name = 'isfieldofficer';

    /**
     * @param string|int $user the user ID.
     * @param Item $item the role or permission that this rule is associated with
     * @param array $params parameters passed to ManagerInterface::checkAccess().
     * @return bool a value indicating whether the rule permits the role or permission it is associated with.
     */
    public function execute($user, $item, $params)
    {
        return isset($params['model']) ? $params['model']->id == $user : false;
    }
}

Hi the getId() returns the result as employee-2. But I want to get only 2 which is the id of the employee which is in the user_id field for auth_assignment table.

Hi,

As so far, I can log in and log out from different tables.

As discussed so far, I have a MultiUser model in models folder as you told. I have employee table with id, FirstName,LastName, etc. I have admin table with columns id, Name,username,password,etc.

I have a groupdetails table where there is columns such as GroupId, id, GroupName,StageOfGroup,etc where relationship is assigned as One employee has many groupdetails. I have created all the permissions, roles and assigned permissions to admin and field officer role as stated in RBAC in yii2.

I have not created a foreign key reference in employee and auth_assignment table.
Now in auth_assignment table I have following

image

Now when I log as admin, I can create, view, update and delete the group details.

But when I login as employee whose id is 2 then I can only create groupdetails, but I cannot view, update and delete those groupdetails which I have created.

Following is the groupdetails controller

<?php

namespace app\controllers;

use Yii;
use app\models\Groupdetails;
use app\models\GroupdetailsSearch;
use yii\web\UploadedFile;
use yii\web\Controller;

use yii\filters\VerbFilter;
use app\models\FieldofficerRule;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
/**
 * GroupdetailsController implements the CRUD actions for Groupdetails model.
 */
class GroupdetailsController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Groupdetails models.
     * @return mixed
     */
    public function actionIndex()
    {

       $searchModel = new GroupdetailsSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Groupdetails model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
		$model=$this->findModel($id);
 if(\Yii::$app->user->can('viewGroup',['model'=>$model]))
		{
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
		}
		else
		{
		   throw new ForbiddenHttpException("You can't view other groups details");
		}
    }

    /**
     * Creates a new Groupdetails model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {



		 if(\Yii::$app->user->can('createGroup'))
		{
		//$this->layout = 'layoutfile';
        $model = new Groupdetails();




       if ($model->load(Yii::$app->request->post()) ) {

            $model->id=\Yii::$app->user->identity->getOnlyid();
			$model->save(false);




            return $this->redirect(['view', 'id' => $model->GroupId]);
        } else {
            return $this->render('create', [
                'model' => $model,

            ]);
        }
		}
		else
		{

		   throw new ForbiddenHttpException("You have no access to create groups");
		}




    }

    /**
     * Updates an existing Groupdetails model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
		$model = $this->findModel($id);

		if(\Yii::$app->user->can('updateGroup', ['model' => $model]))
        {



        if ($model->load(Yii::$app->request->post())) {


				$model->id=\Yii::$app->user->identity->getOnlyid();
					$model->save();



            return $this->redirect(['view', 'id' => $model->GroupId]);
        }
		else {
            return $this->render('update', [
                'model' => $model,

            ]);
        }
		}



		else
		{
		     throw new ForbiddenHttpException("You can't update other groups details");
		}

    }

    /**
     * Deletes an existing Groupdetails model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
		$model = $this->findModel($id);
		if(\Yii::$app->user->can('deleteGroup', ['model' => $model]))
		{









		$model->delete();

        return $this->redirect(['index']);
		}
		else
		{
		  throw new ForbiddenHttpException("You can't delete other groups details");
		}

    }

    /**
     * Finds the Groupdetails model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Groupdetails the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Groupdetails::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

I tried to change the user_id field in auth_assignment table where Admin role is to id 1 of admin table and Field officer to employee whose id is 2, but still it is the same.

How should I resolve this?