Get all session data in zend 1.12 - php

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.

Related

codeigniter session not working in model

I am having issuing with session such after setting the session in my controller method, I be able to access in view but I cannot be able to access in model.
Here is the code:
public function get_username_ticket()
{
$user = $this->db->dbprefix('users');
$kq=$this->session->t_bys;
$sql = "SELECT $user.*
FROM $user
WHERE $user.deleted=0 AND $user.id = $kq";
return $this->db->query($sql)->row();
}
You should retrieve by:
$this->session->userdata('sessionVariable');

PHP - Accessing my user class from the whole app

I am currently writing a login script because I am trying to learn PDO using OOP. I have a index.php page which only contain a login form. Then I have a User class, it looks like this:
<?php
include_once('database.php');
session_start();
class User{
public $id;
public $username;
public $password;
public $firstname;
public $lastname;
public function Login($username, $password) {
$db = new Database;
$db = $db->dbConnect();
$query = "SELECT * FROM users WHERE username = ? AND password = ?";
$statement = $db->prepare($query);
$statement->bindParam(1, $username);
$statement->bindParam(2, $password);
$statement->execute();
$rows = $statement->rowCount();
$data = $statement->fetchAll();
if( $rows == 1 ) {
$this->id = $data[0]['id'];
$this->username = $data[0]['username'];
$this->password = $data[0]['password'];
$this->firstname = $data[0]['firstname'];
$this->lastname = $data[0]['lastname'];
$_SESSION['SESSID'] = uniqid('', true);
header("location: dashboard.php");
}
}
}
?>
When the user is signed-in he/she goes to dashboard.php. I want to access the current User class from there, so I can use echo $user->username from there. But in dashboard.php, I have to declare the User class as new, so it doesn't keep all the variables.
Do you have any ideas on how i can access the User class variables in Dashboard.php which was declared in the Login-function?
Sorry for the bad explanation, but I hope you understand. Thank you in advance!
First off put your user class definition in another file and load it in like you do your database.php. In there you want only your class definition none of the session start business... <?php class User {....} ?> (the closing ?> is optionial).
so what you have now on your pages that need access to the user object is
<?php
include_once('database.php');
include_once('user.php');
session_start();
Then after a user has successfully logged you tuck the user in the session.
$_SESSION["user"] = $user;
Then when you want to get at it just say
$user = $_SESSION["user"];
echo $user->username;
What you could do is, put your user object into the session:
$obj = new Object();
$_SESSION['obj'] = serialize($obj);
$obj = unserialize($_SESSION['obj']);
or you could create a singleton, check out this link:
Creating the Singleton design pattern in PHP5
You have 2 options:
a) You store all the login info in a session.
b) You only store the user ID and some sort of identifier that the user has / is logged in, and create another method that will load the information from the database each time you load the page (bad idea really)
For example, you could add the following methods to your class in order to implement the above mentioned functionality and some more:
function createUserSession(array $userData) {
// Create / save session data
}
function readActiveUserSession() {
// Read current user information
}
function destroyActiveUserSession() {
// Call to destroy user session and sign out
}
Of course, you will have to add the appropriate code to the methods.

How to store and change Zend_Auth session ID?

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);

How to set the timeout while using Zend_auth in Zend framework

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.

change session property in zend

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

Categories