In codeigniter I am trying to include a Logger library and in the below code I need to check whether a user has logged in or not and if so, find his user id.
<?php
class Logger {
private $CI;
public function __construct() {
$this->CI =& get_instance();
}
public function request_logger() {
$uri = $this->CI->uri->uri_string();
$ip="";
$userID="";
//$ip = ip2long($_SERVER['REMOTE_ADDR']);
$ip = $_SERVER['REMOTE_ADDR'];
$params = trim(print_r($this->CI->input->post(), TRUE));
log_message('info', '==============');
log_message('info', 'URI: ' . $uri);
log_message('info', '--------------');
log_message('info', 'PARAMS:' . $params);
log_message('info', 'IP:' . $ip);
log_message('info', '==============');
//if ($this->ion_auth->logged_in())
if(isset($_POST['user_id']))
{
log_message('info', '<== Inside loggedin loop ==>');
$userID=$this->input->post('user_id');
}
log_message('info', 'USERID' . $userID);
}
}
?>
you can use codeigniter Session class.
you can create new session with user data,like this
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
and you can access this data via,
$userId = $this->session->userdata('userid');
Visit this User GuideCodeignitor Session
Related
I'm preparing joomla plugin/api to connect website with mobileapp. I cannot use cookies, I need to do this only by request.
So to login I can go to http://example.net/?user=aaa&pass=bbb and it creates session and returns token.
To go to user profile I can go to: http://example.net/profile?token=8asd7g... and if token matches session id in database then it sets session cookie (on php side) in Joomla framework
Which event should I use to:
check token and maintain session
check login, user and login/create session
check login, user and register user
The second question is how:
is it enought to set $session->set('userid',$user->id); ?
I create fake $response and $app->triggerEvent('onUserLogin', array((array) $response, array('action' => 'core.login.admin'))); is it enough?
If somebody need here is almost fnished solution. It allows users to login via user and pass taken form url or request header, it allows access to restricted parts of website based on token i url not cookie, it allows to pass params from header to JInput->get.
<?php
/**
* #package API
* #subpackage System.sittetokenlogin
*
*/
defined('_JEXEC') or die('Unauthorized Access');
jimport('joomla.filesystem.file');
class PlgSystemSittetokenlogin extends JPlugin
{
public function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
}
public function onUserAuthenticate()
{
//die('onUserAuthenticate');
}
public function onUserLogin()
{//wykonuje się
//die('onUserLogin');
}
public function onUserLogout()
{//wykonuje się
//die('onUserLogout');
}
public function onAfterInitialise()
{
//wstępne ustawienie obiektów
$app = JFactory::getApplication();
if ($app->isClient('administrator')) return;
$input = JFactory::getApplication()->input;
$headers = getallheaders ();
$db = JFactory::getDbo();
//pobranie danych z rządania
$loginToken = $headers['logintoken']; if(!$loginToken) $loginToken = $input->get->get('logintoken', '', 'STRING');
$suser = $headers['suser']; if(!$suser) $suser = $input->get->get('suser', '', 'STRING');
$spass = $headers['spass']; if(!$spass) $spass = $input->get->get('spass', '', 'STRING');
if ($loginToken) // logowanie na bazie tokenu
{
JPluginHelper::importPlugin('user');
$sesja = $db->setQuery('SELECT * FROM `#__session` WHERE `session_id`='.$db->quote($loginToken).' LIMIT 1')->loadObject();
$user = $db->setQuery('SELECT * FROM `#__users` WHERE `id`='.$db->quote($sesja->userid).' LIMIT 1')->loadObject();
$response = new JAuthenticationResponse();
$response->type = 'Joomla';
$response->email = $user->email;
$response->fullname = $user->name;
$response->username = $user->username;
$response->password = '';
$response->status = JAuthentication::STATUS_SUCCESS;
$response->error_message = null;
//print_r($response);
$app->triggerEvent('onUserLogin', array((array) $response, array('action' => 'core.login.site')));
//$testuser = JFactory::getUser(); die(print_r($testuser,true));
}
elseif ($suser && $spass) //logowanie na bazie loginu i hasła
{
$error = $app->login([
'username' => $suser,
'password' => $spass,
]);
$user = JFactory::getUser();
if ($user->id>0) die(JFactory::getSession()->getId());
else die('login_error');
}
//przekazywanie parametrów
$option = $headers['option']; $input->set('option',$option);
$view = $headers['view']; $input->set('view',$view);
$id = $headers['id']; $input->set('id',$id);
$catid = $headers['catid']; $input->set('catid',$catid);
$Itemid = $headers['Itemid']; $input->set('Itemid',$Itemid);
$tmpl = $headers['tmpl']; $input->set('tmpl',$tmpl);
//$input->set('option','com_guru');
//$input->set('view','gurupcategs');
}
}
I am trying to resolve a bug on a client's application, but i can't log in.
So i go to application.dev/metier/login, with application.dev as my virtual host, metier my admin route page and login the page to log in the application.
I complete the form, click on connect, i am getting logged in, redirected to the index page (application.dev/metier/index) but immediately after the redirection i am kicked out to the login page. The url is still application.dev/metier/index, but the i am seeing the login page as i was not authenticated.
I checked session, cleared after redirection.
It is like it's working fine, I am known from database, inserted in session, known as admin, but kicked out no matter what i do. No error, no log. Zend do not enter indexAction().
I can't go to another page due to the routing, and if i try to put my informations in session before access login page, i have an error "too many redirections" (i am in authenticated so go to index, but no i am kicked out, but i am authenticated, but i am kicked out...).
I am on Zend framework 1.12.18, Windows 10, with laragon (Kaspersky as antivirus). I also tried with wamp, and on an Ubuntu VM with xampp, same problem. I tried on another computer, same problem.
It works on the developer who gave me the source code. He gave me the original code and the code with his modification (of application.ini mainly), both give me the "error".
Controller:
public function loginAction() {
try {
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$this->redirect('/metier/index/');
return;
}else{
Zend_Session::regenerateId();
}
$loginForm = new Application_Form_Admin_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($loginForm->isValid($request->getPost())) {
if ($this->_process($loginForm->getValues())) {
// We're authenticated! Redirect to the home page
$this->_helper->redirector('index', 'index');
}
} else {
Log::debug('User sent invalid data.', __FILE__, __LINE__);
Log::debug($request->getPost(), __FILE__, __LINE__);
Log::debug('Errors: ', __FILE__, __LINE__);
Log::debug($loginForm->getErrors(), __FILE__, __LINE__);
$this->view->error = Zend_Registry::get('Language')->errors->login->error;
}
}
} catch (Exception $e) {
//$this->view->error = 'Wrong username and/or password';
$this->redirect('/metier/login/');
return;
}
$this->view->form = $loginForm;
}
protected function _process($values) {
if (!trim($values['username']) || !trim($values['password'])) {
$this->view->error = Zend_Registry::get('Language')->errors->login->empty;
return false;
}
// Get our authentication adapter and check credentials
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
Log::debug('Authentication returned result code: ' . $result->getCode(), __FILE__, __LINE__);
switch ($result->getCode()) {
case Zend_Auth_Result::SUCCESS:
$mdlMetierDep = new Application_Model_DbTable_MetierDepartement();
$user = $adapter->getResultRowObject();
$metDepObj = $mdlMetierDep->fetchRow(array('id_metier = ?' => $user->id_metier, 'id_departement = ?' => $user->id_departement));
if (!$metDepObj) {
$this->view->error = Zend_Registry::get('Language')->errors->login->error;
return $this->_redirect('/metier/login/');
}
$user->Role = Acl::ROLE_ADMIN_METIER;
$user->id_metier_departement = $metDepObj->getIdMetierDepartement();
$user->metier = $metDepObj->findMetier()->toArray();
$user->department = $metDepObj->findDepartement()->toArray();
// to help thwart session fixation/hijacking
// store user object in the session
$authStorage = $auth->getStorage();
$authStorage->write($user);
$this->_redirect('/metier/index/');
break;
case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
default:
$this->view->error = Zend_Registry::get('Language')->errors->login->error;
break;
}
if ($result->isValid()) {
$user = $adapter->getResultRowObject();
//$auth->getStorage()->write($user);
return true;
}
return false;
}
The login and reporting actions (just for informations, zend do not goes in it)
public function indexAction() {
$this->go('reporting');
}
public function reportingAction() {
$this->loadJs(('/scripts/metier/general.js'));
$this->loadCss(('/styles/metier/DataTable.css'));
$this->loadJs(('/scripts/jquery.dataTables.js'));
$this->loadJs(('/scripts/metier/data-table.js'));
}
Init function :
public function init() {
/* Initialize action controller here */
parent::init();
$this->loadCss(('/styles/web/tables2.css'));
$this->loadJs(('/scripts/web/tinyMceConfigs.js'));
$this->language = Zend_Registry::get('Language');
$this->view->language = $this->language;
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$this->storage = $auth->getStorage()->read();
$this->_getLogo();
} else {
$this->view->noLogo = true;
}
//enum field for indicateurs
$this->view->frequence = array('M', 'T', 'S', 'A');
$this->view->sens = array(
'A' => 'Croissant',
'D' => 'Décroissant',
);
$this->view->formulaType = array(
0 => 'rule',
1 => 'min',
2 => 'max',
3 => 'avg');
$this->view->FormulaOperand = array(
0 => '+',
1 => '-',
2 => '/',
3 => '*');
$this->view->tableauTypes = array(Constants::TABLEAU_STRUCTURE_DETAILLE, Constants::TABLEAU_STRUCTURE_COMPTEURS, Constants::TABLEAU_STRUCTURE_GRAPH);
$this->view->operands = array('+', '-', '*', '/');
$this->view->pageTypes = array(
Constants::PAGE_GARDE,
Constants::PAGE_CONTENU,
Constants::PAGE_TABLEAUX,
);
$this->view->HautEtBasTypes = array(
Constants::HEADER => Constants::HEADER,
Constants::FOOTER => Constants::FOOTER,
);
$this->loadCss('styles/forms.css', 'form_css');
$this->view->config = Zend_Registry::get('AppConfig');
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('add-metier', 'json')
->setAutoJsonSerialization(true)
->initContext();
$this->_loggedInUser = Zend_Auth::getInstance()->getIdentity();
ini_set('display_errors', 1);
error_reporting(E_ALL);
}
Classname :
class MetierController extends Reporting_Controller {...}
After debugging, it goes to $this->_redirect('/metier/index') and then kick me out
What could be the problem ?
I am working on a simple anonymous login system and I have a Session class which looks like this:
<?php
class Session
{
private static $cookieLifeSpanInDays;
public function __construct()
{
self::$cookieLifeSpanInDays = 1825;
}
public static function loginUser()
{
if (!Session::isLoggedIn())
{
// Login User
$session_id = Session::newSessionId();
$name = Session::newUserName($session_id);
if (empty($name))
throw new Exception('Failed to generate a unique user name. Try again later.');
DB::insert('users', array(
'name' => $name,
'session_id' => $session_id,
'last_login' => time()
));
setcookie("sessionId", $session_id, time() + (self::$cookieLifeSpanInDays * 86400), '/', $_SERVER['HTTP_HOST']);
$_SESSION['isLoggedIn'] = true;
var_dump(self::$cookieLifeSpanInDays);
var_dump($_COOKIE);
exit();
}
// Defaults
return true;
}
}
When I call the class like this: Session::loginUser();
The var_dumps() in the loginUser function looks like this:
So, my login function is broken (no cookie is getting set) because the static property on class self::$cookieLifeSpanInDays is null. What am I doing wrong here?
I've fixed it:
<?php
class Session
{
private static $cookieLifeSpanInDays = 1825;
public static function loginUser()
{
if (!Session::isLoggedIn())
{
// Login User
$session_id = Session::newSessionId();
$name = Session::newUserName($session_id);
if (empty($name))
throw new Exception('Failed to generate a unique user name. Try again later.');
DB::insert('users', array(
'name' => $name,
'session_id' => $session_id,
'last_login' => time()
));
setcookie("sessionId", $session_id, time() + (self::$cookieLifeSpanInDays * 86400));
$_SESSION['isLoggedIn'] = true;
var_dump(self::$cookieLifeSpanInDays);
var_dump($_COOKIE);
exit();
}
// Defaults
return true;
}
}
I am using codeigniter and want to fetch linkedin data but it not works.. it getting no error but i could not fetch data also
i am using this code defined in following url:
Linkedin php api not setting access token in codeigniter
and codes are
create library:
defined('BASEPATH') OR exit('No direct script access allowed');
class Linkedin {
function __construct(){
}
public function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
exit;
}
public function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
public function fetch($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'],
'format' => 'json',
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$context = stream_context_create(
array('http' =>
array('method' => $method,
)
)
);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response);
}
}
Put all your Constants stuff in confin/constants.php
define('API_KEY', 'Put Yoour API_KEY here');
define('API_SECRET', 'Put Yoour API_SECRET here');
define('REDIRECT_URI', 'Put Yoour REDIRECT_URI here');
define('SCOPE', 'r_fullprofile r_emailaddress rw_nus r_contactinfo r_network');
and finally make my controller
class Profile extends CI_Controller {
function __construct() {
parent:: __construct();
$this->load->library('linkedin'); // load library
session_name('linkedin');
session_start();
}
// linkedin login script
function profile() {
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
// load any error view here
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($_SESSION['state'] == $_GET['state']) {
// Get token so you can make API calls
$this->linkedin->getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
exit;
}
} else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
$this->linkedin->getAuthorizationCode();
}
}
// define the array of profile fields
$profile_fileds = array(
'id',
'firstName',
'maiden-name',
'lastName',
'picture-url',
'email-address',
'location:(country:(code))',
'industry',
'summary',
'specialties',
'interests',
'public-profile-url',
'last-modified-timestamp',
'num-recommenders',
'date-of-birth',
);
$profileData = $this->linkedin->fetch('GET', '/v1/people/~:(' . implode(',', $profile_fileds) . ')');
if ($profileData) {
$this->session->set_userdata("profile_session",$profileData);
} else {
// linked return an empty array of profile data
}
}
}
When i am running this controller then linkedin api works a modal window appears with my app name ..but after login
When i trying to print this session it does not apppears... dont know this code is working or not.. please help
This should work:
LinkedIn Class:
class Linkedin extends CI_Controller {
function __construct(){
parent:: __construct();
$this->load->library('session');
}
public function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$this->session->set_userdata('state',$params['state']);
// Redirect user to authenticate
header("Location: $url");
exit;
}
public function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$ses_params = array('access_token' => $token->access_token,
'expires_in' => $token->expires_in,
'expires_at' => time() + $_SESSION['expires_in']);
$this->session->set_userdata($ses_params);
return true;
}
public function fetch($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'],
'format' => 'json',
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$context = stream_context_create(
array('http' =>
array('method' => $method,
)
)
);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response);
}
}
Profile Controller:
class Profile extends CI_Controller {
function __construct() {
parent:: __construct();
$this->load->library('linkedin'); // load library
$this->load->library('session');
}
// linkedin login script
function profile() {
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
// load any error view here
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($this->session->userdata('state'); == $_GET['state']) {
// Get token so you can make API calls
$this->linkedin->getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
exit;
}
} else {
if ((empty($this->session->userdata('expires_at'))) || (time() > $this->session->userdata('expires_at'))) {
// Token has expired, clear the state
$this->session->sess_destroy();
}
if (empty($this->session->userdata('access_token'))) {
// Start authorization process
$this->linkedin->getAuthorizationCode();
}
}
// define the array of profile fields
$profile_fileds = array(
'id',
'firstName',
'maiden-name',
'lastName',
'picture-url',
'email-address',
'location:(country:(code))',
'industry',
'summary',
'specialties',
'interests',
'public-profile-url',
'last-modified-timestamp',
'num-recommenders',
'date-of-birth',
);
$profileData = $this->linkedin->fetch('GET', '/v1/people/~:(' . implode(',', $profile_fileds) . ')');
if ($profileData) {
$this->session->set_userdata("profile_session",$profileData);
} else {
// linked return an empty array of profile data
}
}
}
I am implementing the facebook connect and its working partially well for me. Its successfully loging the user when some login in with facebook. Here is the link for login http://beta-demo.info/party/users/loginByFacebook but after login when i am trying to fetch user detail from facebook its now displaying anything.
Here is the code of of Fb_Connect.php This file is placed in Libraries folder
<?php
include(APPPATH.'libraries/facebook/facebook.php');
class Fb_connect extends Facebook{
//declare public variables
public $user = NULL;
public $user_id = FALSE;
public $fb = FALSE;
public $fbSession = FALSE;
public $appkey = 0;
//constructor method.
public function __construct()
{
$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$config = $CI->config->item('facebook');
parent::__construct($config);
$this->user_id = $this->getUser(); // New code
$me = null;
if ($this->user_id) {
try {
$me = $this->api('/me');
$this->user = $me;
} catch (FacebookApiException $e) {
error_log($e);
}
}
}
} // end class
and this is loging function
function loginByFacebook(){
$this->load->library('fb_connect');
$param['redirect_uri']=base_url();
redirect($this->fb_connect->getLoginUrl($param));
}
and this is the info function where i am trying to fetch the value.
function facebook() {
print('<pre>');
print_r($this->fb_connect);
if (!$this->fb_connect->user_id) {
echo 'No working ';
//Handle not logged in,
} else {
echo $fb_uid = $this->fb_connect->user_id;
echo $fb_usr = $this->fb_connect->user;
//Hanlde user logged in, you can update your session with the available data
//print_r($fb_usr) will help to see what is returned
}
}
Url of the info page http://beta-demo.info/party/users/facebook
I dont have much of idea about facebook connect API.so please help me
The only thing I can see you are missing are the fields when calling '/me'. This is the function I used to get the info from facebook connect. Working example: http://www.paravegetarianos.com
function facebookConnect()
{
$this->config->load('facebook', TRUE);
$config = array(
'appId' => $this->config->item('facebook_api_id', 'facebook'),
'secret' => $this->config->item('facebook_secret_key', 'facebook'),
'fileUpload' => true,
);
$this->load->library('Facebook', $config);
$user = $this->facebook->getUser();
$profile = null;
if($user):
try {
$profile = $this->facebook->api('/me?fields=id,username,email'); //<--- you are missing the fields
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
endif;
if($profile != null):
$profile['uid'] = $user;
$data = $profile;
var_dump($data); //<--------- Information
die();
endif;
}
This is the working code for me
<?php
function loginByFacebook()
{
$this->load->library('fb_connect');
$param = array(
'scope' =>'email,user_location,user_birthday,offline_access', 'redirect_uri' => base_url()
);
redirect($this->fb_connect->getLoginUrl($param));
}
function facebook()
{
if (!$this->fb_connect->user_id) {
} else {
$fb_uid = $this->fb_connect->user_id;
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];
}
?>