/** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { $user = new User(); $user->username = $this->username; $user->email = $this->email; $user->setPassword($this->password); $user->generateAuthKey(); if ($user->save()) { $auth = Yii::$app->authManager; $authorRole = $auth->getRole('User'); $auth->assign($authorRole, $user->getId()); return $user; } } return null; }
public function onAuthSuccess($client) { $attributes = $client->getUserAttributes(); /* @var $auth Auth */ $auth = Auth::find()->where(['source' => $client->getId(), 'source_id' => $attributes['id']])->one(); if (Yii::$app->user->isGuest) { if ($auth) { // login $user = User::findOne(['id' => $auth->user_id]); Yii::$app->user->login($user); } else { // signup if (isset($attributes['email']) && User::find()->where(['email' => $attributes['email']])->exists()) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "User with the same email as in {client} account already exists but isn't linked to it. Login using email first to link it.", ['client' => $client->getTitle()])]); } else { $password = Yii::$app->security->generateRandomString(6); $user = new User(['username' => $attributes['name'], 'email' => $attributes['email'], 'password' => $password]); $user->generateAuthKey(); $user->generatePasswordResetToken(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $authManager = Yii::$app->authManager; $authorRole = $authManager->getRole('User'); $authManager->assign($authorRole, $user->id); $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id']]); if ($auth->save()) { $transaction->commit(); Yii::$app->user->login($user); } else { print_r($auth->getErrors()); } } else { print_r($user->getErrors()); } } } } else { // user already logged in if (!$auth) { // add auth provider $auth = new Auth(['user_id' => Yii::$app->user->id, 'source' => $client->getId(), 'source_id' => $attributes['id']]); $auth->save(); } } }