I created a Facebook login on my site, then when I get data of a user logged, I created an array session to store the information of users in my controller.
I have problem with this session when I go to another page, my session gets lost, I don't know what happens with this?
I set the session like this: $this->session->set_userdata('fb_user_info', $user_info);
But, my own account login, I do the same way, it works on all pages.
My question is, Why does the session get lost?
Here is my code to set session when get user_info
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Account extends CI_Controller {
public function __construct()
{
parent::__construct();
//$this->authenticate();
// Facebook constructor code
$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$config = $CI->config->item('facebook');
$this->load->library('facebook', $config);
public function index()
{
$user = $this->facebook->getUser();
if($user) {
try {
$user_info = $this->facebook->api('/me');
// Set session
$this->session->set_userdata('FB_SESSION_INFO', $user_info);
$args = $logout_url;
$data['getLogoutUrl'] = $this->facebook->getLogoutUrl($args);
} catch(FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
} else {
$param = array('scope' => 'email','redirect_uri' => $mycurrent_url);
$data['getURLLogin'] = "Login with facebook";
}
}
Related
I am using facebook login in codeigniter and when i run localhost project its working fine but when i upload files on my server its not working . I changed my SITE URL and DOMAIN NAME from facebook developer but still facing the issue.
I found many article from google but did not resolve it.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class User_Authentication extends CI_Controller
{
function __construct() {
parent::__construct();
// Load facebook library
$this->load->library('facebook');
//Load user model
$this->load->model('user');
}
public function index(){
$userData = array();
// Check if user is logged in
if($this->facebook->is_authenticated()){
// Get user facebook profile details
$userProfile = $this->facebook->request('get', '/me?fields=id,first_name,last_name,email,gender,locale,picture');
// Preparing data for database insertion
$userData['oauth_provider'] = 'facebook';
$userData['oauth_uid'] = $userProfile['id'];
$userData['first_name'] = $userProfile['first_name'];
$userData['last_name'] = $userProfile['last_name'];
$userData['email'] = $userProfile['email'];
$userData['gender'] = $userProfile['gender'];
$userData['locale'] = $userProfile['locale'];
$userData['profile_url'] = 'https://www.facebook.com/'.$userProfile['id'];
$userData['picture_url'] = $userProfile['picture']['data']['url'];
// Insert or update user data
$userID = $this->user->checkUser($userData);
// Check user data insert or update status
if(!empty($userID)){
$data['userData'] = $userData;
$this->session->set_userdata('userData',$userData);
} else {
$data['userData'] = array();
}
// Get logout URL
$data['logoutUrl'] = $this->facebook->logout_url();
}else{
$fbuser = '';
// Get login URL
$data['authUrl'] = $this->facebook->login_url();
}
// Load login & profile view
$this->load->view('user_authentication/index',$data);
}
public function logout() {
// Remove local Facebook session
$this->facebook->destroy_session();
// Remove user data from session
$this->session->unset_userdata('userData');
// Redirect to login page
redirect('user_authentication');
}
}
So, I tried Facebook login with Codeigniter on localhost and everything was Ok - When I pressed login button, it showed my profile picture and logout button.
Then I uploaded script on webhost. I'm pressing login button and expect to see my profile picture, but nothing! Except for one thing, website ir, for example, on www.example.com. I press login and address bar shows www.example.com/index.php?code=AQCTt5KzYV8TKKqU5nUUuy0d5DhQLJdFOlDgJ... etc.
There's my welcome.php controller's code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Prakse extends CI_Controller {
public function __construct(){
parent::__construct();
// To use site_url and redirect on this controller.
$this->load->helper(array('form', 'url'));
}
public function login() {
$this->load->library('facebook');
$user = $this->facebook->getUser();
if ($user) {
try {
$data['user_profile'] = $this->facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}else {
$this->facebook->destroySession();
}
if ($user) {
$data['logout_url'] = site_url('welcome/logout'); // Logs off application
// OR
// Logs off FB!
// $data['logout_url'] = $this->facebook->getLogoutUrl();
} else {
$data['login_url'] = $this->facebook->getLoginUrl(array(
'redirect_uri' => site_url('welcome/login'),
'scope' => array("email") // permissions here
));
}
$this->load->view('login',$data);
}
public function logout() {
$this->load->library('facebook');
// Logs off session from website
$this->facebook->destroySession();
// Make sure you destory website session as well.
redirect('welcome/login');
}
}
Help me please. Thank you.
Check https://developers.facebook.com/apps/[your_app_id]/settings/ and make sure app domains and site url are set correctly.
I've recently started using Zend Framework and I'm still pretty used to session_start, and assigning variables to certain session names (ie: $_SESSION['username'] == $username)
I'm trying to figure out how to do something similar to this in Zend. Right now, my auth script checks the credentials using LDAP against my AD server and, if successful, authenticates the user.
I want to create a script that will allow an admin user to easily "enter" someone else's session. Let's say admin1 had an active session and wanted to switch into user1's session. Normally I would just change the $_SESSION['username'] variable and effectively change the identity of the user logged in.
But with Zend, I'm not quite sure how to change the session info. For what it's worth, here's my authentication script:
class LoginController extends Zend_Controller_Action
{
public function getForm()
{
return new LoginForm(array(
'action' => '/login/process',
'method' => 'post',
));
}
public function getAuthAdapter(array $params)
{
$username = $params['username'];
$password = $params['password'];
$auth = Zend_Auth::getInstance();
require_once 'Zend/Config/Ini.php';
$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');
$log_path = $config->ldap->log_path;
$options = $config->ldap->toArray();
unset($options['log_path']);
require_once 'Zend/Auth/Adapter/Ldap.php';
$adapter = new Zend_Auth_Adapter_Ldap($options, $username, $password);
$result = $auth->authenticate($adapter);
if ($log_path) {
$messages = $result->getMessages();
require_once 'Zend/Log.php';
require_once 'Zend/Log/Writer/Stream.php';
require_once 'Zend/Log/Filter/Priority.php';
$logger = new Zend_Log();
$logger->addWriter(new Zend_Log_Writer_Stream($log_path));
$filter = new Zend_Log_Filter_Priority(Zend_Log::DEBUG);
$logger->addFilter($filter);
foreach ($messages as $i => $message) {
if ($i-- > 1) { // $messages[2] and up are log messages
$message = str_replace("\n", "\n ", $message);
$logger->log("Ldap: $i: $message", Zend_Log::DEBUG);
}
}
}
return $adapter;
}
public function preDispatch()
{
if (Zend_Auth::getInstance()->hasIdentity()) {
// If the user is logged in, we don't want to show the login form;
// however, the logout action should still be available
if ('logout' != $this->getRequest()->getActionName()) {
$this->_helper->redirector('index', 'index');
}
} else {
// If they aren't, they can't logout, so that action should
// redirect to the login form
if ('logout' == $this->getRequest()->getActionName()) {
$this->_helper->redirector('index');
}
}
}
public function indexAction()
{
$this->view->form = $this->getForm();
}
public function processAction()
{
$request = $this->getRequest();
// Check if we have a POST request
if (!$request->isPost()) {
return $this->_helper->redirector('index');
}
// Get our form and validate it
$form = $this->getForm();
if (!$form->isValid($request->getPost())) {
// Invalid entries
$this->view->form = $form;
return $this->render('index'); // re-render the login form
}
// Get our authentication adapter and check credentials
$adapter = $this->getAuthAdapter($form->getValues());
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
// Invalid credentials
$form->setDescription('Invalid credentials provided');
$this->view->form = $form;
return $this->render('index'); // re-render the login form
}
// We're authenticated! Redirect to the home page
$this->_helper->redirector('index', 'index');
}
public function logoutAction()
{
Zend_Auth::getInstance()->clearIdentity();
$this->_helper->redirector('index'); // back to login page
}
}
Is there any way to do what I have described? Thanks for any suggestions.
Given your code, the result of authenticating is stored in the PHP session through a Zend_Auth_Storage_Session object.
Calling Zend_Auth::getIdentity() gets access to the storage and returns the result if it is not empty. Likewise, you can change the stored identity by getting access to the underlying storage and changing its value. The actual identity stored as a result of authenticating with Zend_Auth_Adapter_Ldap is just a string value representing the LDAP username.
To effectively change the logged in user, you can do:
Zend_Auth::getInstance()->getStorage()->write('newUserName');
This assumes the default behavior which should be in place given your code.
What I do in my applications after successful authentication is to create a new object of some User model, and write that to the Zend_Auth session so that I have more information about the user available in each session, so you should be aware that different things can be in the storage depending on the application.
This is what I do for example:
$auth = new Zend_Auth(...);
$authResult = $auth->authenticate();
if ($authResult->isValid() == true) {
$userobj = new Application_Model_UserSession();
// populate $userobj with much information about the user
$auth->getStorage()->write($userobj);
}
Now anywhere in my application I call Zend_Auth::getInstance()->getIdentity() I get back the Application_Model_UserSession object rather than a string; but I digress.
The information that should help you is:
$user = Zend_Auth::getInstance()->getIdentity(); // reads from auth->getStorage()
Zend_Auth::getInstance()->getStorage()->write($newUser);
I am using Zend_auth for authentication purposes.Code for the same is as follows:
$authAdapter = $this->getAuthAdapter();
$authAdapter->setIdentity($username)
->setCredential($password);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
# is the user a valid one?
if ($result->isValid()) {
# all info about this user from the login table
# ommit only the password, we don't need that
$userInfo = $authAdapter->getResultRowObject(null, 'password');
# the default storage is a session with namespace Zend_Auth
$authStorage = $auth->getStorage();
$authStorage->write($userInfo);
$emp_id = $userInfo->employee_id;
$userInfo = Zend_Auth::getInstance()->getStorage()->read();
$array_db = new Application_Model_SetMstDb();
$array_name = $array_db->getName($emp_id);
foreach ($array_name as $name) :
$fname = $name['first_name'];
$lname = $name['last_name'];
endforeach;
$firstname = new stdClass;
$lastname = new stdClass;
$userInfo->firstname = $fname;
$userInfo->lastname = $lname;
$privilege_id = $userInfo->privilege_id;
echo 'privilege in Login: ' . $privilege_id;
$this->_redirect('index/index');
} else {
$errorMessage = "Invalid username or password";
$this->view->error = $errorMessage;
}
where getAuthAdapter() as follows:
protected function getAuthAdapter() {
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('credentials')
->setIdentityColumn('employee_id')
->setCredentialColumn('password');
return $authAdapter;
}
I want to set a session timeout.I want to set a timeout of 5 mins and when user does not being active for 5 mins then session should be expired that is logout action should be called whose code is as follows:
public function logoutAction() {
// action body
Zend_Auth::getInstance()->clearIdentity();
$this->_redirect('login/index');
}
Thanks in advance.Plz Help me.Its urgent.
When I use
$session = new Zend_Session_Namespace( 'Zend_Auth' );
$session->setExpirationSeconds( 60 );
control redirects to login page automatically after 60 seconds but I want that if the user of the application in inactive for 60 seconds then only it redirects.At present whether user is active or not redirection occurs.
I wouldn't use init() for this. init() should be use to set object state.
I would use preDispatch(). But to avoid using it all controllers or making a base controller and then extending. You could do a plugin and add it on the Bootstrap.
class YourControllerPlugin extends Zend_Controller_Plugin_Abstract {
public function preDispatch() {
//check if expired
if(hasExpired()) {
//logout and redirect
}
}
}
to add it on Bootstrap :
public function __initYourPlugin () {
$this->bootstrap('frontController');
$plugin = new YourControllerPlugin();
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin($plugin);
return $plugin;
}
I'm looking at my code for this right now. This snippet is from a front controller plugin. Each time an authenticated user requests a page, I reset their session expiration so they've got 60mins from they were last "active".
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {
//check whether the client is authenticated
if (Zend_Auth::getInstance()->hasIdentity()) {
$session = $this->_getAuthSession();
//update session expiry date to 60mins from NOW
$session->setExpirationSeconds(60*60);
return;
}
Aside: I'm looking over this code for a way to show the user a "your session has expired" message rather than the current "you're not authenticated" message.
Going over the Facebook API and I'm a bit confused on the right approach. I want users to skip registration, or auto-register them if they sign in with Facebook. So if they sign into Facebook I collect their id, email and create a record in my user table.
If an id exists already in the user table they skip the auto-registration and go directly to the members page. This is my code so far (taken from Facebook's PHP SDK example). When I run the signup script the page shows up as blank, I do not get redirected.
EDIT: seems to be failing right after the require, if I use the following code 'test' never gets printed.
EDIT: I'm using Codeigniter and this script is part of a controller, would that cause a problem with the require?
require 'http://localhost/facebook-php-sdk-6c82b3f/src/facebook.php';
echo "test";
-
public function signup()
{
require 'http://localhost/facebook-php-sdk-6c82b3f/src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user)
{
try
{
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user)
{
$logoutUrl = $facebook->getLogoutUrl();
}
else
{
$loginUrl = $facebook->getLoginUrl(array('scope' => 'email'));
redirect($loginUrl);
}
print_r($user_profile);
$this->load->model("user_model");
$privileges = 1;
$loginLocation = ip2long($_SERVER['REMOTE_ADDR']);
$active = 1;
$this->user_model->add_user($user_profile->id, $user_profile->name, $user_profile->email, $loginLocation, $privileges, $active);
}
I suggest you read the framework documentation. Adding a library to CodeIgniter is not a hard task. And Facebook library is no exception.
Here's a quick integration I've just come up with:
1.create a config file:application/config/facebook.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['appId'] = 'app_id';
$config['secret'] = 'app_secret';
2.place the sdk files in the libraries folder application/libraries/ and rename the facebook.php file to Facebook.php and replace the php tag with this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
3.in your controller load the config file and then load the Facebook library:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$config = $CI->config->item('facebook');
$this->load->library('facebook', $config);
}
public function index()
{
$user = $this->facebook->getUser();
if($user) {
try {
$user_info = $this->facebook->api('/me');
echo '<pre>'.htmlspecialchars(print_r($user_info, true)).'</pre>';
} catch(FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
} else {
echo "Login using Facebook";
}
}
}
Now in the constructor method, you have just initialized the Facebook library (sdk) and it can be accessed by using: $this->facebook.
Notes:
You can always use an existing library, just google it
A common practice is to extend the core Controller class and add the Facebook library initialization there.
Or create another library, extend the Facebook library, load the config file there and then autoload this new library.
After getting the $user, check session parameters with print_r($_SESSION). After that, check some variables by if(isset($_SESSION['some session var'])). If this condition is true, then navigate to your main page with header("location:main.php"); exit;
You can try using my extension http://github.com/deth4uall/Facebook-Ignited it is set up to work with Facebook. Just update the config file and it will allow you to do what you need to do, as well as some additional methods that I added myself.
do not know why, but it always runs this line:
echo "Login using Facebook";
This is the error message:
couldn't connect to host
But this worked.