public function successCallback($client) { $attributes = $client->getUserAttributes(); /** @var Auth $auth */ $auth = Auth::find()->where(['source' => $client->getId(), 'source_id' => $attributes['id']])->one(); $attributes['login'] = $attributes['login'] ? $attributes['login'] : $attributes['last_name'] . ' ' . $attributes['first_name']; if (Yii::$app->user->isGuest) { if ($auth) { // login $user = $auth->user; $user->username = $attributes['login']; $user->photo = $attributes['photo']; $user->save(); Yii::$app->user->login($user); } else { // signup if (isset($attributes['email']) && isset($attributes['username']) && 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 { $user = new User(['username' => $attributes['login'], 'email' => $attributes['email'], 'first_name' => $attributes['first_name'], 'last_name' => $attributes['last_name'], 'sex' => $attributes['sex'], 'photo' => $attributes['photo'], 'password' => Yii::$app->security->generateRandomString(6)]); $user->generateAuthKey(); $user->generatePasswordResetToken(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $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(); } } }
/** * Logs in a user. * * @return mixed */ public function onAuthSuccess($client) { $data = Yii::$app->getRequest()->getQueryParam("auth_key"); if (!$this->getInviteKey($data)) { Yii::$app->session->setFlash("error", "Not have permision"); return $this->redirect(["/"]); } $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) { $user = $auth->user; Yii::$app->user->login($user); return $this->redirect("site/user"); } else { // signup $email = isset($attributes['email']) ? $attributes['email'] : ""; $invite = Invitation::find()->where(['send_key' => $data, 'email' => $email])->one(); if (isset($attributes['name']) && !empty($invite)) { $password = Yii::$app->security->generateRandomString(8); if (!isset($attributes['email'])) { $attributes['email'] = ''; } $fileName = null; $picturePath = null; if (isset($attributes['picture']) && isset($attributes['picture']['data']) && isset($attributes['picture']['data']['url'])) { $picturePath = $attributes['picture']['data']['url']; } elseif (isset($attributes['profile_image_url'])) { $picturePath = $attributes['profile_image_url']; } // COMMENT: ADD PHOTO FROM FACEBOOK DATA TO DATABASE method file_put_contents - http://php.net/manual/ru/function.file-put-contents.php if ($picturePath) { $photoFile = file_get_contents($picturePath); $security = new \yii\base\Security(); $fileName = $security->generateRandomString() . '.jpg'; $directory = Yii::getAlias('@frontend/web/' . Yii::$app->params['user-photos-directory']); file_put_contents($directory . DIRECTORY_SEPARATOR . $fileName, $photoFile); } $user = new User(['username' => $attributes['name'], 'email' => $attributes['email'], 'password' => $password, 'image' => $fileName, 'sex' => !empty($attributes['gender']) ? $attributes['gender'] : "", 'country' => !empty($attributes['hometown']['name']) ? $attributes['hometown']['name'] : "", 'created_at' => time(), 'updated_at' => time()]); $user->generateAuthKey(); $user->generatePasswordResetToken(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id'], 'email' => $attributes['email']]); $invite->status = Invitation::STATUS_SIGNUP; $invite->save(); if ($auth->save()) { $transaction->commit(); Yii::$app->user->login($user); return $this->redirect(["/"]); } else { print_r($auth->getErrors()); } } else { print_r($user->getErrors()); } } else { Yii::$app->session->setFlash("error", "Email not equals"); return $this->redirect(['site/invite', 'auth_key' => $data]); } } } 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(); } } }
/** * 用户身份验证 * @param [type] $type 校验类型 * @return [type] 成功返回 true 失败返回 原因 */ public static function auth($projectId, $data = '') { $auth = Auth::find()->where(['project_id' => $projectId, 'state' => Auth::STATE_USE])->asArray()->all(); if (!$auth) { Yii::info("no need check !"); return true; } foreach ($auth as $key => $value) { switch (intval($value['type'])) { //判断是否有新用户校验 case Auth::TYPE_NEW_USER: if (!self::isNewUser()) { return ErrorCodeHelper::CODE_NO_NEW_USER; } break; default: # code... break; } return true; } }
public function onAuthSuccess($client) { /* @var $client \yii\authclient\OAuth2*/ /* @var $user \common\models\User */ $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) { // вход $user = $auth->user; if ($user->status == User::STATUS_NOT_ACTIVE && $user->email == '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "To complete registration, enter the phone number and confirm the e-mail address.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_NOT_ACTIVE && $user->email != '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "To complete registration, enter a phone number.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_DELETED) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "This user is blocked.")]); return $this->redirectUser($url = Url::to(['/ad/view/all'])); } Yii::$app->user->login($user); } else { // регистрация if (isset($attributes['email']) && ($user = User::findOne(['email' => $attributes['email']]))) { // Если пользователь регитрировался ранее через форму регистации. if ($user) { if ($user->status == User::STATUS_DELETED) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "User <strong> {email} </strong> blocked.", ['email' => $user->email])); } elseif ($user->auths->source) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Authorization using the email address <strong> {email} </strong> is already happening through the account <strong> {auths} </strong>.\n Log on using the account <strong> {auths} </strong> or use the link <strong> Forgot your password? </strong> for email <strong> {email} </strong> to restore the password..", ['email' => $user->email, 'auths' => $user->auths->source])]); } else { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Authorization using the email address <strong> {email} </strong> has successfully passed through the registration form. Click on the link <strong> Forgot your password? </strong> to restore the password.", ['email' => $user->email])); } } return $this->redirectUser($url = Url::to(['/main/login'])); } else { // Полученные данные заносим в переменные /* @var $email string */ /* @var $first_name string */ /* @var $last_name string */ if (Yii::$app->request->get('authclient') == 'google') { $first_name = $attributes['name']['givenName']; $last_name = $attributes['name']['familyName']; $email = $attributes['emails'][0]['value']; } elseif (Yii::$app->request->get('authclient') == 'yandex') { $first_name = $attributes['first_name']; $last_name = $attributes['last_name']; $email = $attributes['default_email']; } elseif (Yii::$app->request->get('authclient') == 'facebook') { $names = explode(' ', $attributes['name']); $first_name = $names[0]; $last_name = $names[1]; $email = $attributes['email']; } elseif (Yii::$app->request->get('authclient') == 'vkontakte') { $first_name = $attributes['first_name']; $last_name = $attributes['last_name']; $email = false; } elseif (Yii::$app->request->get('authclient') == 'twitter') { $names = $attributes['name']; $names = explode(' ', $names); $first_name = $names[0]; $last_name = $names[1]; $email = false; } elseif (Yii::$app->request->get('authclient') == 'linkedin') { $first_name = $attributes['first_name']; $last_name = $attributes['last_name']; $email = $attributes['email']; } $password = Yii::$app->security->generateRandomString(6); if ($email == false) { $email = ''; } $user = new User(['email' => $email, 'password' => $password, 'status' => User::STATUS_NOT_ACTIVE, 'country_id' => 182]); $user->generateAuthKey(); $user->generateSecretKey(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id']]); if ($auth->save()) { /* @var $modelProfile /common/models/UserProfile */ $modelProfile = new UserProfile(); $modelProfile->user_id = $user->id; $modelProfile->first_name = $first_name; $modelProfile->last_name = $last_name; if ($modelProfile->save()) { if (RbacHelper::assignRole($user->id)) { $modelUserPrivilege = new UserPrivilege(); $modelUserPrivilege->link('user', $user); $transaction->commit(); } // если нет емайл, делаем перенаправление на main/finish-reg if ($email == false) { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "To complete registration, enter the phone number and confirm the e-mail address.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } Yii::$app->getSession()->setFlash('success', [Yii::t('app', "To complete registration, enter a phone number.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } } else { d($auth->getErrors()); } } else { /* @var $user \common\models\User */ $user = User::findOne(['email' => $user->email]); // Если пользователь регитрировался ранее через форму регистации. if ($user) { if ($user->status == User::STATUS_DELETED) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "User <strong> {email} </strong> blocked.", ['email' => $user->email])); } elseif ($user->auths->source) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Authorization using the email address <strong> {email} </strong> is already happening through the account <strong> {auths} </strong>.\n Log on using the account <strong> {auths} </strong> or use the link <strong> Forgot your password? </strong> for email <strong> {email} </strong> to restore the password..", ['email' => $user->email, 'auths' => $user->auths->source])]); } else { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Authorization using the email address <strong> {email} </strong> has successfully passed through the registration form. Click on the link <strong> Forgot your password? </strong> to restore the password.", ['email' => $user->email])); } } return $this->redirectUser($url = Url::to(['/main/login'])); } } } } 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(); } } return true; }
/** * handle */ public function handle() { $attributes = $this->client->getUserAttributes(); // common $continue = false; $id = ArrayHelper::getValue($attributes, 'id'); $fullname = ''; $email = ''; // google if ($this->client->getName() == 'google') { $fullname = ArrayHelper::getValue($attributes, 'displayName'); $emails = ArrayHelper::getValue($attributes, 'emails'); $email = $emails[0]['value']; $continue = true; } // facebook if ($this->client->getName() == 'facebook') { $fullname = ArrayHelper::getValue($attributes, 'name'); $email = ArrayHelper::getValue($attributes, 'email'); $continue = true; } if (!$continue) { // Yii::$app->getSession()->setFlash('info', [ // Yii::t('app', 'Flickr'), // ]); //Yii::$app->user->setReturnUrl(Yii::$app->request->referrer); return; } /* @var Auth $auth */ $auth = Auth::find()->where(['source' => $this->client->getId(), 'source_id' => $id])->one(); if (Yii::$app->user->isGuest) { if ($auth) { // login /* @var Account $user */ $user = $auth->user; $this->updateUserInfo($user); Yii::$app->user->login($user, Setting::getValue('rememberMeDuration')); } else { // signup if ($email !== null && Account::find()->where(['email' => $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' => $this->client->getTitle()])]); } else { $password = Yii::$app->security->generateRandomString(6); $user = new Account(['fullname' => $fullname, 'email' => $email, 'password' => $password]); $user->generateAuthKey(); $user->generatePasswordResetToken(); $transaction = Account::getDb()->beginTransaction(); //file_put_contents('D:\log', json_encode($transaction)); if ($user->save()) { $auth = new Auth(['user_id' => $user->id, 'source' => $this->client->getId(), 'source_id' => (string) $id]); if ($auth->save()) { $transaction->commit(); Yii::$app->user->login($user, Setting::getValue('rememberMeDuration')); } else { $transaction->rollBack(); Yii::$app->getSession()->setFlash('error', [Yii::t('app', 'Unable to save {client} account: {errors}', ['client' => $this->client->getTitle(), 'errors' => json_encode($auth->getErrors())])]); } } else { $transaction->rollBack(); Yii::$app->getSession()->setFlash('error', [Yii::t('app', 'Unable to save user: {errors}', ['client' => $this->client->getTitle(), 'errors' => json_encode($user->getErrors())])]); } } } } else { // user already logged in Yii::$app->user->setReturnUrl(Yii::$app->request->referrer); if (!$auth) { // add auth provider $auth = new Auth(['user_id' => Yii::$app->user->id, 'source' => $this->client->getId(), 'source_id' => (string) $attributes['id']]); if ($auth->save()) { /** @var Account $user */ $user = $auth->user; $this->updateUserInfo($user); Yii::$app->getSession()->setFlash('success', [Yii::t('app', 'Linked {client} account.', ['client' => $this->client->getTitle()])]); } else { Yii::$app->getSession()->setFlash('error', [Yii::t('app', 'Unable to link {client} account: {errors}', ['client' => $this->client->getTitle(), 'errors' => json_encode($auth->getErrors())])]); } } else { // there's existing auth Yii::$app->getSession()->setFlash('error', [Yii::t('app', 'Unable to link {client} account. There is another user using it.', ['client' => $this->client->getTitle()])]); } } }
public function onAuthSuccess($client) { /* @var $client \yii\authclient\OAuth2*/ /* @var $user \common\models\User */ $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) { // вход $user = $auth->user; if ($user->status == User::STATUS_NOT_ACTIVE && $user->email == '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите телефон и подтвердите адрес электронной почты.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_NOT_ACTIVE && $user->email != '') { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите номер телефона.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } elseif ($user->status == User::STATUS_DELETED) { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Данный пользователь заблокирован.")]); return $this->redirectUser($url = Url::to(['/main/index'])); } Yii::$app->user->login($user); } else { // регистрация if (isset($attributes['email']) && ($user = User::findOne(['email' => $attributes['email']]))) { // Если пользователь регитрировался ранее через форму регистации. if ($user->status == User::STATUS_ACTIVE) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже успешно прошла через форму регистрации.\n Воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля.")); return $this->redirectUser($url = Url::to(['/main/login'])); } else { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже происходила через аккунт <strong>" . $user->auths->source . "</strong>.\n Выполните вход используя аккаунт <strong>" . $user->auths->source . "</strong> или воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля для\n пользователя с емайл <strong>" . $user->email . "</strong>.", ['client' => $title = $client->getTitle()])]); return $this->redirectUser($url = Url::to(['/main/login'])); } } else { // Полученные данные заносим в переменные /* @var $email string */ /* @var $first_name string */ /* @var $second_name string */ if (Yii::$app->request->get('authclient') == 'google') { $first_name = $attributes['name']['givenName']; $second_name = $attributes['name']['familyName']; $email = $attributes['emails'][0]['value']; } elseif (Yii::$app->request->get('authclient') == 'yandex') { $first_name = $attributes['first_name']; $second_name = $attributes['last_name']; $email = $attributes['default_email']; } elseif (Yii::$app->request->get('authclient') == 'facebook') { $names = explode(' ', $attributes['name']); $first_name = $names[0]; $second_name = $names[1]; $email = $attributes['email']; } elseif (Yii::$app->request->get('authclient') == 'vkontakte') { $first_name = $attributes['first_name']; $second_name = $attributes['last_name']; $email = false; } elseif (Yii::$app->request->get('authclient') == 'twitter') { $names = $attributes['name']; $names = explode(' ', $names); $first_name = $names[0]; $second_name = $names[1]; $email = false; } elseif (Yii::$app->request->get('authclient') == 'linkedin') { $first_name = $attributes['first_name']; $second_name = $attributes['last_name']; $email = $attributes['email']; } $password = Yii::$app->security->generateRandomString(6); $user = new User(['email' => $email, 'password' => $password, 'status' => User::STATUS_NOT_ACTIVE]); $user->generateAuthKey(); $user->generateSecretKey(); $transaction = $user->getDb()->beginTransaction(); if ($user->save()) { $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $attributes['id']]); if ($auth->save()) { /* @var $modelProfile /common/models/Profile */ $modelProfile = new Profile(); $modelProfile->user_id = $user->id; $modelProfile->first_name = $first_name; $modelProfile->second_name = $second_name; if ($modelProfile->save()) { $transaction->commit(); // если нет емайл, делаем перенаправление на main/finish-reg if ($email == false) { Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите телефон и подтвердите адрес электронной почты.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); } Yii::$app->getSession()->setFlash('success', [Yii::t('app', "Для завершения регистрации введите номер телефона.")]); return $this->redirectUser($url = Url::to(['/main/finish-reg', 'id' => $user->id])); //Yii::$app->user->login($user); } } else { //dd($user->errors); print_r($auth->getErrors()); } } else { $user = User::findOne(['email' => $user->email]); // Если пользователь регитрировался ранее через форму регистации. if ($user->status == User::STATUS_ACTIVE) { Yii::$app->getSession()->setFlash('error', Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже успешно прошла через форму регистрации.\n Воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля.")); return $this->redirectUser($url = Url::to(['/main/login'])); } else { Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Авторизация с использованием электронного адреса <strong>" . $user->email . "</strong> уже происходила через аккунт <strong>" . $user->auths->source . "</strong>.\n Выполните вход используя аккаунт <strong>" . $user->auths->source . "</strong> или воспользуйте ссылкой <strong>" . '"Забыли пароль?"' . "</strong> для востанновления пароля для\n пользователя с емайл <strong>" . $user->email . "</strong>.", ['client' => $title = $client->getTitle()])]); return $this->redirectUser($url = Url::to(['/main/login'])); } } } } } 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(); } } return true; }