Last active
August 29, 2015 14:06
-
-
Save hassanabidpk/36137e5f9d13f7002415 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
composer.json | |
------------- | |
{ | |
"require": { | |
"facebook/php-sdk" : "*" | |
} | |
} | |
Phalcon Bootstrap index.php | |
--------------------------- | |
<?php | |
$di->setShared('facebook', function() use ($api) { | |
return new \Facebook([ | |
'appId' => $api->fb->appId, | |
'secret' => $api->fb->secret, | |
]); | |
}); | |
?> | |
Your Controller Method: | |
--------------------- | |
<?php | |
/** | |
* Logs a user in via facebook | |
* | |
* @return void | |
*/ | |
const REDIRECT_FAILURE = 'login'; | |
const REDIRECT_SUCCESS = 'dashboard'; | |
public function doFacebookAction() | |
{ | |
$facebookId = $this->facebook->getUser(); | |
if (!$facebookId) | |
{ | |
$this->flash->error("Invalid Facebook Call."); | |
return $this->response->redirect(self::REDIRECT_FAILURE); | |
} | |
try{ | |
$facebookUser = $this->facebook->api('/me'); | |
} catch (\FacebookApiException $e) { | |
$this->flash->error("Could not fetch your facebook user."); | |
return $this->response->redirect(self::REDIRECT_FAILURE); | |
} | |
$user = \User::findFirstByFacebookId($facebookId); | |
if (!$user) { | |
// Save user record in database | |
$user = new \User(); | |
$user->facebook_id = $facebookUser['id']; | |
$user->create(); | |
if ($user->getMessages()) { | |
$error = new \Error(); | |
$error->content = "Error creating facebook user with id {$facebookUser['id']}"; | |
$this->flash->error('There was an error connecting your facebook user.'); | |
return $this->response->redirect(self::REDIRECT_FAILURE); | |
} | |
} | |
// This is how I create a Session, do it your own way | |
$this->component->user->createSession($user, [ | |
'facebook_id' => $facebookId, | |
'facebook_logout_url' => $this->facebook->getLogoutUrl() | |
]); | |
return $this->response->redirect(self::REDIRECT_SUCCESS); | |
} | |
?> | |
Logging Out (In arbitrary controller) | |
------------------------------------- | |
<?php | |
public function logout() { | |
$this->session->destroy(); | |
$this->facebook->destroySession(); | |
$this->facebook->setAccessToken(''); | |
return $this->response->redirect($this->facebook->getLogoutUrl(), true); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment