Session problems in cakephp 2.x using sdk facebook in production

I am trying to use PHP PHP sdk with cakephp 2.x for login purpose. And it works with debug mode 1 or 2, but it doesn’t work with debug mode 0. It seems that the session is not working properly in production. I tried this many times on the Internet, but did not get the right solution for me.

I read these two threads in detail, but did not deal with this problem. https://github.com/facebook/php-graph-sdk/issues/473 How to integrate Facebook login with cakephp 2.x?

I use these two functions in the AppController to login.

public function beforeFilter()
{
    $this->disableCache();

    $this->Facebook = new Facebook(array(
        'app_id'                => 'appId',
        'app_secret'            => 'appSecret',
        'default_graph_version' => 'v2.7',
    ));

    $this->Auth->allow(['.....']);
}

public function login()
{
    if (!session_id()) {
        session_start();
    }
    $this->loadModel("User");

    $user_id = $this->Session->read('Auth.User.id');

    $fb          = $this->Facebook->getRedirectLoginHelper();
    $permissions = ['email']; // Optional permissions

    $callback_url = HTTP_ROOT . 'login';
    $fb_login_url = $fb->getLoginUrl($callback_url, $permissions);

    $this->set('fb_login_url', $fb_login_url);

    if (!empty($user_id)) {
        //redirect to profile page if already logged in
        $this->redirect(... . );
    }

    //local login request
    if ($this->request->is('post')) {
        ......
    }

    // when facebook login is used
    elseif ($this->request->query('code')) {
        try {
            $accessToken = $fb->getAccessToken();

        } catch (\Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error
            $this->Session->setFlash('Graph returned an error: ' . $e->getMessage(), 'error');
            $this->redirect($this->referer());
        } catch (\Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues
            $this->Session->setFlash('Facebook SDK returned an error: ' . $e->getMessage(), 'error');
            $this->redirect($this->referer());
        }

        if (!isset($accessToken)) {
            if ($fb->getError()) {
                header('HTTP/1.0 401 Unauthorized');
                $this->Session->setFlash("Error: " . $fb->getError() . "\n", 'error');
                $this->Session->setFlash("Error Code: " . $fb->getErrorCode() . "\n", 'error');
                $this->Session->setFlash("Error Reason: " . $fb->getErrorReason() . "\n", 'error');
                $this->Session->setFlash("Error Description: " . $fb->getErrorDescription() . "\n", 'error');
                $this->redirect($this->referer());
            } else {
                header('HTTP/1.0 400 Bad Request');
                $this->Session->setFlash('Bad request', 'error');
                $this->redirect($this->referer());
            }
        }

        // Logged in
        $oAuth2Client = $this->Facebook->getOAuth2Client();

        $tokenMetadata = $oAuth2Client->debugToken($accessToken);
        $tokenMetadata->validateAppId('1200125790051089'); // Replace {app-id} with your app id
        $tokenMetadata->validateExpiration();

        if (!$accessToken->isLongLived()) {
            try {
                $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
            } catch (\Facebook\Exceptions\FacebookSDKException $e) {
                $this->Session->setFlash('Error getting long-lived access token: ' . $helper->getMessage() . "</p>\n\n", 'error');
                $this->redirect($this->referer());
            }
        }

        $_SESSION['fb_access_token'] = (string) $accessToken;
        $fb_access_token             = (string) $accessToken;

        if (isset($accessToken)) {
            try {
                // Returns a `Facebook\FacebookResponse` object
                $response = $this->Facebook->get('/me?fields=id,first_name,last_name,email', $accessToken);
            } catch (\Facebook\Exceptions\FacebookResponseException $e) {
                $this->Session->setFlash('Graph returned an error: ' . $e->getMessage(), 'error');
                $this->redirect($this->referer());
            } catch (\Facebook\Exceptions\FacebookSDKException $e) {
                $this->Session->setFlash('Facebook SDK returned an error: ' . $e->getMessage(), 'error');
                $this->redirect($this->referer());
            }

            $fb_user = $response->getGraphUser();

            // We will varify if a local user exists first
            $local_user = $this->User->find('first', array(
                'conditions' => array('facebook_id' => $fb_user['id']),
            ));

            // If exists, we will log them in
            if ($local_user) {
                $this->Auth->login($local_user['User']);
            } else {
                // we will create new user with facebook_id and log them in
                $data['User'] = array(.........);

                // You should change this part to include data validation
                $new_user = $this->User->save($data);
                $this->Auth->login($new_user['User']);
            }
            // redirect to profile page here
        }
    }
}
+4
source share

Source: https://habr.com/ru/post/1662395/


All Articles