Couldn't login user when working with 2 types of user( model)s

[size="4"]General[/size]

I have 2 different user tables in my db:


doctor

and


patient

. I created models and CRUD for both tables. Then, I’ve fully completed doctor registration, login. Everything is OK for now. Also registration of patient’s done. But couldn’t login to system as patient.

[size="6"]What steps will reproduce the problem?[/size]

[size="4"]Registration action[/size]


public function actionRegister()

{

    // because I was set default identity class to 'frontend\models\Doctor'

   // and must be changed to Patient class for registering patients.

    Yii::$app->setComponents([

        'user' => [

            'identityClass' => 'frontend\models\Patient',

            'enableAutoLogin' => true,

            'class' => 'yii\web\User',

        ]

    ]);

    $model = new Patient();

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

//            if ($model->validate()) { // creates problem with captcha

        if (UploadedFile::getInstance($model, 'file')) {

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

            $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);

            $model->image = 'uploads/' . $model->file->baseName . '.' . $model->file->extension;

        }

        if ($user = $model->PatientSignUp(Yii::$app->request->post('blood'), Yii::$app->request->post('sex'), $image = $model->image)) {

            if (Yii::$app->getUser()->login($user)) {

                Yii::$app->session->setFlash('success', 'Qeydiyyat uğurla başa çatdı.');

                //echo Yii::$app->user->getIdentity()->attributes['patient_id']; // this line returns nothing

                                //exit();                           // without this line !!!

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

            }

        } else {

            Yii::$app->session->setFlash('error', 'Qeydiyyat zamanı xəta baş verdi.');

            return $this->render('create', [

                'model' => $model,

            ]);

        }

//            }

    }

    return $this->render('create', [

        'model' => $model,

    ]);

}



[size="5"]PatientSignUp function[/size]




public function PatientSignUp($blood_id, $sex, $image = null)

{

    $user = new Patient();

    $user->patient_id = $this->generateID();

    $user->patient_username = $this->patient_username;

    $user->name = $this->name;

    $user->surname = $this->surname;

    $user->email = $this->email;

    $user->address = $this->address;

    $user->blood_id = $blood_id;

    $user->sex = $sex;

    $user->phone = $this->phone;

    $user->dob = $this->dob;

    $user->image = $image;

    $user->setPassword($this->password);


    if ($user->save())

    return $user;


    return null;

}



in my layouts/main.php I set some conditions:




<ul>

........

<li><a href="<?= \yii\helpers\Url::toRoute(['site/contact']) ?>">Contact Us</a></li>

<?php if (!Yii::$app->user->isGuest) {

    if (Yii::$app->getComponents()['user']['identityClass'] === 'frontend\models\Doctor') {

        echo '<li>' . Html::a(

                'Logout (' . Yii::$app->user->identity->doctor_username . ')',

                ['doctor/logout'],

                ['data-method' => 'post']) . '</li>';

    }

    else {

        echo '<li>' . Html::a(

                'Logout (' . Yii::$app->user->identity->doctor_username/*getIdentity()->attributes['patient_username']*/ . ')',

                ['patient/logout'],

                ['data-method' => 'post']) . '</li>';

    }

} else {

    echo '<li>' . Html::a(

            'Login',

            ['site/login']) . '</li>';

} ?>

.......

</ul>



[size="6"]What is the expected result?[/size]

Shortly: username of patient (string)

The same codes working perfectly: in menu bar I can see


Logout (_doctorusername_)

. But in patient mode it fails (not showing


Logout(_patientusername_)

and Login appears.

[size="6"]What do I get instead?[/size]

nothing (null)

[size="4"]Additional info[/size]


| Yii version | 2.0.8 advanced template |

| PHP version | 7.0.4 |

| DB | MySQL 5.7 |

| Operating system | Windows 10 Home |

| Web server | Apache/2.4.18 |

| Browser Chrome | 50.0.2661.102 m (64-bit) |


Are you having the same problem as this guy?

http://www.yiiframework.com/forum/index.php/topic/70944-multiple-identities-in-the-frontend/

Yes. But I solved my problem using these lines




Yii::$app->setComponents([

    'user' => [

        'identityClass' => 'frontend\models\Patient',

        'enableAutoLogin' => true,

        'class' => 'yii\web\User',

    ]

]);



in my other other controller.

Thanks for link. It helped me a lot to improve my code quality ::) :) ;)

I’m wondering if it is OK to have multiple user identity classes in an application.

Isn’t there any possibility that a patient and a doctor may share the same id?

No, it’s impossible. I give different id to every user using the function below.




private function generateID()

{

	if (function_exists('com_create_guid') === true)

		return trim(com_create_guid(), '{}');

	else {

		$data = openssl_random_pseudo_bytes(16);

		$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100

		$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10

		return vsprintf('%s%s%s%s%s%s%s%s', str_split(bin2hex($data), 4));

#		echo sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));

	}

}



Is it ok?

I see.

Yes, I think it’s OK, although I would take the other way that I suggested in the topic that Patrick has pointed.

Oh, I see.

I got the help from that topic ;) :)