예제 #1
0
 public static function getLoginURL()
 {
     FacebookSession::setDefaultApplication(FB_APP_ID, FB_APP_SECRET);
     $helper = new FacebookRedirectLoginHelper(FB_REDIRECT_URI);
     //$fb_session = $helper->getSessionFromRedirect();
     return $helper->getLoginUrl(array('scope' => 'email'));
 }
예제 #2
0
 public function action_index()
 {
     try {
         $helper = new FacebookRedirectLoginHelper(Config::get('login_url'));
         $session = $helper->getSessionFromRedirect();
     } catch (FacebookRequestException $ex) {
         // When Facebook returns an error
     } catch (\Exception $ex) {
         // When validation fails or other local issues
     }
     if (isset($session)) {
         //login succes
         $long_lived_session = $session->getLongLivedSession();
         $access_token = $long_lived_session->getToken();
         //*** Call api to get user info
         $user_info = $this->facebook->get_user_information($access_token);
         //*** Check if user has existed
         $user = Model_Users::find('first', array('where' => array('fb_id' => $user_info->getId())));
         if (empty($user)) {
             // Register user
             if (Model_Users::register_user($user_info, $access_token)) {
                 //Success
             }
         }
         //*** Set session for user
         Fuel\Core\Session::set('user_token', $long_lived_session->getToken());
         Fuel\Core\Session::set('user_id', $user_info->getId());
         //*** Redirect to home
         \Fuel\Core\Response::redirect('fanpage/index');
     } else {
         // login fail
         $this->template->login_url = $helper->getLoginUrl();
     }
 }
예제 #3
0
 public function obtainToken($callback)
 {
     $helper = new FacebookRedirectLoginHelper($callback);
     if ($this->input->get('code') === null) {
         /**
          * Required permissions
          * public_profile
          * email
          * read_insights		Show analytics data of page in dashboard
          * read_page_mailboxes	Manage page conversations
          * read_mailbox			Manage page mailbox
          * manage_pages			Manage brand pages
          * publish_pages		Take actions on behalf of page
          */
         $loginUrl = $helper->getLoginUrl(array('public_profile', 'user_friends', 'email', 'read_mailbox', 'read_page_mailboxes', 'manage_pages', 'publish_actions', 'publish_pages', 'read_insights'));
         Url::redirect($loginUrl);
         return null;
     } else {
         $session = null;
         try {
             $session = $helper->getSessionFromRedirect();
         } catch (FacebookRequestException $ex) {
             // When Facebook returns an error
         } catch (\Exception $ex) {
             // When validation fails or other local issues
         }
         if ($session) {
             // Logged in
         }
         return $session;
     }
 }
예제 #4
0
 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);
 }
 /**
  * @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');
 }
예제 #6
0
 public function index()
 {
     FacebookSession::setDefaultApplication(Config::get('facebook.appid'), Config::get('facebook.secret'));
     $helper = new FacebookRedirectLoginHelper('http://localhost:8000/home');
     // $helper = new FacebookRedirectLoginHelper('http://hexanlyzer.azurewebsites.net/home');
     return redirect($helper->getLoginUrl());
 }
예제 #7
0
 /**
  * login with facebook sdk
  *
  * @param String $appId, $appSecret, $redirectUrl
  *
  * @return boolean
  */
 public function login($appId, $appSecret, $redirectUrl)
 {
     $redirectUrl = 'http://' . $_SERVER['HTTP_HOST'] . $redirectUrl;
     $request = new Request();
     FacebookSession::setDefaultApplication($appId, $appSecret);
     $helper = new FacebookRedirectLoginHelper($redirectUrl);
     try {
         $session = $helper->getSessionFromRedirect();
     } catch (FacebookRequestException $ex) {
         // When Facebook returns an error
     } catch (\Exception $ex) {
         // When validation fails or other local issues
     }
     $this->loginurl = $helper->getLoginUrl();
     if ($session) {
         $FacebookRequest = new FacebookRequest($session, 'GET', '/me');
         $response = $FacebookRequest->execute();
         $graph = $response->getGraphObject(GraphUser::classname());
         $name = $graph->getName();
         $accessToken = $session->getAccessToken();
         $request->setSession('facebook', (string) $accessToken);
         return true;
     } else {
         return false;
     }
 }
예제 #8
0
 /**
  * @param $redirect_url
  * @return string|Facebook\GraphUser Login URL or GraphUser
  */
 function connect($redirect_url)
 {
     FacebookSession::setDefaultApplication($this->appId, $this->appSecret);
     $helper = new FacebookRedirectLoginHelper($redirect_url);
     if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
         $session = new FacebookSession($_SESSION['fb_token']);
     } else {
         $session = $helper->getSessionFromRedirect();
     }
     if ($session) {
         try {
             $_SESSION['fb_token'] = $session->getToken();
             $request = new FacebookRequest($session, 'GET', '/me');
             $profile = $request->execute()->getGraphObject('Facebook\\GraphUser');
             if ($profile->getEmail() === null) {
                 throw new \Exception('L\'email n\'est pas disponible');
             }
             return $profile;
         } catch (\Exception $e) {
             unset($_SESSION['fb_token']);
             return $helper->getReRequestUrl(['email']);
         }
     } else {
         return $helper->getLoginUrl(['email']);
     }
 }
 /**
  * Redirect to generated url 
  */
 public function redirectToGeneratedUrl()
 {
     //permissions
     $scopes = array("read_friendlists", "manage_friendlists", "publish_actions", "user_groups", "user_friends", "user_about_me", "user_location", "user_birthday", "email");
     $loginUrl = $this->loginHelper->getLoginUrl($scopes);
     redirect($loginUrl);
 }
예제 #10
0
 function facebook()
 {
     $permissions = ['email', 'public_profile'];
     // Add `use Facebook\FacebookRedirectLoginHelper;` to top of file
     $helper = new FacebookRedirectLoginHelper(site_url("social/fb_oauth"));
     $loginUrl = $helper->getLoginUrl($permissions);
     redirect($loginUrl);
 }
예제 #11
0
 /**
  *
  * @param string $value
  * @return string
  */
 public function __invoke($value = 'your/redirect/URL/here')
 {
     $config = $this->getServiceLocator()->getServiceLocator()->get('Config');
     FacebookSession::setDefaultApplication($config['facebook']['appId'], $config['facebook']['secret']);
     //TODO should this be in a global space
     $server = isset($_SERVER['HTTP_HOST']) ? "http://" . $_SERVER['HTTP_HOST'] : 'http://0.0.0.0';
     $helper = new FacebookRedirectLoginHelper($server . $value);
     return $helper->getLoginUrl();
 }
예제 #12
0
 public function getFacebook()
 {
     session_start();
     if ($this->auth->check()) {
         abort(404, 'You have alreay logined');
     }
     //        return Socialize::with('facebook')->redirect();//laravel第三方认证
     $this->loadConfig('facebook');
     $helper = new FacebookRedirectLoginHelper($this->callback, $this->appId, $this->appSecret);
     $loginUrl = $helper->getLoginUrl([], NULL, true);
     return redirect($loginUrl);
 }
예제 #13
0
 /**
  * Start an authentication request
  *
  * @param String $providedToken External token
  * @return bool True if user is already logged in, otherwise redirect to the login URL
  */
 public function authenticate($providedToken = null)
 {
     if ($providedToken !== NULL) {
         $this->tryValidateSession($providedToken);
     }
     if ($this->facebookSession == null) {
         $url = $this->loginHelper->getLoginUrl(url(Config::get('Phacebook::redirectUrl')), Config::get('Phacebook::scopes'));
         return $url;
     } else {
         return TRUE;
     }
 }
 public function testLoginURL()
 {
     $helper = new FacebookRedirectLoginHelper(self::REDIRECT_URL, FacebookTestCredentials::$appId, FacebookTestCredentials::$appSecret);
     $loginUrl = $helper->getLoginUrl();
     $state = $_SESSION['FBRLH_state'];
     $params = array('client_id' => FacebookTestCredentials::$appId, 'redirect_uri' => self::REDIRECT_URL, 'state' => $state, 'sdk' => 'php-sdk-' . FacebookRequest::VERSION, 'scope' => implode(',', array()));
     $expectedUrl = 'https://www.facebook.com/v2.0/dialog/oauth?';
     $this->assertTrue(strpos($loginUrl, $expectedUrl) !== false);
     foreach ($params as $key => $value) {
         $this->assertTrue(strpos($loginUrl, $key . '=' . urlencode($value)) !== false);
     }
 }
예제 #15
0
파일: Facebook.php 프로젝트: evias/sociall
 /**
  * The getLoginURL() method can be used to generate
  * the Facebook API login URL for your Facebook App.
  * This URL must be called to get permissions from the Facebook
  * account trying to login into your App.
  * This is the first URL that must be called for your App to be able
  * to retrieve Access tokens for logged in users.
  *
  * @return string
  */
 public function getLoginURL()
 {
     $callback_url = $this->getLoginCallbackURL();
     if (empty($callback_url)) {
         throw new Facebook_APICallError("sociall\\Facebook::getLoginURL() requires a login callback " . "URL to be set first.");
     }
     $app_id = $this->getAppId();
     $app_secret = $this->getAppSecret();
     FacebookSession::setDefaultApplication($app_id, $app_secret);
     $helper = new FacebookRedirectLoginHelper($callback_url);
     $login_url = $helper->getLoginUrl(['public_profile', 'email']);
     return $login_url;
 }
 public function testLoginURL()
 {
     $helper = new FacebookRedirectLoginHelper(self::REDIRECT_URL, FacebookTestCredentials::$appId, FacebookTestCredentials::$appSecret);
     $helper->disableSessionStatusCheck();
     $loginUrl = $helper->getLoginUrl();
     $state = $_SESSION['FBRLH_state'];
     $params = array('client_id' => FacebookTestCredentials::$appId, 'redirect_uri' => self::REDIRECT_URL, 'state' => $state, 'sdk' => 'php-sdk-' . FacebookRequest::VERSION, 'scope' => implode(',', array()));
     $expectedUrl = 'https://www.facebook.com/' . FacebookRequest::GRAPH_API_VERSION . '/dialog/oauth?';
     $this->assertTrue(strpos($loginUrl, $expectedUrl) === 0, 'Unexpected base login URL returned from getLoginUrl().');
     foreach ($params as $key => $value) {
         $this->assertContains($key . '=' . urlencode($value), $loginUrl);
     }
 }
 public function __construct($currentUrl, $homeUrl)
 {
     $this->session = null;
     $this->loginUrl = '';
     $this->logoutUrl = '';
     $cleanUrl = false;
     try {
         if (session_id() == '') {
             session_start();
         }
         $loginHelper = new FacebookRedirectLoginHelper($currentUrl);
         // try to login from session token
         if (!empty($_SESSION['facebook_session_token'])) {
             $this->session = new FacebookSession($_SESSION['facebook_session_token']);
             if ($this->session) {
                 $this->session->validate();
             }
         }
         // try to login from redirect
         if (!$this->session) {
             $this->session = $loginHelper->getSessionFromRedirect();
             $cleanUrl = true;
         }
         // store access token
         if ($this->session) {
             $_SESSION['facebook_session_token'] = $this->session->getToken();
             if ($cleanUrl) {
                 header("HTTP/1.0 301 Moved Permanently");
                 header("Location: " . $currentUrl . '#top');
                 exit;
             }
             $this->logoutUrl = $loginHelper->getLogoutUrl($this->session, $homeUrl);
         } else {
             $this->loginUrl = $loginHelper->getLoginUrl();
         }
     } catch (\Exception $ex) {
         $this->session = null;
         $this->loginUrl = '';
         $this->logoutUrl = '';
     }
 }
 public function masuk()
 {
     FacebookSession::setDefaultApplication(Config::get('facebook.appId'), Config::get('facebook.secret'));
     $helper = new FacebookRedirectLoginHelper(url('/fblogin'));
     $scope = array('email');
     $session = $helper->getSessionFromRedirect();
     if (isset($session)) {
         //return Redirect::to('/bergabung');
         $request = new FacebookRequest($session, 'GET', '/me');
         $response = $request->execute();
         // get response
         $graphObject = $response->getGraphObject();
         $fbid = $graphObject->getProperty('id');
         // To Get Facebook ID
         $fbfullname = $graphObject->getProperty('name');
         // To Get Facebook full name
         $femail = $graphObject->getProperty('email');
         Session::put('logged_in', '1');
         Session::put('level', 'user');
         Session::put('user_name', $fbfullname);
         Session::put('fbid', $fbid);
         //$fbcheck = $this->checkuser($fbid,$fbfullname,$femail);
         $fbcheck = $this->check($fbid);
         if ($fbcheck == TRUE) {
             $data = array('fbname' => $fbfullname, 'fbemail' => $femail);
             Users::where('fbid', '=', $fbid)->update($data);
             $userid = Users::where('fbid', '=', $fbid)->first()->id;
             Session::put('user_id', $userid);
             return Redirect::to('/beranda');
         } else {
             Users::create($data);
             $userid = Users::where('fbid', '=', $fbid)->first()->id;
             Session::put('user_id', $userid);
             return View::make('selamat_bergabung');
         }
     } else {
         $loginUrl = $helper->getLoginUrl($scope);
         return Redirect::to($loginUrl);
     }
 }
예제 #19
0
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     global $base_url;
     $build = [];
     c4a_connect_facebook_client_load();
     $config = \Drupal::config('c4a_connect.fbconnectadmin_config');
     $init_params = array('appId' => $config->get('application_id'), 'secret' => $config->get('application_secret'));
     FacebookSession::setDefaultApplication($init_params['appId'], $init_params['secret']);
     $helper = new FacebookRedirectLoginHelper($base_url . '/user/facebook-connect');
     try {
         if (isset($_SESSION['token'])) {
             // Check if an access token has already been set.
             $session = new FacebookSession($_SESSION['token']);
         } else {
             // Get access token from the code parameter in the URL.
             $session = $helper->getSessionFromRedirect();
         }
     } catch (FacebookRequestException $ex) {
         // When Facebook returns an error.
         print_r($ex);
     } catch (\Exception $ex) {
         // When validation fails or other local issues.
         print_r($ex);
     }
     if (isset($session)) {
         // Retrieve & store the access token in a session.
         $_SESSION['token'] = $session->getToken();
         //          $logoutURL = $helper->getLogoutUrl( $session, 'http://your-app-domain.com/user/logout' );
         // Logged in
         drupal_set_message('Successfully logged in!');
     } else {
         $permissions = array('email', 'user_birthday');
         // Generate the login URL for Facebook authentication.
         $loginUrl = $helper->getLoginUrl($permissions);
         $build['facebook_login']['#markup'] = '<a href="' . $loginUrl . '">Login with facebook</a>';
     }
     return $build;
 }
예제 #20
0
 /**
  * @return string|Facebook\GraphUser Login URL or GraphUser
  */
 public function connect()
 {
     $helper = new FacebookRedirectLoginHelper($this->redirectUrl);
     if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
         $this->setSession(new FacebookSession($_SESSION['fb_token']));
     } else {
         $this->setSession($helper->getSessionFromRedirect());
     }
     if ($this->getSession()) {
         try {
             $_SESSION['fb_token'] = $this->getSession()->getToken();
             $profile = $this->getUser();
             if ($profile->getEmail() === null) {
                 throw new \Exception("L'email n'est pas disponible");
             }
             return $profile;
         } catch (\Exception $e) {
             unset($_SESSION['fb_token']);
             return $helper->getReRequestUrl($this->scope);
         }
     } else {
         return $helper->getLoginUrl($this->scope);
     }
 }
예제 #21
0
파일: Facebook.php 프로젝트: dmelo/dzend
 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}");
     }
 }
예제 #22
0
								<?php 
                                        $num3++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (FacebookRequestException $e) {
        echo "Exception occured, code: " . $e->getCode();
        echo " with message: " . $e->getMessage();
    }
} else {
    echo '<a href="' . $helper->getLoginUrl(array('scope' => 'email,user_photos')) . '"><font size="6"><i><strong>
	Get Details</strong></i></font></a>';
}
?>
<script type="text/javascript" charset="utf-8">
	
	$('.fancybox').fancybox({
					padding:0,
					autoPlay: true
					
				});
		
</script>

	</body>
</html>
예제 #23
0
 public function getAuthURL($redirect_url)
 {
     $helper = new FacebookRedirectLoginHelper($redirect_url);
     $loginUrl = $helper->getLoginUrl($this->config['scope']);
     return Redirect::to((string) $loginUrl);
 }
예제 #24
0
<?php 
} else {
    // echo "session not cretaed _ ";
    $perm = array("scope" => "email,user_photos");
    ?>
			<nav class="navbar navbar-inverse" role="navigation">
				<div class="container-fluid">
					<div class="navbar-header">
						<a class="navbar-brand" href="#">Facebook Album Challenge</a>
					</div>
				</div>
			</nav>

			<div id="login-div" class="row">
				<a id="login-link" class="btn btn-primary btn-lg" href="<?php 
    echo $helper->getLoginUrl($perm);
    ?>
">
					Facebook
				</a>
			</div>

<?php 
}
?>

		<script type="text/javascript" charset="utf-8">
			$( document ).ready(function() {
				var opts = {
				  lines: 20, // The number of lines to draw
				  length: 50, // The length of each line
예제 #25
0
 /**
  * Get URL for login
  * @param string $callbackURL
  * @return string URL login
  */
 public function getLoginUrl()
 {
     $loginUrl = $this->helper->getLoginUrl($this->callBackUrl, $this->scope);
     return $loginUrl;
 }
예제 #26
0
$helper = new FacebookRedirectLoginHelper('http://localhost/hackathon_challenge_3/fbconfig.php');
try {
    $session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
    // When Facebook returns an error
} catch (Exception $ex) {
    // When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
    // graph api request for user data
    $request = new FacebookRequest($session, 'GET', '/me');
    $response = $request->execute();
    // get response
    $graphObject = $response->getGraphObject();
    $fbid = $graphObject->getProperty('id');
    // To Get Facebook ID
    $fbfullname = $graphObject->getProperty('name');
    // To Get Facebook full name
    $femail = $graphObject->getProperty('email');
    // To Get Facebook email ID
    /* ---- Session Variables -----*/
    $_SESSION['FBID'] = $fbid;
    $_SESSION['FULLNAME'] = $fbfullname;
    $_SESSION['EMAIL'] = $femail;
    /* ---- header location after session ----*/
    header("Location: index.php");
} else {
    $loginUrl = $helper->getLoginUrl();
    header("Location: " . $loginUrl);
}
예제 #27
0
/**
 * Get facebook login url for the platform
 * @return string
 */
function facebookGetLoginUrl()
{
    global $facebook_config;
    $helper = new FacebookRedirectLoginHelper($facebook_config['return_url']);
    $loginUrl = $helper->getLoginUrl(array('scope' => 'email'));
    return $loginUrl;
}
예제 #28
0
 /**
  *  facebookAction
  */
 public function facebookAction()
 {
     $config = $this->getServiceLocator()->get('config')['facebook'];
     $config['callbackUrl'] = $this->url()->fromRoute('user/default', ['controller' => 'auth', 'action' => 'facebook-callback'], ['force_canonical' => true]);
     FacebookSession::setDefaultApplication($config['appId'], $config['appSecret']);
     $helper = new FacebookRedirectLoginHelper($config['callbackUrl']);
     $this->redirect()->toUrl($helper->getLoginUrl(['scope' => 'email']));
 }
예제 #29
0
 public function facebookAction()
 {
     $request = $this->getRequest();
     if (trim($request->getQuery('redirect'))) {
         $_SESSION['redirect'] = trim($request->getQuery('redirect'));
     }
     $viewModel = new ViewModel();
     $viewModel->setTerminal(true);
     $response = $this->getResponse();
     require_once 'Facebook/FacebookSession.php';
     require_once 'Facebook/Entities/AccessToken.php';
     require_once 'Facebook/FacebookSDKException.php';
     require_once 'Facebook/FacebookRequestException.php';
     require_once 'Facebook/FacebookAuthorizationException.php';
     require_once 'Facebook/FacebookResponse.php';
     require_once 'Facebook/HttpClients/FacebookCurl.php';
     require_once 'Facebook/HttpClients/FacebookHttpable.php';
     require_once 'Facebook/HttpClients/FacebookCurlHttpClient.php';
     require_once 'Facebook/FacebookSDKException.php';
     require_once 'Facebook/FacebookRequestException.php';
     require_once 'Facebook/FacebookRedirectLoginHelper.php';
     require_once 'Facebook/FacebookRequest.php';
     require_once 'Facebook/GraphObject.php';
     require_once 'Facebook/GraphUser.php';
     $config = $this->getServiceLocator()->get('Config');
     $appId = $config['login']['facebook']['appId'];
     $appSecret = $config['login']['facebook']['appSecret'];
     FacebookSession::setDefaultApplication($appId, $appSecret);
     $url = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
     $url .= $_SERVER['HTTP_HOST'] . '/user/signin/facebook';
     $facebook = new \Facebook\FacebookRedirectLoginHelper($url);
     try {
         $session = $facebook->getSessionFromRedirect();
     } catch (\Facebook\FacebookRequestException $ex) {
         // When Facebook returns an error
         echo $ex->getMessage();
     } catch (\Exception $ex) {
         // When validation fails or other local issues
         echo $ex->getMessage();
     }
     if (isset($session)) {
         $user_profile = (new \Facebook\FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(\Facebook\GraphUser::className());
         $arrResponse = $user_profile->asArray();
         $email = $user_profile->getProperty('email');
         if (!$email) {
             echo '<script>window.opener.alert("Không tồn tại thông tin Email của tài khoản trên");window.close()</script>';
         }
         $user = new User();
         $userMapper = $this->getServiceLocator()->get('User\\Model\\UserMapper');
         $serviceUser = $this->getServiceLocator()->get('User\\Service\\User');
         if (!$serviceUser->authenticateFacebook($email)) {
             $user->setActive('1');
             $user->setEmail($email);
             $user->setRole(\User\Model\User::ROLE_MEMBER);
             $user->setFullName($arrResponse['name']);
             $user->setCreatedDate(DateBase::getCurrentDate());
             $user->setCreatedDateTime(DateBase::getCurrentDateTime());
             $userMapper->save($user);
             // check nếu user đó đã dc mời tham gia dự án sẽ gắn luôn nó với dự án
             $projectUser = new \Work\Model\ProjectUser();
             $projectUser->setUserEmail($user->getEmail());
             $projectUser->setUserId($user->getId());
             $projectUserMapper = $this->getServiceLocator()->get('\\Work\\Model\\ProjectUserMapper');
             $projectUserMapper->updateUserId($projectUser);
             $this->redirect()->toUrl($url);
         } else {
             // check nếu user đó đã dc mời tham gia dự án sẽ gắn luôn nó với dự án
             $projectUser = new \Work\Model\ProjectUser();
             $projectUser->setUserEmail($serviceUser->getUser()->getEmail());
             $projectUser->setUserId($serviceUser->getUser()->getId());
             $projectUserMapper = $this->getServiceLocator()->get('\\Work\\Model\\ProjectUserMapper');
             $projectUserMapper->updateUserId($projectUser);
             if (!$_SESSION['redirect']) {
                 return $this->redirect()->toUrl('/');
             } else {
                 $redirect = $_SESSION['redirect'];
                 unset($_SESSION['redirect']);
                 return $this->redirect()->toUrl($redirect);
             }
         }
     } else {
         $this->redirect()->toUrl($facebook->getLoginUrl(['email', 'user_birthday', 'user_about_me']));
     }
     return $response;
 }
예제 #30
0
try {
    $session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
    // When Facebook returns an error
} catch (Exception $ex) {
    // When validation fails or other local issues
}
// see if we have a session
if (isset($session)) {
    // graph api request for user data
    $request = new FacebookRequest($session, 'GET', '/me?locale=en_US&fields=name,email');
    $response = $request->execute();
    // get response
    $graphObject = $response->getGraphObject();
    $fbid = $graphObject->getProperty('id');
    // To Get Facebook ID
    $fbfullname = $graphObject->getProperty('name');
    // To Get Facebook full name
    $femail = $graphObject->getProperty('email');
    // To Get Facebook email ID
    /* ---- Session Variables -----*/
    $_SESSION['FBID'] = $fbid;
    $_SESSION['FULLNAME'] = $fbfullname;
    $_SESSION['EMAIL'] = $femail;
    $femail = encode($femail, 'Housingmatters_facebook');
    /* ---- header location after session ----*/
    header("Location: http://app.housingmatters.co.in?aqazp2yd=" . $femail . "&source=f&uid=" . $fbid);
} else {
    $loginUrl = $helper->getLoginUrl(array('scope' => 'email'));
    header("Location: " . $loginUrl);
}