private function createUserProfile(FacebookSession $session, GraphUser $user) { $profile = new UserProfile(); $profilePicReq = new FacebookRequest($session, 'GET', '/me/picture', ['redirect' => 0, 'type' => 'large']); $pic = $profilePicReq->execute()->getGraphObject()->asArray(); $profile['displayName'] = $user->getName(); $profile['profileUrl'] = $user->getLink(); $profile['imageUrl'] = $pic['url']; //TODO other props return $profile; }
public function loginFacebookAction() { $response = array("status" => 0, "message" => "Thao tác không thành công"); if (!empty($this->user)) { $response["status"] = 1; } else { if ($this->request->isPost()) { $acesstoken = $this->request->getPost("accesstoken", null, false); \Facebook\FacebookSession::setDefaultApplication($this->config["FACEBOOK_ID"], $this->config["FACEBOOK_SECRET"]); $session = new \Facebook\FacebookSession($acesstoken); if ($session) { $user_profile = (new \Facebook\FacebookRequest($session, 'GET', '/me', ['fields' => 'id,name,email']))->execute()->getGraphObject(\Facebook\GraphUser::className()); if (!empty($user_profile)) { $email = $user_profile->getEmail(); $id = $user_profile->getId(); $username = explode("@", $email); $username = $username[0] . "_fb_" . $id; $data_user = array("email" => $email, "nickname" => $user_profile->getName(), "username" => $username, "id" => $id); $response = $this->doSocialLogin($data_user); } } } } echo json_encode($response); exit; }
public function facebook() { if (Session::has('flash_notification.message')) { return view('auth.facebook'); } $config = config('services.facebook'); session_start(); FacebookSession::setDefaultApplication($config['id'], $config['secret']); $helper = new FacebookRedirectLoginHelper(route('facebook')); if (!Input::has('code')) { return redirect($helper->getLoginUrl(['email'])); } try { $session = $helper->getSessionFromRedirect(); $profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); } catch (FacebookRequestException $e) { flash('Ne pare rău dar a apărut o eroare. <a href="' . route('facebook') . '">Încearcă din nou</a>.', 'danger'); return redirect()->route('facebook'); } if ($user = $this->userRepo->getByFacebook($profile->getId())) { return $this->loginUser($user); } if (empty($profile->getProperty('email'))) { flash('<p>Nu am putut citi adresa de email asociată contului tău de Facebook.</p> <p>Va trebui să te <a href="' . route('register') . '">înregistezi</a> pe site cu o adresă de email validă</p>', 'danger'); return redirect()->route('facebook'); } if ($this->userRepo->getByEmail($profile->getProperty('email'))) { flash('<p>Adresa de email asociată contului tău de Facebook este deja folosită pe site de altcineva.</p> <p>Va trebui să te <a href="' . route('register') . '">înregistezi</a> pe site cu o altă adresă de email.</p>', 'danger'); return redirect()->route('facebook'); } $user = User::create(['email' => $profile->getProperty('email'), 'first_name' => $profile->getFirstName(), 'last_name' => $profile->getLastName(), 'avatar' => $this->getFacebookPictureUrl($session), 'role_id' => config('auth.default_role_id'), 'confirmed' => 1, 'county_id' => 20]); $user->setMeta('facebook', $profile->getId()); $user->save(); return $this->loginUser($user); }
public function MeAction($params) { $ACCESS_TOKEN = isset($params[self::AUTH_TOKEN]) ? $params[self::AUTH_TOKEN] : null; $USER_ID = isset($params[self::USER_ID]) ? $params[self::USER_ID] : null; // 1. If IS NOT set access token - get from DB by USER_ID if (empty($ACCESS_TOKEN)) { if (empty($USER_ID)) { throw new FacebookSDKException('To get access token you need to supply USER_ID'); } $params_social = array(\Av\MediaUserModel::MEDIA_ID => \Av\MediaModel::MEDIA_FACEBOOK, \Av\MediaUserModel::USER_ID => $USER_ID); $oSocialUserMapper = new \Av\MediaUserModel(); $access_token_info = $oSocialUserMapper->GetCredentials($params_social); $ACCESS_TOKEN = isset($access_token_info[\Av\MediaUserModel::ACCESS_TOKEN]) ? $access_token_info[\Av\MediaUserModel::ACCESS_TOKEN] : null; if (empty($ACCESS_TOKEN)) { throw new FacebookSDKException("No access token is saved for USER_ID {$USER_ID}"); } } $session = new FacebookSession($ACCESS_TOKEN); try { $fbRequest = new FacebookRequest($session, 'GET', '/me'); $user_profile = $fbRequest->execute()->getGraphObject(GraphUser::className()); $this->SetMediaUserId($user_profile->getId()); $this->SetUserEmail($user_profile->getEmail()); $this->SetName($user_profile->getName()); $this->SetVerified($user_profile->getVerified()); } catch (FacebookRequestException $e) { echo __METHOD__ . __LINE__ . " Facebook error during authentication <br><pre>"; var_dump($e); echo "</pre>"; return; } }
public function getCurrentSession() { $helper = new FacebookJavaScriptLoginHelper(); try { if (!empty($_SESSION[self::SessionKey])) { $accessToken = $_SESSION[self::SessionKey]; $_SESSION[self::SessionKey] = null; $session = new \Facebook\FacebookSession($accessToken); } else { $session = $helper->getSession(); $accessToken = $session->getAccessToken(); $_SESSION[self::SessionKey] = (string) $accessToken; } } catch (\Exception $ex) { Record::add(__CLASS__, $ex->getMessage(), $ex); throw $ex; } if ($session) { try { $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); return ['id' => $user_profile->getId(), 'name' => $user_profile->getName()]; } catch (FacebookRequestException $e) { $error = "Exception occured, code: " . $e->getCode() . " with message: " . $e->getMessage(); Record::add(__CLASS__, $error, $e); throw $e; } } }
/** * @Route("/fb") */ public function apiAction() { // ustawiamy ID aplikacji i client secret FacebookSession::setDefaultApplication(FB_APP_ID, FB_APP_SECRET); // tworzymy helpera do zalogowania się $helper = new FacebookRedirectLoginHelper(FB_APP_REDIRECT_URI); // Pobieramy token sesji try { $session = $helper->getSessionFromRedirect(); // Logowanie... } catch (FacebookRequestException $ex) { // jeśli błąd Facebooka } catch (\Exception $ex) { // jeśli ogólnie błąd } if ($session) { // Zalogowany echo 'Logged'; // pobieramy profil zalogowanego użytkownika $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); // obiekt z danymi zalogowanego użytkownika: var_dump($user_profile); } else { // Link do logowania echo '<a href="' . $helper->getLoginUrl(array('email', 'user_friends')) . '">Login</a>'; } return $this->render('Api/api.html.twig'); }
public static function user() { if (self::$user !== false) { return self::$user; } FacebookSession::setDefaultApplication(\Config::get('fb-auth::config.facebook_app_id'), \Config::get('fb-auth::config.facebook_secret')); $token = \Input::get('accessToken'); if (!$token) { $token = \Request::header('FB-Access-Token'); } if (!$token) { self::$user = null; return null; } $session = new FacebookSession($token); try { $me = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); self::$user = \User::from_fb($me); } catch (FacebookAuthorizationException $e) { self::$user = null; } catch (FacebookRequestException $e) { self::$user = null; } catch (\Exception $e) { self::$user = null; } return self::$user; }
public function connect() { // check we have a valid session $appId = Config::inst()->get('FacebookControllerExtension', 'app_id'); $secret = Config::inst()->get('FacebookControllerExtension', 'api_secret'); $session = $this->getFacebookHelper()->getSessionFromRedirect(); if ($session) { $token = $session->getAccessToken(); // get a long lived token by default. Access token is saved in // session. try { $long = $token->extend($appId, $secret); if ($long) { $accessTokenValue = (string) $long; } else { $accessTokenValue = (string) $token; } } catch (Exception $e) { $accessTokenValue = (string) $token; } try { Session::set(FacebookControllerExtension::FACEBOOK_ACCESS_TOKEN, $accessTokenValue); $fields = Config::inst()->get('FacebookControllerExtension', 'facebook_fields'); $user = (new FacebookRequest($session, 'GET', '/me', array('fields' => implode(',', $fields))))->execute()->getGraphObject(GraphUser::className()); if (!($member = Member::currentUser())) { // member is not currently logged into SilverStripe. Look up // for a member with the UID which matches first. $member = Member::get()->filter(array("FacebookUID" => $user->getId()))->first(); if (!$member) { // see if we have a match based on email. From a // security point of view, users have to confirm their // email address in facebook so doing a match up is fine $email = $user->getProperty('email'); if ($email) { $member = Member::get()->filter(array('Email' => $email))->first(); } } if (!$member) { $member = Injector::inst()->create('Member'); } } $member->syncFacebookDetails($user); $member->logIn(); // redirect the user to the provided url, otherwise take them // back to the route of the website. if ($url = Session::get(FacebookControllerExtension::SESSION_REDIRECT_URL_FLAG)) { return $this->redirect($url); } else { return $this->redirect(Director::absoluteBaseUrl()); } } catch (Exception $e) { SS_Log::log($e, SS_Log::ERR); } } else { return $this->httpError(400); } return $this->httpError(400); }
public function getUserProfile() { try { $user_profile = (new FacebookRequest($this->session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); return $user_profile; } catch (FacebookRequestException $e) { return false; } }
public function validateRequest(RequestInterface $request, ResponseInterface $response) { $identifier = $this->getQuerystringIdentifier(); if (!$request->request($identifier)) { $response->setError(400, 'invalid_request', 'Missing parameters: "' . $identifier . '" required'); return null; } $fb_app_id = Config::get('api-foundation::fb_app_id'); $fb_app_secret = Config::get('api-foundation::fb_app_secret'); if (empty($fb_app_id)) { throw new \LogicException('Facebook APP ID not set.'); } if (empty($fb_app_secret)) { throw new \LogicException('Facebook APP SECRET not set.'); } FacebookSession::setDefaultApplication($fb_app_id, $fb_app_secret); try { $session = new FacebookSession($request->request($identifier)); } catch (FacebookRequestException $e) { $response->setError(401, 'invalid_grant', $e->getMessage()); return null; } catch (\Exception $e) { $response->setError(401, 'invalid_grant', $e->getMessage()); return null; } if (!empty($session)) { try { $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); $email = $user_profile->getProperty('email'); if (empty($email)) { $response->setError(400, 'invalid_request', "User's email address not available."); return null; } else { $userInfo = $this->storage->getUserInfoByFacebookId($user_profile->getId()); if (empty($userInfo)) { $this->storage->createFacebookUser($user_profile); $userInfo = $this->storage->getUserInfoByFacebookId($user_profile->getId()); } } } catch (FacebookRequestException $e) { $response->setError(401, 'invalid_grant', $e->getMessage()); return null; } } else { $response->setError(401, 'invalid_grant', 'Facebook session could not be set with supplied access token.'); return null; } if (empty($userInfo)) { $response->setError(400, 'invalid_grant', 'Unable to retrieve user information.'); return null; } if (!isset($userInfo['user_id'])) { throw new \LogicException("You must set the user_id on the array."); } $this->userInfo = $userInfo; return true; }
public function getUser($userId = 'me') { try { $request = new FacebookRequest($this->getSession(), 'GET', '/' . $userId); return $request->execute()->getGraphObject(GraphUser::className())->asArray(); } catch (Exception $e) { } return []; }
public function testMeReturnsGraphUser() { $response = (new FacebookRequest(FacebookTestHelper::$testSession, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); $info = FacebookTestHelper::$testSession->getSessionInfo(); $this->assertTrue($response instanceof GraphUser); $this->assertEquals($info->getId(), $response->getId()); $this->assertNotNull($response->getName()); $this->assertNotNull($response->getLastName()); $this->assertNotNull($response->getLink()); }
public function getGraph() { $request = new FacebookRequest($this->session, 'GET', '/me'); $response = $request->execute(); return $response->getGraphObject(GraphUser::className()); //echo "<img src='$image'/>"; //echo "<br>"; //echo "Hello $name <br>"; //echo "Email: $email <br>"; //echo "Your Facebook ID: $id <br>"; }
public function get_user_information($access_token) { $session = $this->get_session_from_token($access_token); if (!$session->validate()) { return false; } //*** Call api $request = new FacebookRequest($session, 'GET', '/me'); $response = $request->execute(); return $response->getGraphObject(GraphUser::className()); }
/** * getUserInfo * * @throws FacebookException * @return GraphUser */ public function getGraphUser() { $url = '/me?fields=id,email,first_name,last_name,birthday,permissions'; try { /** @var GraphUser $userProfile */ $userProfile = (new FacebookRequest($this->session, 'GET', $url))->execute()->getGraphObject(GraphUser::className()); return $userProfile; } catch (FacebookRequestException $e) { throw new FacebookException($e->getMessage()); } }
public function get_profile() { $profile = array(); $fb_session = $this->get_session(); try { $profile = (new FacebookRequest($fb_session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); } catch (FacebookRequestException $e) { //echo "Exception occured, code: " . $e->getCode(); //echo " with message: " . $e->getMessage(); } return $profile; }
/** * login with token * * @param String $accessToken, $appId, $appSecret * * @return boolean */ public function loginWithToken($accessToken, $appId, $appSecret) { FacebookSession::setDefaultApplication($appId, $appSecret); $session = new FacebookSession($accessToken); $FacebookRequest = new FacebookRequest($session, 'GET', '/me'); $response = $FacebookRequest->execute(); $this->graph = $response->getGraphObject(GraphUser::classname()); if ($session) { return true; } return false; }
public function testAsList() { $backingData = array('data' => array(array('id' => 1, 'name' => 'David'), array('id' => 2, 'name' => 'Fosco'))); $enc = json_encode($backingData); $response = new FacebookResponse(null, json_decode($enc), $enc); $list = $response->getGraphObjectList(GraphUser::className()); $this->assertEquals(2, count($list)); $this->assertTrue($list[0] instanceof GraphObject); $this->assertTrue($list[1] instanceof GraphObject); $this->assertEquals('David', $list[0]->getName()); $this->assertEquals('Fosco', $list[1]->getName()); }
public function login(\Illuminate\Cookie\CookieJar $cookieJar, \Request $request) { // Replace 1234 with your APP_ID // Replace 123456789 with your APP_SECRET FacebookSession::setDefaultApplication('1234', '123456789'); $helper = new FacebookRedirectLoginHelper(\Request::url()); if ($session = $helper->getSessionFromRedirect()) { $request = new FacebookRequest($session, 'GET', '/me'); $userData = $request->execute()->getGraphObject(GraphUser::className()); $cookieJar->queue(cookie('access_token', $session->getAccessToken(), 45000)); } return redirect($helper->getLoginUrl()); }
/** @return facebook info */ function getFbProfile($fieldName) { if (is_null($this->fbProfile) && $this->getFbUid()) { $session = $this->getFacebookJsSession(); $fbReq = new FacebookRequest($session, 'GET', '/me'); try { $user_profile = $fbReq->execute()->getGraphObject(GraphUser::className()); $this->fbProfile = $user_profile; } catch (Exception $e) { return null; } } return $this->fbProfile->getProperty($fieldName); }
public function loginAction($appId, Request $request) { $ret = array('success' => false); if ($request->request->get('facebook_token') != null && 'POST' === $request->getMethod()) { $em = $this->getDoctrine(); $app = $em->getRepository('KeosuCoreBundle:App')->find($appId); $configPackages = $app->getConfigPackages(); $fbAppId = $configPackages[KeosuGadgetFaceBookBundle::PLUGIN_NAME]['fbAppId']; $fbAppSecret = $configPackages[KeosuGadgetFaceBookBundle::PLUGIN_NAME]['fbAppSecret']; FacebookSession::setDefaultApplication($fbAppId, $fbAppSecret); $session = new FacebookSession($request->request->get('facebook_token')); try { $session->validate(); $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); // user Email $email = $user_profile->getProperty('email'); $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->findUserByUsernameOrEmail($email); // the user doesn't have account if ($user == null) { $user = $userManager->createUser(); $user->setUsername($email); $user->setEnabled(true); $user->setPlainPassword(\md5($email . \rand())); $user->setEmail($email); $user->setAccountType('facebook'); $userManager->updateUser($user); } if ($user->getAccountType() == 'facebook') { // We log the user $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $this->get('security.context')->setToken($token); $this->get('session')->set('_security_main', serialize($token)); $ret['success'] = true; } else { $ret['message'] = "This email is allready used with an other account"; } } catch (FacebookRequestException $ex) { echo $ex->getMessage(); } catch (\Exception $ex) { echo $ex->getMessage(); } } else { $ret['message'] = 'unable to login with facebook'; } return new JsonResponse($ret); }
private function checkIfNewSession() { try { $session = $this->helper->getSessionFromRedirect(); } catch (FacebookRequestException $ex) { echo $ex; } catch (Exception $ex) { // When validation fails or other local issues echo $ex; } if (isset($session)) { $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); $token = $session->getToken(); update_option($this->globalMessageOptionsKey, ""); update_option($this->tokenOptionsKey, $token); update_option($this->fbIdOptionsKey, $user_profile->getId()); } }
public function getLoginFacebookCallback() { FacebookSession::setDefaultApplication(Config::get('facebook.app_id'), Config::get('facebook.secret')); $helper = new FacebookRedirectLoginHelper(url('/users/login-facebook-callback')); try { $session = $helper->getSessionFromRedirect(); } catch (FacebookRequestException $ex) { // When Facebook returns an error } catch (Exception $ex) { // When validation fails or other local issues } $request = new FacebookRequest($session, 'GET', '/me'); $response = $request->execute(); $graphUser = $response->getGraphObject(GraphUser::className()); $facebookUserId = $graphUser->getId(); $facebookFirstName = $graphUser->getFirstName(); $facebookLastName = $graphUser->getLastName(); $facebookName = $graphUser->getName(); $facebookEmailAddress = $graphUser->getProperty('email'); // sometimes the response does not contain the email address, although the user gave email permission if (empty($facebookEmailAddress)) { $facebookEmailAddress = $facebookFirstName . '.' . $facebookLastName . '@facebook.com'; } $socialProfile = SocialProfile::where('uid', '=', $facebookUserId)->first(); if (empty($socialProfile)) { $user = new User(); $user->first_name = $facebookFirstName; $user->last_name = $facebookLastName; $user->email = $facebookEmailAddress; $user->username = $facebookName; $user->avatar = 'https://graph.facebook.com/' . $facebookUserId . '/picture?type=large'; $user->reg_method = 'facebook'; $user->active = true; $user->save(); $socialProfile = new SocialProfile(); $socialProfile->uid = $facebookUserId; $socialProfile = $user->socialProfiles()->save($socialProfile); } $socialProfile->access_token = $session->getToken(); $socialProfile->save(); $user = $socialProfile->user; Auth::login($user); return Redirect::action('ProductController@getIndex')->with('message_info', 'Mit Facebook eingeloggt'); }
private function AddNewUser() { $session = Session::get('fb_session'); $user = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); $user_pic = (new FacebookRequest($session, 'GET', '/me/picture', array('redirect' => false, 'height' => '480', 'width' => '480')))->execute()->getGraphObject(GraphUser::className()); $uid = $this->db->real_escape_string($user->getProperty("id")); $first_name = $this->db->real_escape_string($user->getProperty("first_name")); $last_name = $this->db->real_escape_string($user->getProperty("last_name")); $email = $this->db->real_escape_string($user->getProperty("email")); $name = $this->db->real_escape_string($user->getProperty("name")); $gender = $this->db->real_escape_string($user->getProperty("gender")); $dob = $this->db->real_escape_string(changeDateFormatToDB($user->getProperty("birthday"))); $dos = date("Y-m-d"); $profile_pic_link = $this->db->real_escape_string($user_pic->getProperty("url")); $query = "INSERT INTO " . DB_TABLE . " (uid,email,first_name,last_name,name,gender,dob,dos,profile_pic_link) \n VALUES ('" . $uid . "','" . $email . "','" . $first_name . "','" . $last_name . "','" . $name . "','" . $gender . "','" . $dob . "','" . $dos . "','" . $profile_pic_link . "')"; $result = $this->db->query($query); if ($this->db->affected_rows) { $this->Attempt(); } }
public function signin() { FacebookSession::setDefaultApplication(Ntentan::$config['social.facebook.app_id'], Ntentan::$config['social.facebook.secret']); $helper = new \Facebook\FacebookRedirectLoginHelper('http://paanoo.com/users/signin/facebook'); try { $session = $helper->getSessionFromRedirect(); if ($session === null) { header('Location: ' . $helper->getLoginUrl(array('email'))); } } catch (FacebookRequestException $ex) { } catch (\Exception $ex) { } if ($session) { try { $userRequest = new FacebookRequest($session, 'GET', '/me'); $user = $userRequest->execute()->getGraphObject(GraphUser::className())->asArray(); return array('firstname' => $user['first_name'], 'lastname' => $user['last_name'], 'key' => "facebook_{$user['id']}", 'avatar' => "http://graph.facebook.com/{$user['id']}/picture?type=large", 'email' => $user['email'], 'email_confirmed' => $user['verified'], 'avatar_format' => 'jpg'); } catch (Exception $ex) { } } }
/** * Create a new user or log them in if they exist * * @param \Facebook\GraphUser $fb * @return bool * @throws \Exception */ public function create(\Facebook\GraphUser $fb) { $email = $fb->getId() . '@fb'; $user = $this->db->select('*')->from(':user')->where(['email' => $email])->get(); if (isset($user['user_id'])) { $_password = $fb->getId() . uniqid(); $password = (new \Core\Hash())->make($_password); $this->db->update(':user', ['password' => $password], ['user_id' => $user['user_id']]); } else { $_password = $fb->getId() . uniqid(); $password = (new \Core\Hash())->make($_password); $id = $this->db->insert(':user', ['user_group_id' => NORMAL_USER_ID, 'email' => $email, 'password' => $password, 'full_name' => $fb->getFirstName() . ' ' . $fb->getLastName(), 'user_name' => 'fb-' . $fb->getId(), 'user_image' => '{"fb":"' . $fb->getId() . '"}', 'joined' => PHPFOX_TIME, 'last_activity' => PHPFOX_TIME]); $tables = ['user_activity', 'user_field', 'user_space', 'user_count']; foreach ($tables as $table) { $this->db->insert(':' . $table, ['user_id' => $id]); } } \User_Service_Auth::instance()->login($email, $_password, true, 'email'); if (!\Phpfox_Error::isPassed()) { throw new \Exception(implode('', \Phpfox_Error::get())); } return true; }
/** * @return \Illuminate\Http\JsonResponse * @throws \FacebookFacebookAuthorizationException * @throws \Facebook\FacebookRequestException */ public function facebookAuth($code) { $accessToken = $this->getAccessToken($code); $session = new FacebookSession($accessToken); if (!$session) { throw new FacebookAuthorizationException('Invalid code'); } /** * @var GraphUser $userProfile */ $userProfile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); $user = Member::firstOrNew(['facebookId' => $userProfile->getId()]); $user->name = $userProfile->getName(); $user->save(); Auth::login($user); $memberToken = new MemberToken(); $memberToken->memberId = $user->id; $memberToken->accessToken = $accessToken; $memberToken->sessionId = Session::getId(); $memberToken->save(); return $accessToken; }
public static function loginCallback() { FacebookSession::setDefaultApplication(FB_APP_ID, FB_APP_SECRET); $helper = new FacebookRedirectLoginHelper(FB_REDIRECT_URI); $fb_session = $helper->getSessionFromRedirect(); //4. if fb sess exists echo name if (isset($fb_session)) { //create request object,execute and capture response $request = new FacebookRequest($fb_session, 'GET', '/me?fields=id,first_name,last_name,email,gender,locale,picture,birthday'); // from response get graph object $response = $request->execute(); $graph = $response->getGraphObject(GraphUser::className()); //print_r($graph); $fbRecords = array(); $fbRecords["access_token"] = $fb_session->getAccessToken(); $fbRecords["first_name"] = $graph->getFirstName(); $fbRecords["last_name"] = $graph->getLastName(); $fbRecords["email"] = $graph->getEmail(); $fbRecords["fb_id"] = $graph->getId(); $fbRecords["gender"] = $graph->getGender(); // Returns a long-lived access token try { $longSession = $fb_session->getLongLivedSession(); } catch (Facebook\Exceptions\FacebookSDKException $e) { //echo $e->getMessage(); //exit; } if (isset($longSession)) { $fbRecords["long_lived_access_token"] = $longSession->getToken(); } //return the array of records return $fbRecords; } else { return null; } }
public function authenticate() { $logger = Zend_Registry::get('logger'); // Set credentials FacebookSession::setDefaultApplication(Zend_Registry::get('facebookId'), Zend_Registry::get('facebookSecret')); // Set callback URL $helper = new FacebookRedirectLoginHelper(Zend_Registry::get('domain') . '/Auth/index/login/'); try { $session = $helper->getSessionFromRedirect(); $logger->info("getSessionFromRedirect with no exception"); } catch (FacebookRequestException $e) { $logger->info('FacebookRequestException ' . $e->getMessage()); } catch (Exception $e) { $logger->info("Could not get Facebook session." . $e->getMessage() . '#' . $e->getTraceAsString()); } $logger->info("Facebook::authenticate session: " . var_export($session, true)); if (isset($session)) { // User is logged in on facebook and have given the permission. $logger->debug('Facebook session acquired'); try { $me = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); $this->setIdentity($me->getEmail()); $this->setName($me->getName()); // Authentication successful return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this->_identity); } catch (Exception $e) { // Some other error occurred $logger->err('Error authenticating user on facebook ' . $e->getMessage() . ' # ' . $e->getTraceAsString()); return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, $this->_identity); } } else { $url = $helper->getLoginUrl(); $logger->debug("redirecting user to Facebook, for authentication: {$url}"); header("Location: {$url}"); } }
/** * Retourne un utilisateur de la base en fonction de l'utilisateur facebook * Si il n'existe pas, on en créée un * @param GraphUser $user [description] * @return [type] [description] */ public function getUserFromFacebook(GraphUser $user) { $email = $user->getEmail(); if (is_null($email)) { throw new \Exception('Facebook user does not share email', 400); } // Get user from email $fos_user = $this->user_manager->findUserByEmail($email); // Create user if necessary if (is_null($fos_user)) { $fos_user = $this->user_manager->createUser(); } $fos_user->setEnabled(true); $fos_user->setEmail($email); $fos_user->setFirstName($user->getFirstName()); $fos_user->setLastName($user->getLastName()); $fos_user->setRoles([$this->user_role]); $fos_user->setFacebookId($user->getId()); $fos_user->setLocale(substr($user->getProperty('locale'), 0, 2)); $fos_user->setTimezone($user->getTimezone()); $this->user_manager->updateCanonicalFields($fos_user); $this->user_manager->updateUser($fos_user); return $fos_user; }