作者:lowbas
项目:yii2-use
/**
* Добавляем обрамление 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');
}
作者:sankam-nikoly
项目:yii2-user
/**
* 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);
}
作者:iw-reloa
项目:i
/**
*
* @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));
}
}
作者:sly1
项目:map
/**
* Ищет в базе и возвращает авторизующийся социальный профиль.
* Если не найден — сохраняет и возвращает.
*
* @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;
}
作者:cookyi
项目:module-accoun
/**
* @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;
}
作者:rmrevi
项目:yii2-applicatio
/**
* @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);
}
}
作者:cookyi
项目:module-accoun
/**
* @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);
}
}
}
}
作者:fabristyl
项目:yii2-user-
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);
}
}
作者:kissara
项目:yii2-templat
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());
}
作者:ilya
项目:dektrium-yii2-use
/**
* 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);
}
}
作者:cheaterB
项目:yii2-users-modul
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;
}
}
}
}
作者:grutabo
项目:getyi
/**
* 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
}
}
作者:Leamma
项目:i-hunte
/**
* 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');
}
}
作者:bogiesof
项目:yii2-accoun
/**
* 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]);
}
}
作者:kd-brine
项目:k
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);
}
}
作者:lowbas
项目:yii2-use
/**
* Меняем ссылки на добавление и удаление ключей
* @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');
}
作者:mrbighokag
项目:book-test-yii
/**
* @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();
}
}
}
作者:aroot
项目:module-accoun
/**
* @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);
}
}
作者:dram100
项目:bogda
/**
* @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']);
}
作者:hucongyan
项目:yiiframework.co
/**
* @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();
}
}
}