Example #1
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;
 }
Example #2
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);
 }
 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;
     }
 }
Example #4
0
 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');
 }
Example #6
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;
 }
 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);
 }
Example #8
0
 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 [];
 }
Example #11
0
 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());
 }
Example #12
0
 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());
 }
Example #13
0
 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>";
 }
 /**
  * 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());
     }
 }
Example #15
0
 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 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;
 }
 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());
 }
Example #18
0
 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());
     }
 }
Example #20
0
 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();
     }
 }
Example #22
0
 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) {
         }
     }
 }
 /**
  * Performs an authentication attempt
  *
  * @return \Zend\Authentication\Result
  * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface If authentication cannot be performed
  */
 public function authenticate()
 {
     try {
         $service = $this->service;
         $session = $service->getSession();
         $me = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className());
         $res = new OAuth2Result($this->authenticationService, Result::SUCCESS, $me->getId());
         $res->setUserProfile($this->createUserProfile($session, $me));
         //TODO
         //$res->setAccessToken($token->accessToken);
         //$res->setRefreshToken($token->refreshToken);
         //$res->setExpiresIn($token->expires);
         return $res;
     } catch (FacebookRequestException $ex) {
         // When Facebook returns an error
         return new Result($this->authenticationService, Result::FAILURE_CREDENTIAL_INVALID, array(), array("Facebook request exception - " . $ex->getErrorType() . " - " . $ex->getMessage()));
     } catch (\Exception $ex) {
         // When validation fails or other local issues
         return new Result($this->authenticationService, Result::FAILURE, array(), array("General exception - " . $ex->getMessage()));
     }
 }
Example #24
0
 /**
  * @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;
 }
Example #25
0
 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;
     }
 }
Example #26
0
 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}");
     }
 }
 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;
 }
Example #28
0
 public function doFacebookRequest($session, $method, $request)
 {
     $result = (new FacebookRequest($session, $method, $request))->execute()->getGraphObject(GraphUser::className());
     return $result;
 }
Example #29
0
 $my_url = BASE_URL . 'oauth2/facebook/connexion/';
 \Facebook\FacebookSession::setDefaultApplication($app_id, $app_secret);
 $helper = new \Facebook\FacebookRedirectLoginHelper($my_url);
 $loginUrl = $helper->getLoginUrl();
 if (isset($_GET['code'])) {
     $code = $_GET['code'];
     $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code;
     $response = @file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);
     $acces_token = $params['access_token'];
     // If you already have a valid access token:
     $session = new \Facebook\FacebookSession($acces_token);
     // To validate the session:
     try {
         $user_profile = (new \Facebook\FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(\Facebook\GraphUser::className());
         $email = $user_profile->getEmail();
         if ($email) {
             $UserFacebookQuery = new UserFacebookQuery($crud);
             $UserFacebookQuery->filterByEmail($email);
             $UserFacebookQuery->find();
             $UserFacebookEntity = $UserFacebookQuery->_getEntity();
             // L'utilisateur existe
             if ($UserFacebookEntity) {
                 $UserFacebookEntity->setAccessToken($acces_token);
                 $UserFacebookEntity->setDateModification(time());
                 $UserFacebookEntity->save();
                 $_SESSION['oauth2']['facebook'] = $acces_token;
                 // L'utilisateur n'existe pas
             } else {
                 $UserFacebookEntity = new UserFacebookEntity(null, $crud);
Example #30
0
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Facebook\FacebookHttpable;
use Facebook\FacebookCurlHttpClient;
use Facebook\FacebookCurl;
$app_id = '1566678260239016';
$app_secret = 'c237a840aaf9371f56806a01767960a0';
$redirect_url = 'http://nubespic.com/logext.php';
FacebookSession::setDefaultApplication($app_id, $app_secret);
$helper = new FacebookRedirectLoginHelper($redirect_url);
$sess = $helper->getSessionFromRedirect();
$mensaje = "";
if (isset($sess)) {
    $request = new FacebookRequest($sess, 'GET', '/me');
    $response = $request->execute();
    $graph = $response->getGraphObject(GraphUser::className());
    $name = $graph->getName();
    $id = $graph->getId();
    $email = $graph->getProperty('email');
    $imagen = "https://graph.facebook.com/" . $id . "/picture";
    $_SESSION["user"] = $name;
    $_SESSION["userid"] = $id;
    $_SESSION["foto"] = $imagen;
    //echo var_dump($_SESSION);
    $consulta = $db->queryMySQL("SELECT * FROM usuario WHERE idFB = " . $id);
    $nbr = $db->num_rows($consulta);
    if ($nbr == 0) {
        $insertarUsuario = $db->queryMySQL("INSERT INTO usuario (idUsuario,idFB,nombre,correo) VALUES ('NULL','{$id}','{$name}','{$email}')");
        $_SESSION["id"] = $db->insert_id();
    } else {
        $usuarioRegistrado = $db->queryMySQL("SELECT * FROM usuario WHERE idFB=" . $id);