/** * Sync the connected Facebook user. * * If User is logged in: * a. but doesn't have a facebook account associated, try to associate it. * * If User is not logged in: * b. but have a facebook account associated, try to log the user in. * c. and doesn't have a facebook account associated, * 1. try to automatically create an account and associate it (if $this->createUser). * 2. try to log the user in, afterwards. * * @return boolean True if successful, false otherwise. */ private function __syncFacebookUser() { if (!isset($this->Controller->Auth)) { return false; } // set Auth to a convenience publiciable $Auth = $this->Controller->Auth; if (!$this->__initUserModel()) { return false; } // if you don't have a facebook_id field in your user table, throw an error if (!$this->User->hasField('facebook_id')) { $this->__error("Facebook.Connect handleFacebookUser Error. facebook_id not found in {$Auth->userModel} table."); return false; } // check if the user already has an account // User is logged in but doesn't have a if ($Auth->user('id')) { $this->hasAccount = true; $this->User->id = $Auth->user($this->User->primaryKey); if (!$this->User->field('facebook_id')) { $this->User->saveField('facebook_id', $this->uid); } return true; } else { // attempt to find the user by their facebook id $this->authUser = $this->User->findByFacebookId($this->uid); //if we have a user, set hasAccount if (!empty($this->authUser)) { $this->hasAccount = true; } elseif (empty($this->authUser) && $this->createUser) { $this->authUser[$this->User->alias]['facebook_id'] = $this->uid; $this->authUser[$this->User->alias][$this->modelFields['password']] = $Auth->password(FacebookInfo::randPass()); if ($this->__runCallback('beforeFacebookSave')) { $this->hasAccount = $this->User->save($this->authUser, array('validate' => false)); } else { $this->authUser = null; } } //Login user if we have one if ($this->authUser) { $this->__runCallback('beforeFacebookLogin', $this->authUser); $Auth->authenticate = array('Form' => array('fields' => array('username' => 'facebook_id', 'password' => $this->modelFields['password']))); if ($Auth->login($this->authUser[$this->model])) { $this->__runCallback('afterFacebookLogin'); } } return true; } }