i use Zend_Auth for one of my Projects, but so far haven't figured out how to set the Lifetime for the Session, or how to extend it (lets say it should run 5 minutes and should reset to that when the user makes an action), here is my Initialization code:
$authAdapter = new Zend_Auth_Adapter_DbTable($this->_model->pdo);
$authAdapter->setTableName('normal_folks')
->setIdentityColumn('username')
->setCredentialColumn('password');
$post = $this->_request->getPost();
$authAdapter->setIdentity($post['username'])
->setCredential($post['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if($result->isValid())
{
$userInfo = $authAdapter->getResultRowObject(null, 'password');
$authStorage = $auth->getStorage();
$authStorage->write($userInfo);
if(strlen($post['refferer']) > 1){
header("Location: ".$post['refferer']);
}elseif(strlen($this->_request->getParam('ref_action')) > 1){
Zend_Controller_Action::_forward($this->_request->getParam('ref_action'),"admin",null,null);
}else{
Zend_Controller_Action::_forward("index","admin",null,null);
}
}
Ant this how i check if the user is logged in:
if(Zend_Auth::getInstance()->hasIdentity()){
echo "Woho!";
}else{
die("invalid-identity");
}
Its probably right there in front of me but I just can't figure it out, help? Please? Pretty Please? :D
Authentication state is stored in the registered Auth Storage. By default this is Zend_Session. You can set an expiration time to the Zend_Auth namespace, e.g.
$namespace = new Zend_Session_Namespace('Zend_Auth');
$namespace->setExpirationSeconds(300);
You can also globally configure Zend_Session via
Zend_Session::setOptions(array(
'cookie_lifetime' => 300,
'gc_maxlifetime' => 300));
If you are using different namespace for zend_auth session you can do it like this:
$auth = Zend_Auth::getInstance ();
$auth->setStorage ( new Zend_Auth_Storage_Session ( 'user' ) );
$namespace = new Zend_Session_Namespace('user');
$namespace->setExpirationSeconds(7200); // 2 hours
Related
I am using adldap library to authenticate users against Active Directory. Below is the piece of code I use to authenticate
$username = $_POST['username'];
$password = $_POST['password'];
require_once '/adlap/adLDAP.php';
try {
$adldap = new adLDAP();
}
catch (adLDAPException $e) {
echo $e;
exit();
}
$authUser = $adldap->user()->authenticate($username, $password);
How should I setIdentity for the user?
In Login system where we store username and password we can setIdentity as mentioned below
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
protected function _getAuthAdapter() {
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('users')
->setIdentityColumn('username')
->setCredentialColumn('password')
->setCredentialTreatment('SHA1(CONCAT(?,salt))');
return $authAdapter;
}
I am not storing password in Database and checking it directly against Active Directory. So I couldn't use the above solution.
How shall I setIdentity of users so that I can check if user hasIdentity() like this
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()){
}
I referred the following Stackoverflow question
Get display name for Zend LDAP Authentication.
However I am not sure how we shall "get('LDAP_host')" Zend Registry and how should we set it before. Below is the line of code I'm confused with
'host' => Zend_Registry::get('LDAP_host'),
Can someone please help me?
Zend_Registry::get('LDAP_host') simply returnes the hostname of your LDAP-Server. Somewhere before that line of code you will find a line similar to Zend_Registry::set('LDAP_host', 'ldap.example.com') which sets ldap.example.com as LDAP-server.
getAuthAdapter() in your case returns an instance of Zend_Auth_Adapter_DbTable but you want an instance of Zend_Auth_Adapter_Ldap. So you will have to either call a different method/function getLdapAuthAdapter() or rewrite the current method.
public function getLdapAuthAdapter() {
return new Zend_Auth_Adapter_Ldap(array(
'host' => 'ldap.example.com',
'accountDomainName' => 'example.com',
'accountDomainNameShort' => 'EXAMPLE',
'accountCanonicalForm' => 3,
'username' => "CN=user1,DC=example,DC=com",
'password' => 'pass1',
'baseDn' => "DC=example,DC=com",
'bindRequiresDn' => true,
));
}
$adapter = $this->getLdapAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$result = $adapter->authenticate();
Hope that somehow helps.
In the login action I'm having the following code:
public function login($sEmail, $sEncryptedPassword, $bIsClear = true)
{
$manager = $this->getServiceLocator()->get('session_manager');
$manager->start();
Container::setDefaultManager($manager);
$this->auth = new AuthenticationService();
$this->auth->setStorage(new Session('FSP'));
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$this->authAdapter = new AuthAdapter(
$dbAdapter,
'fsp_user',
'email',
'password'
);
$this->authAdapter
->setIdentity($sEmail)
->setCredential($sEncryptedPassword);
$authAuthenticate = $this->auth->authenticate($this->authAdapter);
if ($authAuthenticate->isValid()) {
$user = $this->authAdapter->getResultRowObject();
$storage = $this->auth->getStorage();
$storage->write(
array(
'email' => $user->email,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'id' => $user->id
)
);
}
I have two problems with this code:
1) I'm saving the session in the database, and the session SaveHandler is configured in a service manager. I don't know if once I'm using Zend\Authenticate I should use the session manager too. In the documentation is saying that
"Unless specified otherwise, Zend\Authentication\AuthenticationService
uses a storage class named Zend\Authentication\Storage\Session, which,
in turn, uses Zend\Session."
So my first question is: can I configure the sessionHandler using just Zend\Authenticate or do I have to use the session manager?
2)I can't figured out how session storage is working in ZF. After login, the session data is not persisted in the DB. If I'm doing some debugging I get the following data:
$session = new Container("FSP");
//this returns the session data
var_dump($session->getIterator());
//this returns empty
var_dump($this->auth->getStorage());
//this returns null, but I do have a FSP named cookie with an Id, showing in Chrome's developer tool
$cookie = $this->getServiceLocator()->get('request')->getHeaders()->get('cookie');
$sessionId = $cookie->FSP;
var_dump($sessionId);
However, if I'm doing a refresh on the login (the login action is run again) the data from the previous session is wrote in the DB and not the data from the current one.
So the second question is, why the session data is not persisted in the database at login and at what step in the session instantiation process is the cookie with the session ID created?
I am using Elliot Haughin's twitter oauth library for codeigniter. It can be found here :
https://github.com/elliothaughin/codeigniter-twitter
I have the following code which authenticates a user with twitter and stores session details.
public function login() {
$this->tweet->set_callback(site_url(''));
$this->tweet->login();
$tokens = $this->tweet->get_tokens();
$user = $this->tweet->call('get', 'account/verify_credentials');
$u = $user->screen_name ;
$data = array(
'user' => $u,
'logged_in' => true
);
$this->session->set_userdata($data) ;
}
This is weird but the logged_in variable is saved whereas the user is not. I am not sure where i am going wrong.
have you include SESSION library or autoload it.
Update:
http://codeigniter.com/user_guide/libraries/sessions.html
I would like to dynamically set the session expiration time in Codeigniter. I'm autoload the session class. I have a view that contains checkbox for users to click (remember me). Right now if they click the check box or not the expiration time stays the same :/
// Config.php
$config['sess_expiration'] = 7200;
// Controller
if ($this->input->post('remember_me') == 'TRUE')
{
$this->session->remember_me();
}
$newdata = array(
'failed_login' => 0,
'user_name' => $this->input->post('user_name'),
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
// MY_Session.php
class MY_Session extends CI_Session {
function remember_me()
{
$this->sess_expiration = 172800;
}
}
If you need to implement "Remember me" feature - then you've started it in a wrong way.
You need to create one more database table with fields user_id | token.
Then, after user has been logged in (with "remember me" checkbox checked on) - generate random token and insert a new row with current user_id and that token. Also - set remember cookie with the same token value.
Now, if user enters your site, not authenticated and has some token - you can always find that token and authenticate user (each token is unique and strognly related to specific user_id).
Here is my solution I've been playing with.
You can edit the function inside domain.com/system/libraries/Session.php
function _set_cookie($cookie_data = NULL)
Comment out
// $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();
Then Add
if(isset($this->userdata['rememberme'])){
// If they want to stay connected
if( $this->userdata['rememberme'] == 1) {
$expire = 0;
} else {
$expire = time() + $this->sess_expiration;
}
} else {
$expire = time() + $this->sess_expiration;
}
Please let me know if this helps in anyway or modify my code to help me out. Thank you.
$data = array(
'username' => $this->input->post('username'),
'ADMIN_is_logged_in' => true
);
$this->session->sess_expiration = '14400';// expires in 4 hours
$this->session->set_userdata($data);// set session
In my entry controller I set:
This works:
$authadapter = new Test_Auth_Adapter_DbTable($db);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authadapter);
$data = $authadapter->getResultRowObject(null, 'password');
$auth->getStorage()->write($data);
$this->_redirector->gotoUrl('/main');
This does not:
$authadapter = new Test_Auth_Adapter_DbTable($db);
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('Test_User')); //the only difference
$result = $auth->authenticate($authadapter);
$data = $authadapter->getResultRowObject(null, 'password');
$auth->getStorage()->write($data);
$this->_redirector->gotoUrl('/main');
I can see it set in the $_SESSION var with all of the correct data when I use a debugger but after the data is set and I redirect to the desired destination the $_SESSION var is no longer set thus I cannot access things!
The page being redirected to checks auth with:
$this->auth = Zend_Auth::getInstance();
if (!$this->auth->hasIdentity()) {
$this->_redirector->gotoUrl('/entry');
}
Why doesn't this work?
Try this:
$this->auth = Zend_Auth::getInstance();
$this->auth->setStorage(new Zend_Auth_Storage_Session('Test_User'));
if (!$this->auth->hasIdentity()) {
$this->_redirector->gotoUrl('/entry');
}
the problem is if you don't set a storage class, it will default to using Zend_Auth_Storage_Session with the Zend_Auth namespace. And because your session data isn't in that namespace, Zend_Auth doesn't see it and behaves as if the user is not logged in.
Depending on how your application is structured (and how big a part of it the auth is), you might want to do this in a bootstrap method instead so you only have to do it once:
protected function _initAuth()
{
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('Test_User'));
return $auth;
}