public function testARawSignedRequestCanBeRetrievedFromCookieData() { $_COOKIE['fbsr_123'] = $this->rawSignedRequestAuthorized; $helper = new FacebookJavaScriptLoginHelper($this->appId, $this->appSecret); $rawSignedRequest = $helper->getRawSignedRequest(); $this->assertEquals($this->rawSignedRequestAuthorized, $rawSignedRequest); }
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 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; } } }
public function testGetSessionFromCookie() { $helper = new FacebookJavaScriptLoginHelper(FacebookTestCredentials::$appId); $signedRequest = FacebookSessionTest::makeSignedRequest(array('oauth_token' => 'token')); $_COOKIE['fbsr_' . FacebookTestCredentials::$appId] = $signedRequest; $session = $helper->getSession(); $this->assertTrue($session instanceof FacebookSession); $this->assertTrue($session->getToken() == 'token'); }
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"]; }
private function set_session() { if (empty($this->fb_session)) { $helper = new FacebookJavaScriptLoginHelper($this->fb_app_id); try { $this->fb_session = $helper->getSession(); } catch (FacebookRequestException $ex) { //print_r($ex); } catch (\Exception $ex) { //print_r($ex); } } }
protected function initFacebookSession() { // first try from redirect try { $helper = new FacebookRedirectLoginHelper(ROOT_URL); $this->fb = $helper->getSessionFromRedirect(); } catch (\Exception $ex) { // When validation fails or other local issues } if (!$this->fb) { // next try from canvas try { $helper = new FacebookCanvasLoginHelper(); $this->fb = $helper->getSession(); } catch (\Exception $ex) { // When validation fails or other local issues } } if (!$this->fb) { // next try from JS try { $helper = new FacebookJavaScriptLoginHelper(); $this->fb = $helper->getSession(); } catch (\Exception $ex) { // When validation fails or other local issues } } // finally fall back to an existing session, if we have one if (!$this->fb && !empty($_SESSION['fb_token'])) { try { $this->fb = new FacebookSession($_SESSION['fb_token']); $this->fb->validate(); } catch (\Exception $ex) { // When validation fails or other local issues } } if ($this->fb) { // Logged in try { $_SESSION['fb_token'] = $this->fb->getToken(); $user_profile = (new FacebookRequest($this->fb, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); $this->fb_uid = $user_profile->getId(); } catch (\Exception $e) { $this->fb = null; } } if (!$this->fb) { session_destroy(); } }
private function _getFacebookSessionFromJavaScript() { $helper = new FacebookJavaScriptLoginHelper(); try { return $helper->getSession(); } catch (FacebookRequestException $ex) { // When Facebook returns an error //if (APPLICATION_ENV=="dev") { Log::error($ex->getMessage()); //} return false; } catch (\Exception $ex) { // When validation fails or other local issues if (App::environment('dev')) { Log::error($ex->getMessage()); } return false; } }
} } return $ipaddress; } //When a GET request is received if (isset($_GET)) { $peticion = $_GET['tipo']; //Type of petition (in spanish) //Petition types: //validar = validate = check if session is open (user logged in) //datos = data = returns the Graph User data on JSON format (name, birthday, email, sex, age calculated from birthdate on user's profile) //foto = picture = returns a link for the profile picture of the user //ip = returns the client's public ip address, for location tracking use //$respuestaJSON = JSON object with the response data if ($peticion == "validar") { $helper = new FacebookJavaScriptLoginHelper(); try { $session = $helper->getSession(); } catch (FacebookRequestException $ex) { // When Facebook returns an error echo $ex; } catch (\Exception $ex) { // When validation fails or other local issues echo $ex; } if (isset($session)) { $_SESSION['token'] = $session->getToken(); $loginStatus = true; } else { $loginStatus = false; }
public function facebook_login() { $fbAppID = Configure::read('System.Facebook.AppID'); $fbSecret = Configure::read('System.Facebook.AppSecret'); FacebookSession::setDefaultApplication($fbAppID, $fbSecret); $helper = new FacebookJavaScriptLoginHelper(); try { $session = $helper->getSession(); } catch (FacebookRequestException $ex) { die('Error get FB session'); } catch (\Exception $ex) { die('Error get FB session'); } if ($session) { try { $user = new FacebookRequest($session, 'GET', '/me'); $user = $user->execute(); $user = $user->getGraphObject(GraphUser::className()); } catch (FacebookRequestException $e) { echo "Exception occured, code: " . $e->getCode(); echo " with message: " . $e->getMessage(); } } if (isset($user) && $user) { $fbid = $user->getProperty("id"); $email = $user->getProperty("email"); $firstName = $user->getProperty("first_name"); $lastName = $user->getProperty("last_name"); $user = $this->Users->find()->where(['facebook_id' => $fbid, 'status <>' => USER_STATUS_DELETED])->first(); if ($user) { // Has already login fb before => Allow to login $this->request->session()->write('Core.Users', $user); $this->redirect(['plugin' => 'admin', 'controller' => 'pages', 'action' => 'index']); } else { // Check email exist or not $user = $this->Users->find()->where(['email' => $email, 'status <>' => USER_STATUS_DELETED])->first(); if ($user) { //Exist Real account => not allow to login using facebook $this->Flash->success(__('This email exist in the system and cannot be using Facebook')); $this->redirect($this->referer()); } else { $userEntity = $this->Users->newEntity(); $userEntity->email = $email; $userEntity->facebook_id = $fbid; $userEntity->first_name = $firstName; $userEntity->last_name = $lastName; $userEntity->auth_token = \Core::randomCode(); $userEntity->status = USER_STATUS_ACTIVE; if ($this->Users->save($userEntity)) { $this->request->session()->write('Core.Users', $userEntity); $this->redirect($this->referer()); } else { $this->Flash->warning(__('Cannot create member account')); $this->redirect($this->referer()); } } } } else { $scope = ['email', 'public_profile']; $loginUrl = $helper->getLoginUrl($scope); $this->redirect($loginUrl); } }
/** * return FacebookSession $session; */ function getFacebookJsSession() { if (is_null($this->session)) { try { $helper = new FacebookJavaScriptLoginHelper(); $this->session = $helper->getSession(); } catch (Exception $e) { return null; } } return $this->session; }
/** * * Handels the Facebook Login / Signup based on the Request * * @return void */ public function fblogin() { $this->request->session()->write('FB_LOGIN', 'TRUE'); FacebookSession::setDefaultApplication(Configure::read('FB.appid'), Configure::read('FB.secret')); $fb_arr = array(); $fb_arr = $this->request->query('fb_login'); if (!empty($fb_arr)) { $helper = new FacebookRedirectLoginHelper(Router::url(['action' => 'fblogin', '_full' => true])); $this->redirect($helper->getLoginUrl(array('email', 'public_profile'))); return; } if ($this->request->query('fb_js_login')) { $helper = new FacebookJavaScriptLoginHelper(); $session = $helper->getSession(); $isJSReq = TRUE; } else { $helper = new FacebookRedirectLoginHelper(Router::url(['action' => 'fblogin', '_full' => true])); $session = $helper->getSessionFromRedirect(); } try { $request = new FacebookRequest($session, 'GET', '/me?fields=id,email,first_name,last_name'); $response = $request->execute(); $graphObject = $response->getGraphObject(); // Collect the basic User details from the FB Graph Response $userData = array('fb_id' => 'fb_' . $graphObject->getProperty('id'), 'name' => $graphObject->getProperty('first_name') . ' ' . $graphObject->getProperty('last_name'), 'email' => $graphObject->getProperty('email'), 'first_name' => $graphObject->getProperty('first_name'), 'last_name' => $graphObject->getProperty('last_name')); //pr($userData); //die('we are here for testing'); /** * * Checkes weather the Email already register with us in case it is * Register than Link the Facebook Account with the Account in case * the Email address isn't register with us in that case Sign up the * User. */ $users = $this->Users->findByEmail($userData['email'])->toArray(); if (count($users) > 0) { $this->Auth->setUser($users); $user = $users[0]; $user->fb_connect = $userData['fb_id']; $user->status = 'active'; } else { $randomPassword = $this->Users->generateRandomString(); $user = $this->Users->patchEntity($this->Users->newEntity(), $userData); $user->password = $randomPassword; $user->role = 'customer'; $user->status = 'active'; $user->fb_connect = $userData['fb_id']; } $this->Users->save($user); $this->Auth->setUser($user->toArray()); $this->redirect('/'); } catch (\Exception $ex) { $this->redirect('/'); } }
public function loginWithFb() { $redirectUrl = Input::get('redirect_url'); $facebookBaseConfig = Config::get('facebook'); $config = app('siteConfig'); $facebookConfig = $config['main']['social']['facebook']; $facebookConfig['appId'] = empty($facebookConfig['appId']) ? '' : $facebookConfig['appId']; $facebookConfig['secret'] = empty($facebookConfig['secret']) ? '' : $facebookConfig['secret']; FacebookSession::setDefaultApplication($facebookConfig['appId'], $facebookConfig['secret']); $helper = new FacebookJavaScriptLoginHelper(); $session = null; function getUserDataFromFb($session) { $request = new FacebookRequest($session, 'GET', '/me', array('fields' => 'id,name,email')); $response = $request->execute(); $graphObject = $response->getGraphObject()->asArray(); return $graphObject; } try { $session = $helper->getSession(); } catch (FacebookRequestException $ex) { // When Facebook returns an error } catch (\Exception $ex) { // When validation fails or other local issues } if (Request::ajax()) { if ($session) { // Logged in. $uid = $session->getUserId(); $accessToken = $session->getToken(); $profile = Profile::whereUid($uid)->first(); if (empty($profile)) { $me = getUserDataFromFb($session); $user = new User(); $user->name = $me['name']; $user->email = $me['email']; $user->photo = 'https://graph.facebook.com/' . $uid . '/picture?type=large'; $user->save(); $profile = new Profile(); $profile->uid = $uid; //$profile->username = $me['username']; //Username not available in the new Facebook API $profile->access_token = $accessToken; $profile = $user->profiles()->save($profile); } else { $profile->access_token = $accessToken; $profile->save(); } $user = $profile->user; Auth::login($user); return Response::json(array('user' => $user)); } else { return Response::make('Not loggedin', 400); } } else { if ($session) { if ($redirectUrl) { return Redirect::to($redirectUrl); } else { return Redirect::route('home'); } } return Redirect::route('login'); } }