Вход в Google с использованием cakephp - PullRequest
0 голосов
/ 12 ноября 2018

Я пытаюсь настроить google login theough cakephp, я могу попасть на экран аутентификации, но когда он возвращается на мою веб-страницу, я получаю предупреждение Invalid user, что означает что-то неправильное в передаче имени пользователя.

Можете ли вы помочь мне разобраться с этим больше? Как я могу проверить, я получаю все имя пользователя, адрес электронной почты и фотографии из Google?

login.php:

<script src="https://apis.google.com/js/api:client.js"></script>
  <script>
  var googleUser = {};
  var startApp = function() {
    gapi.load('auth2', function(){
      // Retrieve the singleton for the GoogleAuth library and set up the client.
      auth2 = gapi.auth2.init({
         client_id: 'xxxxxxx.apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        // Request scopes in addition to 'profile' and 'email'
        scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me"
      });
      attachSignin(document.getElementById('googleLoginBtn'));//id of google login button
    });
  };

  function attachSignin(element) { // call this function on your login button

    auth2.attachClickHandler(element, {},
        function(googleUser) {
          setUserDetailsForGoogle(googleUser);
        }, function(error) {
          //alert(JSON.stringify(error, undefined, 2));
        });
  }
function setUserDetailsForGoogle(userData){

    var email=userData.getBasicProfile().getEmail();
    var socialid=userData.getBasicProfile().getId();
    var name=userData.getBasicProfile().getName();
    var gender=1;//userData.getBasicProfile().getGender();

    $.ajax({
      type:'Post',
      data:{email:email,socialid:socialid}, // add the parameters you want to send to save
      url:'users/googleLogin',
      success:function(res){

         var res = $.trim(res);
        if(res=="true")
        {
          location.reload();
        }
        else if(res=="0")
        {
       alert("Not valid user!!");

        }
        else if(res=="error")
        {
          alert("Error in controller!!");
        }

      }
      ,
      error:function(){
        alert("Error in controller!!");
      }
    });   
   }
  </script>

Контроллер пользователей

/*function used to login */
public function googleLogin()
      {
        $this->loadModel("User");

        if ($this->request->is('Ajax')) 
        {
          $data=$_POST;
          $userInfo=$this->User->find('first',array('conditions' =>array('User.email'=>trim($data['email']))));
          if (!empty($userInfo)) // user exist
          {
            $userStatus=trim($userInfo['User']['status']);
            if($userStatus==1)// code to check if user is in active state
            {
              $userID=trim($userInfo['User']['id']);
              $userSocialId=trim($data['socialid']);
              $this->User->updateAll(array('google_id' =>"'".$userSocialId."'"),array('id'=>$userID));
              /* write parameter in session to login */
              $this->Session->write('User.email', trim($userInfo['User']['email']));
              $login_user = $this->Auth->login();


              echo "true";
            }
            else{
              echo "0";//status inactive
            }
          }
          else // new signup- 
          {
            //$userData['User']['first_name']=trim($data['first_name']);
            //$userData['User']['last_name']=trim($data['last_name']);
            $userData['User']['email']=trim($data['email']);
            $userData['User']['status']=1;
            $userData['User']['google_id']=trim($data['socialid']);

            $userData['User']['password']=md5($userPass);
            $this->User->save($userData);
            $userID=$this->User->getLastInsertId();
            $userData['User']['id']=$userID;
            $login_user = $this->Auth->login();


            echo "true";
          }
        }
        else{
          echo "error";
        }
        die;
      }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...