コード例 #1
0
ファイル: AuthChoice.php プロジェクト: lowbase/yii2-user
 /**
  * Добавляем обрамление div
  * @param ClientInterface $client
  * @param null $text
  * @param array $htmlOptions
  * @throws InvalidConfigException
  */
 public function clientLink($client, $text = null, array $htmlOptions = [])
 {
     echo Html::beginTag('div', ['class' => $this->clientCssClass]);
     $text = Html::tag('span', $text, ['class' => 'auth-icon ' . $client->getName()]);
     if (!array_key_exists('class', $htmlOptions)) {
         $htmlOptions['class'] = 'auth-link ' . $client->getName();
     }
     $viewOptions = $client->getViewOptions();
     if (empty($viewOptions['widget'])) {
         if ($this->popupMode) {
             if (isset($viewOptions['popupWidth'])) {
                 $htmlOptions['data-popup-width'] = $viewOptions['popupWidth'];
             }
             if (isset($viewOptions['popupHeight'])) {
                 $htmlOptions['data-popup-height'] = $viewOptions['popupHeight'];
             }
         }
         echo Html::a($text, $this->createClientUrl($client), $htmlOptions) . '<br>';
     } else {
         $widgetConfig = $viewOptions['widget'];
         if (!isset($widgetConfig['class'])) {
             throw new InvalidConfigException('Widget config "class" parameter is missing');
         }
         /* @var $widgetClass Widget */
         $widgetClass = $widgetConfig['class'];
         if (!is_subclass_of($widgetClass, AuthChoiceItem::className())) {
             throw new InvalidConfigException('Item widget class must be subclass of "' . AuthChoiceItem::className() . '"');
         }
         unset($widgetConfig['class']);
         $widgetConfig['client'] = $client;
         $widgetConfig['authChoice'] = $this;
         echo $widgetClass::widget($widgetConfig);
     }
     echo Html::endTag('div');
 }
コード例 #2
0
 /**
  * Composes client auth URL.
  * @param ClientInterface $provider external auth client instance.
  * @return string auth URL.
  */
 public function createClientUrl($provider)
 {
     $this->autoRender = false;
     $url = $this->getBaseAuthUrl();
     $url[$this->clientIdGetParamName] = $provider->getId();
     return Url::to($url);
 }
コード例 #3
0
ファイル: SiteController.php プロジェクト: iw-reload/iw
 /**
  * 
  * @param \yii\authclient\ClientInterface $client
  * @return type
  */
 public function successCallback($client)
 {
     // TODO: Group FK's to one local user.
     //       Otherwise, if we log in via FB and another time via google, we
     //       end up with two local accounts.
     if (!$this->action instanceof \yii\authclient\AuthAction) {
         throw new \yii\base\InvalidCallException("successCallback is only meant to be executed by AuthAction!");
     }
     $attributes = $client->getUserAttributes();
     $externalUser = new AuthForm();
     $externalUser->authProvider = $client->getName();
     $externalUser->externalUserId = array_key_exists('id', $attributes) ? $attributes['id'] : null;
     if ($externalUser->validate()) {
         Yii::info('AuthForm validated.');
         if ($externalUser->isRegistered()) {
             Yii::info('ExternalUser is registered. Logging in and redirecting to game/index.');
             $externalUser->login();
             return $this->action->redirect(Url::to(['site/index'], true));
         } else {
             throw new \yii\base\InvalidCallException("Can't login non-registered user '{$externalUser->externalUserId}@{$externalUser->authProvider}'!");
         }
     } else {
         // TODO error. Throw, display actionError?
         Yii::info('AuthForm couldn\'t be validated. Errors: ' . print_r($externalUser->errors, true));
         Yii::info('Client attributes: ' . print_r($attributes, true));
     }
 }
コード例 #4
0
ファイル: SiteController.php プロジェクト: sly13/maps
 /**
  * Ищет в базе и возвращает авторизующийся социальный профиль.
  * Если не найден — сохраняет и возвращает.
  *
  * @param ClientInterface $client
  *
  * @throws Exception
  * @return SocialProfile
  */
 protected function findSocialProfile(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     if (null === ($profile = SocialProfile::findOne(['socialId' => $attributes['user_id']]))) {
         $profile = $this->save($attributes);
     }
     return $profile;
 }
コード例 #5
0
ファイル: Model.php プロジェクト: cookyii/module-account
 /**
  * @param \yii\authclient\ClientInterface $Client
  * @return static
  */
 public static function createLog(\yii\authclient\ClientInterface $Client)
 {
     $AuthResponse = new static();
     $AuthResponse->client = $Client->getId();
     $attributes = $Client->getUserAttributes();
     $AuthResponse->response = Json::encode($attributes);
     return $AuthResponse;
 }
コード例 #6
0
 /**
  * @param \yii\authclient\ClientInterface $Client
  * @throws \yii\base\NotSupportedException
  */
 public function authSuccessCallback(\yii\authclient\ClientInterface $Client)
 {
     $AuthResponse = new \resources\User\Auth\Response();
     $AuthResponse->client = $Client->getId();
     $attributes = $Client->getUserAttributes();
     $AuthResponse->response = Json::encode($attributes);
     $UserQuery = \resources\User::find();
     switch ($Client->getId()) {
         case 'facebook':
             $UserQuery->byFacebookId($attributes['id']);
             break;
         case 'github':
             $UserQuery->byGithubId($attributes['id']);
             break;
         case 'google':
             $UserQuery->byGoogleId($attributes['id']);
             break;
         case 'linkedin':
             $UserQuery->byLinkedinId($attributes['id']);
             break;
         case 'live':
             $UserQuery->byLiveId($attributes['id']);
             break;
         case 'twitter':
             $UserQuery->byTwitterId($attributes['id']);
             break;
         case 'vkontakte':
             $UserQuery->byVkontakteId($attributes['id']);
             break;
         case 'yandex':
             $UserQuery->byYandexId($attributes['id']);
             break;
     }
     /** @var \resources\User $User */
     $User = $UserQuery->one();
     if ($User instanceof \resources\User) {
         $AuthResponse->result = Json::encode($User->id);
     } else {
         $User = new \resources\User();
         $User->appendClientAttributes($Client);
         if ($User->save()) {
             $User->createSocialLink($Client);
             $AuthResponse->result = Json::encode($User->id);
             AuthManager()->assign(RbacFactory::Role(\frontend\Permissions::ROLE_USER), $User->id);
         } else {
             $AuthResponse->result = Json::encode($User->getErrors());
         }
     }
     $AuthResponse->save();
     if ($User instanceof \resources\User && !$User->isNewRecord) {
         $User->save();
         User()->login($User, 86400);
     }
 }
コード例 #7
0
 /**
  * @param \yii\authclient\ClientInterface $Client
  * @throws \yii\base\NotSupportedException
  */
 public function appendClientAttributes(\yii\authclient\ClientInterface $Client)
 {
     /** @var \cookyii\modules\Account\resources\Account\Model $self */
     $self = $this;
     $attributes = $Client->getUserAttributes();
     switch ($Client->getId()) {
         default:
             $attributes = null;
             break;
         case 'facebook':
             $attributes = $this->appendFacebookAttributes($attributes);
             break;
         case 'instagram':
             $attributes = $this->appendInstagramAttributes($attributes);
             break;
         case 'github':
             $attributes = $this->appendGithubAttributes($attributes);
             break;
         case 'google':
             $attributes = $this->appendGoogleAttributes($attributes);
             break;
         case 'linkedin':
             $attributes = $this->appendLinkedinAttributes($attributes);
             break;
         case 'live':
             $attributes = $this->appendLiveAttributes($attributes);
             break;
         case 'twitter':
             $attributes = $this->appendTwitterAttributes($attributes);
             break;
         case 'vkontakte':
             $attributes = $this->appendVkontakteAttributes($attributes);
             break;
         case 'yandex':
             $attributes = $this->appendYandexAttributes($attributes);
             break;
         case 'odnoklassniki':
             $attributes = $this->appendOdnoklassnikiAttributes($attributes);
             break;
     }
     if (!empty($attributes)) {
         foreach ($attributes as $key => $value) {
             $attr = $self->getAttribute($key);
             if ($self->hasAttribute($key) && empty($attr)) {
                 $self->setAttribute($key, $value);
             }
         }
     }
 }
コード例 #8
0
 public function authenticate(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     $provider = $client->getId();
     $clientId = $attributes['id'];
     $model = SocialAccount::find()->where(['provider' => $provider, 'client_id' => $clientId])->one();
     if ($model === NULL) {
         $model->save(FALSE);
     }
     if (NULL === ($user = $model->getUser())) {
         $this->action->successUrl = Url::to(['/user/registration/connect', 'account_id' => $model->id]);
     } else {
         Yii::$app->user->login($user, UserModule::$rememberMeDuration);
     }
 }
コード例 #9
0
 public function social(ClientInterface $client)
 {
     $user_data = new UserData($client->getName(), $client->getUserAttributes());
     if (Yii::$app->user->isGuest) {
         $user = User::findSocial($user_data->getObjectName(), $user_data->getObjectName());
         if ($user) {
             Login::login($user);
         } else {
             $user_data->save();
         }
     } else {
         User::saveSocial(Yii::$app->user->identity, $user_data);
     }
     Yii::$app->session->set('social', $client->getName());
 }
コード例 #10
0
 /**
  * Logs the user in if this social account has been already used. Otherwise shows registration form.
  *
  * @param  ClientInterface $client
  * @return \yii\web\Response
  */
 public function authenticate(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     $provider = $client->getId();
     $clientId = $attributes['id'];
     if (null === ($account = $this->module->manager->findAccount($provider, $clientId))) {
         $account = $this->module->manager->createAccount(['provider' => $provider, 'client_id' => $clientId, 'data' => json_encode($attributes)]);
         $account->save(false);
     }
     if (null === ($user = $account->user)) {
         $this->action->successUrl = Url::to(['/user/registration/connect', 'account_id' => $account->id]);
     } else {
         \Yii::$app->user->login($user, $this->module->rememberFor);
     }
 }
コード例 #11
0
 public function authenticate(ClientInterface $client)
 {
     // find existing user by service
     if ($this->userService !== null) {
         /** @var User $user */
         $user = Yii::createObject(ModelMapHelper::User());
         $user = $user->loadModel($this->userService->user_id);
         $user->login(UsersModule::module()->loginDuration);
     } else {
         // no user for this pair
         // this is the most hard part
         // create user
         /** @var SocialServiceInterface|BaseClient $client */
         $client->retrieveAdditionalData();
         /** @var RegistrationForm $registrationForm */
         $registrationForm = Yii::createObject(ModelMapHelper::RegistrationForm());
         $this->mapServiceAttributes($client, $registrationForm);
         $user = $registrationForm->socialRegister($client);
         if ($user === false) {
             throw new ErrorException("Unable to register user");
         }
         $userService = $this->createService();
         if ($user->save() === false) {
             throw new ErrorException("Unable to save user:" . var_export($user->errors, true));
         }
         $user->link('services', $userService);
         // check if we need to run post-registration
         $user->login(UsersModule::module()->loginDuration);
         // check if there's some required or recommended fields missing
         foreach (UsersModule::module()->requiredUserAttributes as $attribute) {
             if (empty($user->{$attribute})) {
                 Yii::$app->session->setFlash('info', Yii::t('users', 'Please fill required profile fields.'));
                 $this->redirectToProfileUpdate();
                 return;
             }
         }
         foreach (UsersModule::module()->recommendedUserAttributes as $attribute) {
             if (empty($user->{$attribute})) {
                 //! @todo Add limitation on UsersModule::recommendedFieldsMaxPrompts
                 Yii::$app->session->setFlash('info', Yii::t('users', 'Please fill recommended profile fields.'));
                 $this->redirectToProfileUpdate();
                 return;
             }
         }
     }
 }
コード例 #12
0
 /**
  * Logs the user in if this social account has been already used. Otherwise shows registration form.
  * @param  ClientInterface $client
  * @return \yii\web\Response
  */
 public function authenticate(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     $provider = $client->getId();
     $clientId = $attributes['id'];
     $account = UserAccount::find()->where(['provider' => $provider, 'client_id' => $clientId])->one();
     if ($account === null) {
         $account = \Yii::createObject(['class' => UserAccount::className(), 'provider' => $provider, 'client_id' => $clientId, 'data' => json_encode($attributes), 'created_at' => time()]);
         $account->save(false);
     }
     if (null === ($user = $account->user)) {
         $this->action->successUrl = Url::to(['/site/connect', 'account_id' => $account->id]);
     } else {
         \Yii::$app->user->login($user, 1209600);
         // two weeks
     }
 }
コード例 #13
0
 /**
  * @param Account $user
  */
 private function updateUserInfo(Account $user)
 {
     $attributes = $this->client->getUserAttributes();
     //        $github = ArrayHelper::getValue($attributes, 'login');
     //        if ($user->github === null && $github) {
     //            $user->github = $github;
     //            $user->save();
     //        }
 }
コード例 #14
0
ファイル: SiteController.php プロジェクト: Leammas/i-hunter
 /**
  * This function will be triggered when user is successfuly authenticated using some oAuth client.
  *
  * @param ClientInterface $client
  * @return boolean|Response
  * @throws UnauthorizedHttpException
  */
 public function oAuthSuccess($client)
 {
     // get user data from client
     $userAttributes = $client->getUserAttributes();
     if (isset($userAttributes['emails']) && isset($userAttributes['emails'][0]) && isset($userAttributes['emails'][0]['value'])) {
         $email = $userAttributes['emails'][0]['value'];
         $user = User::find()->byEmail($email)->one();
         if ($user instanceof User) {
             return Yii::$app->user->login($user, 3600 * 24 * 30);
         } else {
             Yii::info('Попытка входа с неразрешенного аккаунта:' . $email . var_export($userAttributes, true), 'site');
             throw new UnauthorizedHttpException('You shall not pass!');
         }
     } else {
         Yii::error('Нет данных аккаунта в ответе OAuth:' . var_export($userAttributes, true), 'site');
         throw new UnauthorizedHttpException('OAuth service error');
     }
 }
コード例 #15
0
 /**
  * Invoked after a successful authentication with a client.
  *
  * @param ClientInterface $client client instance.
  * @return \yii\web\Response
  */
 public function clientLogin(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     $name = $client->getId();
     $dataContract = $this->module->getDataContract();
     $provider = $dataContract->findProvider(['name' => $name, 'clientId' => $attributes['id']]);
     if ($provider === null) {
         $provider = $dataContract->createProvider(['attributes' => ['name' => $name, 'clientId' => $attributes['id'], 'data' => $attributes]]);
         if (!$provider->save(false)) {
             $this->fatalError();
         }
     }
     if ($provider->account !== null) {
         Yii::$app->user->login($provider->account, Module::getParam(Module::PARAM_LOGIN_EXPIRE_TIME));
         return $this->goHome();
     } else {
         return $this->redirect([Module::URL_ROUTE_CONNECT, 'providerId' => $provider->id]);
     }
 }
コード例 #16
0
ファイル: SecurityController.php プロジェクト: kd-brinex/kd
 public function authenticate(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     $provider = $client->getId();
     $clientId = $attributes['id'];
     $account = $this->finder->findAccountByProviderAndClientId($provider, $clientId);
     if ($account === null) {
         $account = \Yii::createObject(['class' => Account::className(), 'provider' => $provider, 'client_id' => $clientId, 'data' => json_encode($attributes)]);
         $account->save(false);
     }
     if (null === ($user = $account->user)) {
         if ($provider == 'kd') {
             $this->action->successUrl = Url::to(['/user/registration/connect', 'account_id' => $account->id, 'provider' => $provider, 'username' => $attributes['username'], 'email' => $attributes['email']]);
         } else {
             $this->action->successUrl = Url::to(['/user/registration/connect', 'account_id' => $account->id]);
         }
     } else {
         \Yii::$app->user->login($user, $this->module->rememberFor);
     }
 }
コード例 #17
0
ファイル: AuthRedSocial.php プロジェクト: alejandrososa/AB
 /**
  * Red Social
  */
 public function autorizar()
 {
     $attributes = $this->client->getUserAttributes();
     $model = new LoginRedSocialForm();
     $model->red_social = $this->client->getName();
     $model->perfil_id = $attributes['id'];
     $model->correo = isset($attributes['email']) ? $attributes['email'] : null;
     $model->nombre = $attributes['first_name'];
     $model->apellido = $attributes['last_name'];
     $model->genero = $attributes['gender'];
     $model->url_perfil = $attributes['link'];
     $model->localidad = $attributes['locale'];
     $model->estado = $attributes['verified'];
     $model->access_token = $this->token_acces;
     $model->imagen = $this->getImagenPerfilFacebook($attributes['id']);
     //Set return url if the user is authenticated. AuthAction will handle the redirect
     if ($returnUrl = $model->autenticarUsuario()) {
         \Yii::$app->user->setReturnUrl($returnUrl);
     }
 }
コード例 #18
0
ファイル: AuthKeysManager.php プロジェクト: lowbase/yii2-user
 /**
  * Меняем ссылки на добавление и удаление ключей
  * @param ClientInterface $client external auth client instance.
  * @param string $text link text, if not set - default value will be generated.
  * @param array $htmlOptions link HTML options.
  * @throws InvalidConfigException on wrong configuration.
  */
 public function clientLink($client, $text = null, array $htmlOptions = [])
 {
     echo Html::beginTag('div', ['class' => 'col-xs-4']);
     $exists = UserOauthKey::findOne(['user_id' => Yii::$app->user->id, 'provider_id' => UserOauthKey::getAvailableClients()[$client->getId()]]);
     if ($exists) {
         $button = Html::a('<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> <span class="hidden-xs">' . Yii::t('user', 'Удалить') . '</span>', Url::toRoute(['auth/unbind', 'id' => $client->getId()]), ['class' => 'btn btn-danger btn-sm', 'onclick' => '$(this).off("click"); return true;']);
     } else {
         $viewOptions = $client->getViewOptions();
         if (isset($viewOptions['popupWidth'])) {
             $htmlOptions['data-popup-width'] = $viewOptions['popupWidth'];
         }
         if (isset($viewOptions['popupHeight'])) {
             $htmlOptions['data-popup-height'] = $viewOptions['popupHeight'];
         }
         $htmlOptions['class'] = 'btn btn-success btn-sm';
         $button = Html::a('<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> <span class="hidden-xs">' . Yii::t('user', 'Добавить') . '</span>', $this->createClientUrl($client), $htmlOptions);
     }
     echo Html::tag('span', $button, ['class' => 'auth-icon ' . $client->getName(), 'style' => 'padding-left: 40px; margin-bottom: 10px;']);
     echo Html::endTag('div');
 }
コード例 #19
0
 /**
  * @param $client
  *
  * TODO
  */
 public function onAuthSuccess(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     /* @var $auth UserAuth */
     $auth = UserAuth::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);
         } else {
             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 {
                 if ($client->signIn()) {
                     $this->redirect('/profile');
                 }
             }
         }
     } else {
         if (!$auth) {
             $auth = new UserAuth(['user_id' => Yii::$app->user->id, 'source' => $client->getId(), 'source_id' => $attributes['id']]);
             $auth->save();
         }
     }
 }
コード例 #20
0
 /**
  * @param \yii\authclient\ClientInterface $Client
  * @throws \yii\base\NotSupportedException
  */
 public function appendClientAttributes(\yii\authclient\ClientInterface $Client)
 {
     $attributes = $Client->getUserAttributes();
     switch ($Client->getId()) {
         default:
             $attributes = null;
             break;
         case 'facebook':
             $attributes = $this->aggregateFacebookAttributes($attributes);
             break;
         case 'github':
             $attributes = $this->aggregateGithubAttributes($attributes);
             break;
         case 'google':
             $attributes = $this->aggregateGoogleAttributes($attributes);
             break;
         case 'linkedin':
             $attributes = $this->aggregateLinkedinAttributes($attributes);
             break;
         case 'live':
             $attributes = $this->aggregateLiveAttributes($attributes);
             break;
         case 'twitter':
             $attributes = $this->aggregateTwitterAttributes($attributes);
             break;
         case 'vkontakte':
             $attributes = $this->aggregateVkontakteAttributes($attributes);
             break;
         case 'yandex':
             $attributes = $this->aggregateYandexAttributes($attributes);
             break;
     }
     if (!empty($attributes)) {
         $this->setAttributes($attributes);
     }
 }
コード例 #21
0
 /**
  * Parse profile
  *
  * @return array
  */
 private function parseProfile()
 {
     $profile = $this->client->getUserAttributes();
     $data = [];
     switch ($this->type) {
         case UserProvider::TYPE_FACEBOOK:
             $data = $this->parseProfileFacebook($profile);
             break;
         case UserProvider::TYPE_VKONTAKTE:
             $data = $this->parseProfileVkontakte($profile);
             break;
         case UserProvider::TYPE_TWITTER:
             $data = $this->parseProfileTwitter($profile);
             break;
     }
     return $data;
 }
コード例 #22
0
ファイル: AuthController.php プロジェクト: dram1008/bogdan
 /**
  * @param \yii\authclient\ClientInterface $client
  */
 public function successCallback($client)
 {
     $attributes = $client->getUserAttributes();
     /** @var \app\services\authclient\authClientInterface $client */
     $client->saveToken();
     if (Yii::$app->user->isGuest) {
         $user = $client->login($attributes);
         if (is_null($user)) {
             $user = $client->register($attributes);
         }
         if (!is_null($user)) {
             Yii::$app->user->login($user);
         }
     } else {
         $client->attach($attributes, Yii::$app->user->identity);
     }
     $client->setAuthFlag();
     Yii::$app->user->setReturnUrl($_SERVER['HTTP_REFERER']);
 }
コード例 #23
0
 /**
  * @param ClientInterface $client
  */
 public function onAuthSuccess($client)
 {
     $attributes = $client->getUserAttributes();
     $email = ArrayHelper::getValue($attributes, 'email');
     /** @var Auth $auth */
     $auth = Auth::find()->where(['source' => $client->getId(), 'source_id' => $attributes['id']])->one();
     if (Yii::$app->user->isGuest) {
         if ($auth) {
             // login
             $user = $auth->user;
             Yii::$app->user->login($user, 3600 * 24 * 30);
         } else {
             // signup
             if (User::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' => $client->getTitle()])]);
             } else {
                 $password = Yii::$app->security->generateRandomString(6);
                 $user = new User(['username' => $attributes['login'], 'email' => $email, 'password' => $password]);
                 $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, 3600 * 24 * 30);
                     } else {
                         print_r($auth->getErrors());
                         die;
                     }
                 } else {
                     print_r($user->getErrors());
                     die;
                 }
             }
         }
     } 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();
         }
     }
 }
コード例 #24
0
 /**
  * Finds an account by client.
  * @param  ClientInterface $client
  * @return AccountQuery
  */
 public function byClient(ClientInterface $client)
 {
     //xiaoma update
     //qq and sina 's attr has no id
     $client_type = $client->getId();
     switch ($client_type) {
         case 'qq':
             $client_id = $client->getUserAttributes()['openid'];
             break;
         case 'sina':
             $client_id = $client->getUserAttributes()['uid'];
             break;
         default:
             $client_id = $client->getUserAttributes()['id'];
             break;
     }
     return $this->andWhere(['provider' => $client->getId(), 'client_id' => $client_id]);
 }
コード例 #25
0
ファイル: AccountQuery.php プロジェクト: someet/yii2-user
 /**
  * Finds an account by client.
  * @param  ClientInterface $client
  * @return AccountQuery
  */
 public function byClient(ClientInterface $client)
 {
     return $this->andWhere(['provider' => $client->getId(), 'unionid' => $client->getUserAttributes()['unionid']]);
 }
コード例 #26
0
ファイル: Connect.php プロジェクト: grutabow/getyii
 /**
  * Checks if provider already connected to user.
  *
  * @param ClientInterface $provider
  * @return bool
  */
 public function isConnected(ClientInterface $provider)
 {
     return $this->accounts != null && isset($this->accounts[$provider->getId()]);
 }
コード例 #27
0
 /**
  * @param \yii\authclient\ClientInterface $Client
  * @throws \yii\web\ForbiddenHttpException
  */
 public function authSuccessCallback(\yii\authclient\ClientInterface $Client)
 {
     $AuthResponse = new \cookyii\modules\Account\resources\Account\Auth\Response();
     $AuthResponse->client = $Client->getId();
     $attributes = $Client->getUserAttributes();
     $AuthResponse->response = Json::encode($attributes);
     /** @var \cookyii\modules\Account\resources\Account $AccountModel */
     $AccountModel = \Yii::createObject(\cookyii\modules\Account\resources\Account::className());
     $AccountQuery = $AccountModel::find();
     switch ($Client->getId()) {
         case 'facebook':
             $AccountQuery->byFacebookId($attributes['id']);
             break;
         case 'github':
             $AccountQuery->byGithubId($attributes['id']);
             break;
         case 'google':
             $AccountQuery->byGoogleId($attributes['id']);
             break;
         case 'linkedin':
             $AccountQuery->byLinkedinId($attributes['id']);
             break;
         case 'live':
             $AccountQuery->byLiveId($attributes['id']);
             break;
         case 'twitter':
             $AccountQuery->byTwitterId($attributes['id']);
             break;
         case 'vkontakte':
             $AccountQuery->byVkontakteId($attributes['id']);
             break;
         case 'yandex':
             $AccountQuery->byYandexId($attributes['id']);
             break;
     }
     $Account = $AccountQuery->one();
     if ($Account instanceof \cookyii\modules\Account\resources\Account) {
         if (true !== ($reason = $Account->isAvailable())) {
             switch ($reason) {
                 default:
                 case true:
                     break;
                 case 'not-activated':
                     $Account->addError('activated', \Yii::t('account', 'Account is not activated.'));
                     break;
                 case 'deleted':
                     $Account->addError('deleted', \Yii::t('account', 'Account removed.'));
                     break;
             }
             $AuthResponse->result = Json::encode($Account->getErrors());
         } else {
             $AuthResponse->result = Json::encode($Account->id);
         }
     } else {
         $Account = $AccountModel;
         $Account->appendClientAttributes($Client);
         if (!empty($Account->email)) {
             $SearchAccount = $AccountModel::find()->byEmail($Account->email)->one();
             if (!empty($SearchAccount)) {
                 $Account = $SearchAccount;
                 $Account->appendClientAttributes($Client);
             }
         } else {
             Session()->set('OAuthResponseClient', $Client);
             Response()->redirect(['/account/sign/fill'])->send();
             exit;
         }
         if ($Account->save()) {
             $Account->createSocialLink($Client);
             $AuthResponse->result = Json::encode($Account->id);
             if (!$Account->can(\common\Roles::USER)) {
                 AuthManager()->assign(RbacFactory::Role(\common\Roles::USER), $Account->id);
             }
         } else {
             $AuthResponse->result = Json::encode($Account->getErrors());
         }
     }
     $AuthResponse->save();
     if ($Account instanceof \cookyii\modules\Account\resources\Account && !$Account->isNewRecord && !$Account->hasErrors()) {
         $Account->save();
         User()->login($Account, 86400);
     } else {
         $errors = $Account->getFirstErrors();
         if (isset($errors['activated'])) {
             throw new \yii\web\ForbiddenHttpException($errors['activated']);
         }
         if (isset($errors['deleted'])) {
             throw new \yii\web\ForbiddenHttpException($errors['deleted']);
         }
     }
 }
コード例 #28
0
 /**
  * @param \yii\authclient\BaseClient $authClient
  * @param Registration $registration
  * @return boolean already all registration data gathered
  * @throws Exception
  */
 protected function handleAuthClientRegistration(ClientInterface $authClient, Registration $registration)
 {
     $attributes = $authClient->getUserAttributes();
     if (!isset($attributes['id'])) {
         throw new Exception("No user id given by authclient!");
     }
     $registration->enablePasswordForm = false;
     if ($authClient instanceof ApprovalBypass) {
         $registration->enableUserApproval = false;
     }
     // do not store id attribute
     unset($attributes['id']);
     $registration->getUser()->setAttributes($attributes, false);
     $registration->getProfile()->setAttributes($attributes, false);
 }
コード例 #29
0
 /**
  * Connects social account to user.
  * @param  ClientInterface $client
  * @return \yii\web\Response
  */
 public function connect(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     $provider = $client->getId();
     $clientId = $attributes['id'];
     $account = $this->finder->findAccountByProviderAndClientId($provider, $clientId);
     if ($account === null) {
         $account = \Yii::createObject(['class' => Account::className(), 'provider' => $provider, 'client_id' => $clientId, 'data' => json_encode($attributes), 'user_id' => \Yii::$app->user->id]);
         $account->save(false);
         \Yii::$app->session->setFlash('success', \Yii::t('user', 'Your account has been connected'));
     } else {
         if (null == $account->user) {
             $account->user_id = \Yii::$app->user->id;
             $account->save(false);
         } else {
             \Yii::$app->session->setFlash('error', \Yii::t('user', 'This account has already been connected to another user'));
         }
     }
     $this->action->successUrl = Url::to(['/user/settings/networks']);
 }
コード例 #30
0
 /**
  * Connects social account to user.
  *
  * @param  ClientInterface $client
  * @return \yii\web\Response
  */
 public function connect(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     $provider = $client->getId();
     $clientId = $attributes['id'];
     if (null === ($account = $this->module->manager->findAccount($provider, $clientId))) {
         $account = $this->module->manager->createAccount(['provider' => $provider, 'client_id' => $clientId, 'properties' => json_encode($attributes), 'user_id' => \Yii::$app->user->id]);
         $account->save(false);
         \Yii::$app->session->setFlash('account_connected', \Yii::t('user', 'Account has successfully been connected'));
     } else {
         \Yii::$app->session->setFlash('account_not_connected', \Yii::t('user', 'This account has already been connected to another user'));
     }
     return $this->redirect(['networks']);
 }