/** * * @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)); } }
/** * @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(); } } }
/** * Ищет в базе и возвращает авторизующийся социальный профиль. * Если не найден — сохраняет и возвращает. * * @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; }
/** * @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; }
/** * 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]); }
/** * @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(); // } }
/** * @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); } }
/** * 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); } }
/** * @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); } } } }
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()); }
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); } }
/** * 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); } }
/** * 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 } }
/** * 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; }
/** * @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(); } } }
/** * 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'); } }
/** * 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]); } }
/** * @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']); }
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); } }
/** * @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); } }
/** * @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); }
/** * 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']); }
/** * Finds an account by client. * @param ClientInterface $client * @return models\Account|null */ public function findAccountByClient(ClientInterface $client) { return $this->accountQuery->where(['provider' => $client->getId(), 'client_id' => $client->getUserAttributes()['id']])->one(); }
/** * 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']); }
public function getRemoteUser(ClientInterface $client) { $class = $this->remoteUserClass; return $class::findOrCreate($client->getId(), $client->getUserAttributes()['id']); }
/** * Automatically creates user by auth client attributes * * @param \yii\authclient\BaseClient $authClient * @return boolean success status */ public static function createUser(ClientInterface $authClient) { $attributes = $authClient->getUserAttributes(); if (!isset($attributes['id'])) { return false; } $registration = new \humhub\modules\user\models\forms\Registration(); $registration->enablePasswordForm = false; if ($authClient instanceof interfaces\ApprovalBypass) { $registration->enableUserApproval = false; } unset($attributes['id']); $registration->getUser()->setAttributes($attributes, false); $registration->getProfile()->setAttributes($attributes, false); $registration->getGroupUser()->setAttributes($attributes, false); if ($registration->validate() && $registration->register($authClient)) { return $registration->getUser(); } return null; }
/** * @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']); } } }
public static function create(BaseClientInterface $client) { /** @var Account $account */ $account = Yii::createObject(['class' => static::className(), 'provider' => $client->getId(), 'client_id' => $client->getUserAttributes()['id'], 'data' => json_encode($client->getUserAttributes())]); if ($client instanceof ClientInterface) { $account->setAttributes(['username' => $client->getUsername(), 'email' => $client->getEmail()], false); } if (($user = static::fetchUser($account)) instanceof User) { $account->user_id = $user->id; } $account->save(false); return $account; }
/** * 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']]); }
/** * 绑定第三方账号 * @param ClientInterface $client * @return \yii\web\Response */ public function connect(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), 'user_id' => Yii::$app->user->id, 'created_at' => time()]); $account->save(false); Yii::$app->session->setFlash('success', '账号绑定成功'); } else { Yii::$app->session->setFlash('error', '绑定失败,此账号已经绑定过了'); } $this->action->successUrl = Url::to(['/user/setting/networks']); }