I made session using zend authentication it works good but my problem is I want to change some property of it from another action in other controller my code is:
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {
$blogId = new model_blog request;
$auth->getIdentity()->user_current_blog = $blogId;
print "Current Blog";
print_r($auth->getIdentity()->user_current_blog);
}
in this action user_current_blog change but in other action it not works!!!
where I made a mistake???
$identity = $auth->getIdentity();
$identity->user_current_blog = $blogId;
$authStorage = $auth->getStorage();
$authStorage->write($identity);
http://framework.zend.com/manual/en/zend.auth.adapter.dbtable.html#zend.auth.adapter.dbtable.advanced.storing_result_row
Related
Hi good morning to everyone here, I have the following code which always returns me the value 'direccion' on the view, but I would like to retrieve all the values of the vase of data and put it to the meeting, as I can do that, they are thank you in advance.
Controller:
$authAdapter = new Zend_Auth_Adapter_DbTable();
$authAdapter
->setTableName('credential')
->setIdentityColumn('email')
->setCredentialColumn('password')
->setIdentityColumn('direccion');
$authAdapter
->setIdentity($form->getValue('email'))
->setCredential($form->getValue('password'))
->setIdentity('San marcos');
$select = $authAdapter->getDbSelect();
$select->where('status = "1"');
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
View:
if (Zend_Auth::getInstance()->hasIdentity()) {
$username = Zend_Auth::getInstance()->getIdentity();
$profile = 'Welcome, ' . var_dump($username) . ' logout';
} else {
You can write your own LoginStorage class for the current user on zend_auth.
In this way, when you authenticate the user, write you LoginStorage with your custom values on Zend_auth.
Something like this:
<?php
//LoginStorage custom class
class LoginStorage {
public function __construct ($direccion){
$this->direccion = $direccion;
}
public $direccion;
}
So when you are running auth:
...
if (Zend_Auth::getInstance()->authenticate($myAuthAdapter)->isValid()) {
//Instance of UNIQUE auth -> get session writer to record authentication rowset
Zend_Auth::getInstance()->getStorage()->write(new LoginStorage($myDireccionForThisUser));
...
Now, when you get Zend_Auth::getInstance()->getStorage()->read(), there you be a LoginStorage object ready for you.
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 working with cakephp.Recently I am facing problem in saving data in session.
I have created login page which will send value to controller/action. it will receives like this.
function ajaxCall() {
$this->autoRender = false;
$this->layout = 'ajax';
$arrData = $this->params['url'];
if(!empty($arrData)){
if($arrData['submit']=='Y'){
$userObj = new Api(); // create an instance of the user class
$userInfo = $userObj->login($arrData['email'],$arrData['password']); // call the api login user methods
$xml = simplexml_load_string($userInfo);
$userId = $xml->message->id;
if($userId != "0" && $userId != ""){
$this->setCurrentUserId($userId);
echo "success";
}
else{
echo "no";
}
}
}
}
public function setCurrentUserId($userId)
{
//Is session alive
//if not then redirect to session time out page
//session_start();
//session_register("");
if($userId == 419 || $userId == 423){
$userId1 = $this->Session->write('userId', $userId);
}else{
$userId1 = $this->Session->write('userId', $userId);
}
return $userId1;
}
my controller contain also these line to include helpers,component
public $components = array('Session');
public $helpers = array('Html','Session');
and in core.php file i set session as-
Configure::write('Session', array(
'defaults' => 'php', 'ini' => array('session.auto_start' => 1)
));
Please help me as i am unable to save userId in session
Thanks
On the internet there You can find CakePHP cookbook to create simple application with authentication and authorization: book.cakephp.org
Here You can find very simple example on how to create UsersController, User model and Views for login etc with login action using CakePHP's inbuilt Auth object - there is no need to write the whole login logic - Auth object will do most for You.
Hope You'll enjoy it!
I've been successfully accessing the LinkedIn API through my CodeIngiter application. I moved to a nearly identical server and implemented i18n library and it's stopped working.
After the user authenticates on LinkedIn it returns to the correct URL, but generates a series of errors beginning with Undefined index: oauth_verifier
After using an i18n library my URLs now have two letter language codes in the 1st segment like 'en' or 'br'.
EDIT: This is the Linkedin library I'm using.
I believe this is causing routing issues with the setting of $_REQUEST['oath_verifier']
Any help on this is greatly appreciated.
Excerpt from controller:
class LinkLogin extends MY_Controller {
function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load->model('profile_model');
$this->load->model('generic_model');
include_once (APPPATH.'libraries/Linkedin.php');
}
function index(){
}
function initiate(){
session_start();
$this->load->helper('url');
$config['linkedin_access'] = "***";
$config['linkedin_secret'] = "***";
$config['base_url'] = "http://www.youinapage.com/linklogin/initiate/";
if ($this->uri->segment(4) == 'profile') {
$config['callback_url'] = "http://www.youinapage.com/linklogin/get_profile_linkedin/";
}
if ($this->uri->segment(4) == 'resume') {
$config['callback_url'] = "http://www.youinapage.com/linklogin/get_resume_linkedin/";
}
function get_resume_linkedin() {
session_start();
$this->load->library('format');
$config['linkedin_access'] = "***";
$config['linkedin_secret'] = "***";
$config['base_url'] = "http://www.youinapage.com/linklogin/initiate/";
$config['callback_url'] = "http://www.youinapage.com/linklogin/get_resume_linkedin/";
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true;
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true;
if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
header("Location: " . $config['callback_url']);
exit;
}
else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier']; // ERROR: Undefined index: oauth_verifier
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);
}
Based on your comments and post, I'm guessing you are trying to use the same method twice in a row, so you get logged in. Seems weird but whatever.
The i18n you use will however change your routes to encorporate the languages so you should update your url's which you are setting inside your to controller to also use that language or a language.
In codeigniter, you should always try to set url's by the use of site_url(). This way you can easily port your application to other domainnames/locations. In this case, the localisation-library would also have changed the url's for you.
You should change all references to urls as follows:
$config['base_url'] = site_url("linklogin/initiate/");
$config['callback_url'] = site_url("linklogin/get_resume_linkedin/");
To use site_url(), you will need the URL Helper. You should include that helper before trying to use site_url(). But you already include it in your constructor, so no problems there.
You should also replace the use of header(...); exit; with redirect();. If you die after sending the header, codeigniter will not fully run and your logs will not be fully completed.
redirect($config['callback_url']); // Replaces: header($config['callback_url']);exit;
redirect('linklogin/get_resume_linkedin/'); // Alternative to above statement
I would also advice you to check out the manual to check out the build-in session class and the input class.
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.