示例#1
0
 private function getUserInfo()
 {
     FacebookSession::setDefaultApplication(Config::get('facebook.appid'), Config::get('facebook.secret'));
     $helper = new FacebookRedirectLoginHelper('http://localhost:8000/home');
     $userID = "";
     $userEmail = "";
     $userName = "";
     $userPicUrl = "";
     try {
         $session = $helper->getSessionFromRedirect();
     } catch (FacebookRequestException $ex) {
         // When Facebook returns an error
     } catch (\Exception $ex) {
         // When validation fails or other local issues
     }
     if (isset($_SESSION['token'])) {
         // We have a token, is it valid?
         $session = new FacebookSession($_SESSION['token']);
         try {
             $session->Validate(Config::get('facebook.appid'), Config::get('facebook.secret'));
         } catch (FacebookAuthorizationException $ex) {
             // Session is not valid any more, get a new one.
             $session = '';
         }
     }
     if (isset($session)) {
         $_SESSION['token'] = $session->getToken();
         $request = new FacebookRequest($session, 'GET', '/me?fields=id,name,email,picture');
         $response = $request->execute();
         $graphObject = $response->getGraphObject();
         $userID = $graphObject->getProperty('id');
         $userName = $graphObject->getProperty('name');
         $userEmail = $graphObject->getProperty('email');
         $userPicObj = $graphObject->getProperty('picture')->asArray();
         $userPicUrl = $userPicObj['url'];
         $_SESSION['usrID'] = $userID;
         $_SESSION['usrName'] = $userName;
         $_SESSION['usrEmail'] = $userEmail;
         $_SESSION['usrPicUrl'] = $userPicUrl;
         $user_model = App\user::where('user_id', $userID)->first();
         if (is_null($user_model)) {
             $user_model = new App\user();
             $user_model->user_id = $userID;
             $user_model->user_name = $userName;
             $user_model->user_email = $userEmail;
             $user_model->user_profilePic = $userPicUrl;
             $user_model->save();
         } else {
             $user_model->user_name = $userName;
             $user_model->user_email = $userEmail;
             $user_model->user_profilePic = $userPicUrl;
             $user_model->save();
         }
     }
     $data = array("user_id" => $userID, "user_name" => $userName, "user_email" => $userEmail, "user_profilePic" => $userPicUrl);
     $data = array("user_id" => $userID, "user_name" => $userName, "user_email" => $userEmail, "user_profilePic" => $userPicUrl);
     return $data;
 }
示例#2
0
 public function facebook()
 {
     $facebook_default_scope = explode(',', $this->ci->config->item("facebook_default_scope"));
     $facebook_app_id = $this->ci->config->item("facebook_app_id");
     $facebook_api_secret = $this->ci->config->item("facebook_api_secret");
     // init app with app id and secret
     FacebookSession::setDefaultApplication($facebook_app_id, $facebook_api_secret);
     // login helper with redirect_uri
     $helper = new FacebookRedirectLoginHelper(site_url('login/facebook'));
     // see if a existing session exists
     if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
         // create new session from saved access_token
         $session = new FacebookSession($_SESSION['fb_token']);
         // validate the access_token to make sure it's still valid
         try {
             if (!$session->validate()) {
                 $session = null;
             }
         } catch (Exception $e) {
             // catch any exceptions
             $session = null;
         }
     }
     if (!isset($session) || $session === null) {
         // no session exists
         try {
             $session = $helper->getSessionFromRedirect();
         } catch (FacebookRequestException $ex) {
             // When Facebook returns an error
             // handle this better in production code
             print_r($ex);
         } catch (Exception $ex) {
             // When validation fails or other local issues
             // handle this better in production code
             print_r($ex);
         }
     }
     // see if we have a session
     if (isset($session)) {
         // save the session
         $_SESSION['fb_token'] = $session->getToken();
         // create a session using saved token or the new one we generated at login
         $session = new FacebookSession($session->getToken());
         // graph api request for user data
         //$request = new FacebookRequest($session, 'GET', '/me/friends');
         $request = new FacebookRequest($session, 'GET', '/me?fields=id,name,picture,friends');
         $response = $request->execute();
         // get response
         $graphObject = $response->getGraphObject()->asArray();
         $fb_data = array('me' => $graphObject, 'loginUrl' => $helper->getLoginUrl($facebook_default_scope));
         $this->ci->session->set_userdata('fb_data', $fb_data);
     } else {
         $fb_data = array('me' => null, 'loginUrl' => $helper->getLoginUrl($facebook_default_scope));
         $this->ci->session->set_userdata('fb_data', $fb_data);
     }
     return $fb_data;
 }
示例#3
0
 public function exchange_long_lived_token($access_token)
 {
     $session = new FacebookSession($access_token);
     // Check validate token
     if ($session->validate()) {
         $long_lived_session = $session->getLongLivedSession();
         return $long_lived_session->getToken();
     }
     return false;
 }
示例#4
0
function isLogged()
{
    // Inicializações para autenticação
    // Crie um aplicativo no Facebook e configure aqui o ID e a chave secreta obtidos no site
    $id = '987654321012345';
    $secret = 'aeiou12345qwert98765asdfg1234567';
    FacebookSession::setDefaultApplication($id, $secret);
    // Inicializa sessão PHP
    session_start();
    // Se o cookie foi recebido numa requisição anterior, e o
    // token FB já foi recuperado, necessita apenas autenticar
    // o usuário no FB usando o token
    if (isset($_SESSION['token'])) {
        $session = new FacebookSession($_SESSION['token']);
        try {
            if (!$session->validate($id, $secret)) {
                unset($session);
            }
        } catch (FacebookRequestException $ex) {
            // Facebook retornou um erro
            // return [false, $ex->getMessage()];
            unset($session);
        } catch (\Exception $ex) {
            // return [false, $ex->getMessage()];
            unset($session);
        }
    }
    // Se o cookie ainda não foi recebido (primeira requisição
    // do cliente), recupera e grava na variável de sessão PHP.
    // Executa autenticação no FB
    if (!isset($session)) {
        try {
            $helper = new FacebookJavaScriptLoginHelper();
            $session = $helper->getSession();
            if ($session) {
                $_SESSION['token'] = $session->getToken();
            }
        } catch (FacebookRequestException $ex) {
            // Facebook retornou um erro
            unset($session);
            return [false, $ex->getMessage()];
        } catch (\Exception $ex) {
            // Falha na validação ou outro erro
            unset($session);
            return [false, $ex->getMessage()];
        }
    }
    // Facebook aceitou usuário/senha
    if (isset($session) && $session) {
        return [true, $_SESSION['token']];
    }
    // Facebook rejeitou usuário/senha
    return [false, "Usuário/senha inválida"];
}
示例#5
0
 public function validate()
 {
     try {
         FacebookSession::setDefaultApplication($this->getParam('APP_ID'), $this->getParam('APP_SECRET'));
         $session = new FacebookSession($this->getParam('TOKEN'));
         $session->validate();
     } catch (FacebookSDKException $f) {
         return false;
     }
     return true;
 }
 /**
  * Get the FacebookSession through an access_token.
  *
  * @param  string $accessToken
  * @return FacebookSession
  */
 private function getFacebookSession($accessToken)
 {
     $facebookSession = new FacebookSession($accessToken);
     try {
         $facebookSession->validate();
         return $facebookSession;
     } catch (FacebookRequestException $ex) {
         throw new FacebookException($ex->getMessage());
     } catch (\Exception $ex) {
         throw new FacebookException($ex->getMessage());
     }
 }
示例#7
0
 /**
  * @param string $accessToken
  * @param string $appId
  * @param string $appSecret
  * @throws \Vegas\Social\Exception
  */
 protected function connect($accessToken, $appId, $appSecret)
 {
     $session = new FacebookSession($accessToken);
     $session->setDefaultApplication($appId, $appSecret);
     if ($session->getToken() == $accessToken) {
         $this->fbSession = $session;
         $this->fbScope = $session->getSessionInfo()->getScopes();
         $this->checkPermissions();
         return $this;
     }
     $this->fbSession = false;
     throw new \Vegas\Social\Exception\InvalidSessionException();
 }
 /**
  * Initializes facebook's connection.
  *
  * @throws FacebookRequestException
  * @throws \Exception
  */
 private function initialize()
 {
     FacebookSession::enableAppSecretProof(false);
     $session = new FacebookSession($this->accessToken);
     try {
         $session->validate();
     } catch (FacebookRequestException $e) {
         $this->entry->addException($e->getMessage());
     } catch (\Exception $e) {
         $this->entry->addException($e->getMessage());
     }
     $this->session = $session;
 }
示例#9
0
 public function matchUser($access_token)
 {
     FacebookSession::setDefaultApplication('1594113490874544', 'fca50280932a6065e68a540ac3f2925b');
     $session = new FacebookSession($access_token);
     try {
         $session->validate();
     } catch (FacebookRequestException $ex) {
         return false;
     } catch (\Exception $ex) {
         return false;
     }
     return true;
 }
示例#10
0
 /**
  * Get the FacebookSession through an access_token.
  *
  * @param string $accessToken
  * @return FacebookSession
  */
 public function getFacebookSession($accessToken)
 {
     $session = new FacebookSession($accessToken);
     // Validate the access_token to make sure it's still valid
     try {
         if (!$session->validate()) {
             $session = null;
         }
     } catch (\Exception $e) {
         // Catch any exceptions
         $session = null;
     }
     return $session;
 }
示例#11
0
 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 BuildLink($params = null)
 {
     require_once 'Facebook/FacebookSDKException.php';
     $APP_ID = $this->GetClientId();
     $APP_SECRET = $this->GetClientSecret();
     if (!isset($APP_ID) || !isset($APP_SECRET)) {
         throw new \Facebook\FacebookSDKException('You must to set the app client credentials');
     }
     require_once 'Facebook/FacebookSession.php';
     \Facebook\FacebookSession::setDefaultApplication($APP_ID, $APP_SECRET);
     $CALLBACK_URL = $this->GetCallbackUrl();
     if (!isset($CALLBACK_URL)) {
         throw new \Facebook\FacebookSDKException('You must to set callback url');
     }
     $SCOPE = $this->GetScope();
     if (!isset($SCOPE)) {
         throw new \Facebook\FacebookSDKException('You must to set scope');
     }
     require_once 'Facebook/FacebookRequest.php';
     require_once 'Facebook/FacebookRedirectLoginHelper.php';
     $helper = new \Facebook\FacebookRedirectLoginHelper($CALLBACK_URL);
     $STATE = $this->GetState();
     if (isset($STATE)) {
         $helper->SetState($STATE);
     }
     $redirectUrl = $helper->getLoginUrl($SCOPE);
     //	var_dump($redirectUrl);
     return $redirectUrl;
 }
 /**
  * Ask for a facebook session 
  * @return boolean
  */
 public final function hasLoggedIn()
 {
     if (is_null($this->fbsession) and !is_null($this->session)) {
         return $this->session->getData("_facebookSession") ?: false;
     }
     return $this->fbsession->validate();
 }
示例#14
0
 /**
  * @return \Facebook\FacebookSession
  */
 public function getSession()
 {
     $conf = json_decode(file_get_contents(realpath(dirname(__FILE__)) . '/config.json'));
     Api::init($conf->applicationId, $conf->applicationSecret, $conf->accessToken);
     FacebookSession::setDefaultApplication($conf->applicationId, $conf->applicationSecret);
     return new FacebookSession($conf->accessToken);
 }
示例#15
0
 /**
  * @return FacebookSession
  */
 protected function getSession()
 {
     if (!$this->session) {
         $this->session = FacebookSession::newAppSession();
     }
     return $this->session;
 }
示例#16
0
 public function register($kernel, $options = array())
 {
     FacebookSession::setDefaultApplication($options['AppId'], $options['AppSecret']);
     $kernel->facebookSession = function () use($options) {
         return FacebookSession::newAppSession();
     };
 }
示例#17
0
文件: Facebook.php 项目: Xackery/coop
 public function action_index()
 {
     $gameList = DB::query(Database::SELECT, "SELECT * FROM game")->execute();
     $this->template->content = $gameList[0]['name'];
     require_once Kohana::find_file('vendor', 'vendor/autoload');
     $config = Kohana::$config->load('auth');
     //$session = Session::instance($config['session_type']);
     FacebookSession::setDefaultApplication('376812619137510', 'd054fff7f6146da72c9585d78d0357b5');
     $helper = new FacebookJavaScriptLoginHelper();
     try {
         $session = $helper->getSession();
     } catch (FacebookRequestException $ex) {
         // When Facebook returns an error
         $this->template->content = "fb returned an error";
     } catch (\Exception $ex) {
         // When validation fails or other local issues
         $this->template->content = "validation failed";
         //print_r($ex);
     }
     if (isset($session)) {
         $request = new FacebookRequest($session, 'GET', '/me');
         $response = $request->execute();
         $graphObject = $response->getGraphObject();
         if (isset($graphObject->id)) {
             $loginData = array('first_name' => $graphObject->first_name);
         }
         $this->template->content = "Hi, " . $graphObject->getProperty('first_name');
     } else {
         echo "No session";
     }
 }
 public function __construct()
 {
     $this->ci =& get_instance();
     FacebookSession::setDefaultApplication($this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook'));
     $this->helper = new FacebookRedirectLoginHelper($this->ci->config->item('redirect_url', 'facebook'));
     if ($this->ci->session->userdata('fb_token')) {
         $this->session = new FacebookSession($this->ci->session->userdata('fb_token'));
         // Validate the access_token to make sure it's still valid
         try {
             if (!$this->session->validate()) {
                 $this->session = false;
             }
         } catch (Exception $e) {
             // Catch any exceptions
             $this->session = false;
         }
     } else {
         try {
             $this->session = $this->helper->getSessionFromRedirect();
         } catch (FacebookRequestException $ex) {
             // When Facebook returns an error
         } catch (\Exception $ex) {
             // When validation fails or other local issues
         }
     }
     if ($this->session) {
         $this->ci->session->set_userdata('fb_token', $this->session->getToken());
         $this->session = new FacebookSession($this->session->getToken());
     }
 }
示例#19
0
文件: User.php 项目: RobertDuy/vnup
 function __construct()
 {
     parent::__construct();
     $this->load->helper('form');
     $this->load->library('form_validation');
     $this->load->library('session');
     $this->load->library('email');
     $this->load->helper('url');
     $this->load->helper('cookie');
     $this->load->model('user_model');
     $this->load->model('user_cookie_model');
     // setting up email ===============================================
     $config['useragent'] = "Codeigniter";
     $config['protocol'] = "smtp";
     $config['smtp_host'] = "smtp.gmail.com";
     $config['smtp_port'] = "465";
     $config['smtp_user'] = "******";
     $config['smtp_pass'] = "******";
     $config['charset'] = "utf-8";
     $config['mailtype'] = "html";
     $config['newline'] = "\r\n";
     $config['smtp_crypto'] = "ssl";
     $this->email->initialize($config);
     $this->email->from('*****@*****.**', 'VN UP TEST');
     // ==================================================================
     $this->default_redirectURL = config_item('base_url') . 'user/user';
     FacebookSession::setDefaultApplication($this->app_id, $this->app_secret);
     $this->helper = new FacebookRedirectLoginHelper($this->default_redirectURL);
     $this->wp_hasher = new PasswordHash(8, true);
 }
示例#20
0
 private function getSession()
 {
     $session = "";
     FacebookSession::setDefaultApplication(Config::get('facebook.appid'), Config::get('facebook.secret'));
     if (isset($_SESSION['token'])) {
         // We have a token, is it valid?
         $session = new FacebookSession($_SESSION['token']);
         try {
             $session->Validate(Config::get('facebook.appid'), Config::get('facebook.secret'));
         } catch (FacebookAuthorizationException $ex) {
             // Session is not valid any more, get a new one.
             $session = '';
         }
     }
     return $session;
 }
 /**
  * @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');
 }
示例#22
0
 /**
  * @return FacebookRedirectLoginHelper
  */
 protected function getFacebookRedirectLoginHelper()
 {
     FacebookSession::setDefaultApplication($this->appId, $this->appSecret);
     $helper = new FacebookRedirectLoginHelper($this->getRedirectUrl());
     $helper->disableSessionStatusCheck();
     return $helper;
 }
 /**
  * This function runs the script
  * @param $name string
  * @param $args array | null
  */
 public function run($name, $args)
 {
     if ($name != Website::WEBSITE_SCRIPT_TYPE_PRESCRIPT) {
         return;
     }
     $credentials = $this->backendContainer->getConfigInstance()->getFacebookAppCredentials();
     if (($id = $credentials['id']) == "" || ($secret = $credentials['secret']) == "" || !isset($this->backendContainer->getConfigInstance()['facebook_page_id'])) {
         return;
     }
     FacebookSession::setDefaultApplication($id, $secret);
     $this->backendContainer->facebookPage = function (BackendSingletonContainer $container) {
         return new FacebookPageImpl($container, $this->backendContainer->getConfigInstance()['facebook_page_id']);
     };
     $vars = $this->backendContainer->getSiteInstance()->getVariables();
     $k = 'FacebookSessionInitializePreScriptImpl_last_updated';
     if ($vars->hasKey($k) && $vars->getValue($k) > time() - 86400) {
         return;
     }
     $vars->setValue($k, time());
     /** @var FacebookPage $fb */
     $fb = $this->backendContainer->facebookPage;
     if ($fb->update()) {
         $this->backendContainer->getSiteInstance()->modify();
     }
 }
示例#24
0
 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;
 }
示例#25
0
 protected function initialize()
 {
     if (!$this->loaded) {
         FacebookSession::setDefaultApplication(Config::get('accounts.facebook.id'), Config::get('accounts.facebook.secret'));
         $this->loaded = true;
     }
 }
 /**
  * Create a new FacebookInsights instance.
  *
  * @param  \Illuminate\Config\Repository  $config
  */
 public function __construct(Repository $config)
 {
     $this->config = $config;
     $this->pageId = $this->config->get('facebook-insights::page-id');
     FacebookSession::setDefaultApplication($this->config->get('facebook-insights::app-id'), $this->config->get('facebook-insights::app-secret'));
     $this->session[$this->pageId] = new FacebookSession($this->config->get('facebook-insights::access-token'));
 }
 private function create_fb_session()
 {
     // Facebook app config
     FacebookSession::setDefaultApplication($this->app_id, $this->app_secret);
     // Facebook session login
     $this->fb_session = new FacebookSession($this->access_token);
 }
示例#28
0
 public function getAppSession()
 {
     if ($this->appSession) {
         return $this->appSession;
     }
     return $this->appSession = FacebookSession::newAppSession();
 }
 /**
  * Instantiates a FacebookSession from the signed request from input.
  *
  * @return FacebookSession|null
  */
 public function getSession()
 {
     if ($this->signedRequest && $this->signedRequest->hasOAuthData()) {
         return FacebookSession::newSessionFromSignedRequest($this->signedRequest);
     }
     return null;
 }
示例#30
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);
 }