See also: http://oauth.net/
Since: 2.0
Author: Paul Klimov (klimov.paul@gmail.com)
Inheritance: extends BaseClient, implements yii\authclient\ClientInterface
Exemple #1
0
 public static function clientUser(BaseOAuth $client)
 {
     $attributes = ['name' => $client->getName(), 'service_id' => $client->id];
     /**
      * @var self $model
      */
     if (!($model = self::findOne($attributes))) {
         $model = new self(array_merge($attributes, ['created_at' => time(), 'data' => json_encode($client->getUserAttributes())]));
         $model->save(false);
         $user = new User(['username' => $model->name . $model->id, 'status' => User::STATUS_ACTIVE]);
         $user->save(false);
         $model->updateAttributes(['user_id' => $user->id]);
         return $user;
     }
     return $model->user;
 }
 /**
  * Creates test OAuth client instance.
  * @return BaseOAuth oauth client.
  */
 protected function createOAuthClient()
 {
     $oauthClient = $this->getMock(BaseOAuth::className(), ['setState', 'getState', 'composeRequestCurlOptions', 'refreshAccessToken', 'apiInternal']);
     $oauthClient->expects($this->any())->method('setState')->will($this->returnValue($oauthClient));
     $oauthClient->expects($this->any())->method('getState')->will($this->returnValue(null));
     return $oauthClient;
 }
Exemple #3
0
 /**
  *
  * @param BaseOAuth $client
  */
 public function successCallback($client)
 {
     $tokenParams = $client->getAccessToken()->getParams();
     $attributes = $client->getUserAttributes();
     if ($attributes['state'] == 'err') {
         throw new NotFoundHttpException($attributes['desc']);
     }
     $user = new User();
     $user->id = 'userdata';
     $user->userData = $attributes['customer'];
     $user->accessToken = $tokenParams['access_token'];
     $user->refreshToken = $tokenParams['refresh_token'];
     $user->authKey = time() . rand(10000, 99999);
     $user->save();
     Yii::$app->user->login($user, $tokenParams['expires_in']);
 }
Exemple #4
0
 /**
  * Grab the user's ungrabbed posts from Facebook
  * 
  * @param \yii\authclient\BaseOAuth $client
  */
 public static function grabSocial(\yii\authclient\BaseOAuth $client)
 {
     if ($client->getId() === 'facebook') {
         $token = $client->getAccessToken();
         \Facebook\FacebookSession::enableAppSecretProof(false);
         $session = new \Facebook\FacebookSession($token->getToken());
         $request = new \Facebook\FacebookRequest($session, 'GET', "/me/posts");
         $response = $request->execute()->getResponse();
         $posts = $response->data;
         foreach ($posts as $post) {
             if (!Fbposts::find()->where('post_id = :pid', ['pid' => $post->id])->exists()) {
                 $fbpost = new Fbposts(['user_id' => Yii::$app->user->id, 'post_id' => $post->id, 'message' => isset($post->message) ? $post->message : $post->story, 'created_time' => $post->created_time]);
                 $fbpost->save();
             }
         }
     }
 }
 public static function clientUser(BaseOAuth $client)
 {
     $attributes = ['name' => $client->getName(), 'service_id' => $client->id];
     /**
      * @var static $model
      */
     if (!($model = static::findOne($attributes))) {
         $model = new static(array_merge($attributes, ['created_at' => time(), 'data' => json_encode($client->getUserAttributes())]));
         $model->save(false);
         /** @var User $userClass */
         $userClass = User::childClass();
         /** @var User $user */
         $user = new $userClass(['username' => $model->name . '_' . $model->id, 'email' => $model->name . '_' . $model->id, 'status' => $userClass::STATUS_ACTIVE]);
         $user->save(false);
         $model->updateAttributes(['user_id' => $user->id]);
         return $user;
     }
     return $model->user;
 }
Exemple #6
0
 /**
  * @inheritdoc
  */
 public function createApiRequest()
 {
     $request = parent::createApiRequest();
     // ensure correct event handlers order :
     $request->off(Request::EVENT_BEFORE_SEND, [$this, 'beforeRequestSend']);
     $request->on(Request::EVENT_BEFORE_SEND, [$this, 'beforeRequestSend']);
     return $request;
 }
Exemple #7
0
 /**
  * Creates token from its configuration.
  * @param array $tokenConfig token configuration.
  * @return OAuthToken token instance.
  */
 protected function createToken(array $tokenConfig = [])
 {
     $tokenConfig['tokenParamKey'] = 'access_token';
     return parent::createToken($tokenConfig);
 }
Exemple #8
0
 /**
  * @param BaseOAuth $client
  * @throws \yii\db\Exception
  */
 public function onAuthSuccess($client)
 {
     \Yii::info('start auth client: ' . $client->getId(), 'authClient');
     $attributes = $client->getUserAttributes();
     /* @var $userAuthClient UserAuthClient */
     $userAuthClient = UserAuthClient::find()->where(['provider' => $client->getId(), 'provider_identifier' => ArrayHelper::getValue($attributes, 'id')])->one();
     if (\Yii::$app->user->isGuest) {
         if ($userAuthClient) {
             // Все просто идет авторизация
             $userAuthClient->provider_data = $attributes;
             $userAuthClient->save();
             $user = $userAuthClient->user;
             \Yii::$app->user->login($user);
         } else {
             // Регистрация
             /**
              * @var $user User
              */
             $user = null;
             //Если соц сеть вернула нам email то на него можно опираться.
             if ($emailFromAuthClient = ArrayHelper::getValue($attributes, 'email')) {
                 //Нашли email
                 $userEmailModel = CmsUserEmail::find()->where(['value' => $emailFromAuthClient])->one();
                 if ($userEmailModel) {
                     if ($userEmailModel->user) {
                         $user = $userEmailModel->user;
                     }
                 }
             }
             if (!$user) {
                 $userClassName = \Yii::$app->cms->getUserClassName();
                 $user = new $userClassName();
                 $user->populate();
                 if (!$user->save()) {
                     \Yii::error("Не удалось создать пользователя: " . serialize($user->getErrors()), 'authClient');
                     return false;
                 }
                 //Тут можно обновить данные пользователя.
                 if ($login = ArrayHelper::getValue($attributes, 'screen_name')) {
                     $user->username = $login;
                     if (!$user->save()) {
                         \Yii::error("Не удалось обновить данные пользователя: " . serialize($user->getErrors()), 'authClient');
                     }
                 }
                 //Тут можно обновить данные пользователя.
                 if ($login = ArrayHelper::getValue($attributes, 'login')) {
                     $user->username = $login;
                     if (!$user->save()) {
                         \Yii::error("Не удалось обновить данные пользователя: " . serialize($user->getErrors()), 'authClient');
                     }
                 }
                 if ($email = ArrayHelper::getValue($attributes, 'email')) {
                     $user->email = $email;
                     if (!$user->save()) {
                         \Yii::error("Не удалось обновить данные пользователя: " . serialize($user->getErrors()), 'authClient');
                     }
                 }
                 if ($name = ArrayHelper::getValue($attributes, 'name')) {
                     $user->name = $name;
                     if (!$user->save()) {
                         \Yii::error("Не удалось обновить данные пользователя: " . serialize($user->getErrors()), 'authClient');
                     }
                 }
                 $firstName = ArrayHelper::getValue($attributes, 'first_name');
                 $lastName = ArrayHelper::getValue($attributes, 'last_name');
                 if ($firstName || $lastName) {
                     $user->name = $lastName . " " . $firstName;
                     if (!$user->save()) {
                         \Yii::error("Не удалось обновить данные пользователя: " . serialize($user->getErrors()), 'authClient');
                     }
                 }
             }
             //$transaction = $user->getDb()->beginTransaction();
             $auth = new UserAuthClient(['user_id' => $user->id, 'provider' => $client->getId(), 'provider_identifier' => (string) $attributes['id'], 'provider_data' => $attributes]);
             if ($auth->save()) {
                 //$transaction->commit();
                 Yii::$app->user->login($user);
                 if (!$user->image) {
                     try {
                         if ($photoUrl = ArrayHelper::getValue($attributes, 'photo')) {
                             $file = \Yii::$app->storage->upload($photoUrl, ['name' => $user->name]);
                             $user->link('image', $file);
                         }
                     } catch (\Exception $e) {
                     }
                 }
                 if (!$user->image) {
                     try {
                         if ($photoUrl = ArrayHelper::getValue($attributes, 'avatar_url')) {
                             $file = \Yii::$app->storage->upload($photoUrl, ['name' => $user->name]);
                             $user->link('image', $file);
                         }
                     } catch (\Exception $e) {
                     }
                 }
             } else {
                 \Yii::error("Не удалось создать социальный профиль: " . serialize($auth->getErrors()), 'authClient');
             }
         }
     } else {
         // user already logged in
         if (!$userAuthClient) {
             // add auth provider
             $userAuthClient = new UserAuthClient(['user_id' => \Yii::$app->user->identity->id, 'provider' => $client->getId(), 'provider_identifier' => (string) $attributes['id'], 'provider_data' => $attributes]);
             if (!$userAuthClient->save()) {
                 print_r($userAuthClient->getErrors());
                 die('no');
             }
         } else {
             $userAuthClient->provider_data = $attributes;
             $userAuthClient->save();
         }
     }
 }
Exemple #9
0
 /**
  * Composes HTTP request CUrl options, which will be merged with the default ones.
  * @param string $method request type.
  * @param string $url request URL.
  * @param mixed $params request params.
  * @return array CUrl options.
  * @throws Exception on failure.
  */
 protected function composeRequestCurlOptions($method, $url, $params)
 {
     $curlOptions = [];
     switch ($method) {
         case 'GET':
             $curlOptions[CURLOPT_URL] = $this->composeUrl($url, $params);
             break;
         case 'POST':
             $curlOptions[CURLOPT_POST] = true;
             if (!empty($params)) {
                 $curlOptions[CURLOPT_POSTFIELDS] = is_array($params) ? !parent::paramsHaveFile($params) ? http_build_query($params, null, '&', PHP_QUERY_RFC3986) : $params : $params;
             }
             $authorizationHeader = $this->composeAuthorizationHeader($params);
             if (!empty($authorizationHeader)) {
                 $curlOptions[CURLOPT_HTTPHEADER][] = $authorizationHeader;
             }
             break;
         case 'HEAD':
             $curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
             if (!empty($params)) {
                 $curlOptions[CURLOPT_URL] = $this->composeUrl($url, $params);
             }
             break;
         default:
             $curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
             if (!empty($params)) {
                 $curlOptions[CURLOPT_POSTFIELDS] = $params;
             }
     }
     return $curlOptions;
 }