Search code examples
yii2yii2-advanced-app

Yii2 Automatically Login after Registration


I'm creating a website using yii2 framework. I have a problem in registration. I have a modal in home and it contains the sign up form. Now when i trying to register, Yes it saved successful but it only stay in the modal. Now i want is after registering it will automatically login.

This is my sign up form_:

<div class="row">
    <div class="col-lg-12">
        <?php yii\widgets\Pjax::begin(['id' => 'sign-up']) ?>
            <?php $form = ActiveForm::begin(['id' => 'form-signup', 'options' => ['data-pjax' => true]]); ?>
                <div class="row">
                <div class="col-sm-6">
                <?= $form->field($model, 'role')->dropDownList(['2' => 'User', '1' => 'Encoder', '3' => 'Admin']) ?>
                <?= $form->field($model, 'username')->textInput(['placeholder' => 'Username....']) ?>
                <?= $form->field($model, 'email')->textInput(['placeholder' => 'Email....']) ?>
                <?= $form->field($model, 'password')->passwordInput(['placeholder' => 'Password.....']) ?>
                </div>
                 <div class="col-sm-6">
                <?= $form->field($model, 'confirmPassword')->passwordInput(['placeholder' => 'Confirm Password.....']) ?>
                <?= $form->field($model, 'first_name')->textInput(['placeholder' => 'First Name....']) ?>
                <?= $form->field($model, 'middle_name')->textInput(['placeholder' => 'Middle Name....']) ?>
                <?= $form->field($model, 'last_name')->textInput(['placeholder' => 'Last Name....']) ?> 
                </div>
                </div>
                <center>
                <?= $form->field($model, 'verifyCode')->widget(Captcha::className()) ?>               
                </center>
                <div class="form-group">
                    <?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button', 'style' => 'width: 100%; padding: 10px;']) ?>
                </div>
            <?php ActiveForm::end(); ?>
        <?php yii\widgets\Pjax::end() ?>
    </div>
</div>

This is my model:

class SignupForm extends Model
{
public $role;
public $username;
public $email;
public $password;
public $first_name;
public $middle_name;
public $last_name;
public $confirmPassword;
public $verifyCode;

public function rules()
{
    return [
        ['role', 'required'],
        ['username', 'trim'],
        ['username', 'required'],
        ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
        ['username', 'string', 'min' => 2, 'max' => 20],
        ['email', 'trim'],
        ['email', 'required'],
        ['email', 'email'],
        ['email', 'string', 'max' => 30],
        ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
        ['password', 'required'],
        ['password', 'string', 'min' => 6],
        ['first_name', 'trim'],
        ['first_name', 'required'],
        ['middle_name', 'trim'],
        ['middle_name', 'required'],
        ['last_name', 'trim'],
        ['last_name', 'required'],
        ['verifyCode', 'captcha'],
        ['verifyCode', 'required'],
        [['confirmPassword'], 'compare', 'compareAttribute' => 'password', 'message' => 'Passwords do not match.'],

    ];
  }

/**
 * Signs user up.
 *
 * @return User|null the saved model or null if saving fails
 */
public function signup()
{
    if (!$this->validate()) {
        return null;
    }

    $user = new User();
    $user->username = $this->username;
    $user->email = $this->email;
    $user->setPassword($this->password);
    $user->generateAuthKey();
    $user->role = $this->role;
    $user->first_name = $this->first_name;
    $user->middle_name = $this->middle_name;
    $user->last_name = $this->last_name;

    return $user->save() ? $user : null;
}
}

This is my controller:

  public function actionSignup()
{
    $model = new SignupForm();
    if ($model->load(Yii::$app->request->post())) {
        if ($user = $model->signup()) {
            if (Yii::$app->getUser()->login($user)) {
                return $this->goHome();
            }
        }
    }

    return $this->renderAjax('signup', [
        'model' => $model,
    ]);
}

I don't have any ideas, I think my codes is correct but i don't know why is not working.

UPDATED

  • When i clicked the button signup it stay only in the modal and when i clicked it again the button the validations is working. It means it saves to database but not automatically login.

Solution

  • you should get the user identity for login

    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
    
            if ($user = $model->signup()) {
                $identity = User::findOne(['username' => $model->$username]);
                 if (Yii::$app->user->login($identity)) {
                    return $this->goHome();
                }
            }
        }
    
        return $this->renderAjax('signup', [
            'model' => $model,
        ]);
    }
    

    see this for more http://www.yiiframework.com/doc-2.0/guide-security-authentication.html

    http://www.yiiframework.com/doc-2.0/yii-web-user.html