Zend_Auth Identity not persisting between controllers - zend-framework

Fairly new to Zend Framework 1.11 with Doctrine 2.
I have successfully created a login etc using Doctrine.
My current problem though is that the Zend_Auth instance works fine when I stay within the controller that the log in is within.
If I try determine the state of Zend_Auth::getInstance->HasIdentity() in any other controller it returns blank.
If I then go back to any page residing within the controller containing the login/authentication hasIdentity works fine.
I have even tried writing to the storage but this provides no joy.
My auth code is as follows which is the action called after clicking Login (Within MembersareaController)
public function authAction()
{
$this->_helper->viewRenderer->setNoRender(true);
$loginForm = new Application_Model_Login();
if($this->getRequest()->isPost()){
$usr = "";
$pwd = "";
$KeepLoggedIn = false;
$message = "";
$usr = $this->_getParam('username');
$pwd = $this->_getParam('password');
$pwdMd5 = md5($pwd);
if($usr !== "" && $pwd !== ""){
$GDSAdaptor = new ZC_Auth_Adapter($usr, $pwdMd5);
$result = \Zend_Auth::getInstance()->authenticate($GDSAdaptor);
if(\Zend_Auth::getInstance()->hasIdentity()){
$this->flashMessenger->addMessage(LOGIN_SUCCESS);
$this->_redirect('/membersarea/index');
}else{
$this->flashMessenger->addMessage(LOGIN_INVALID);
}
}else{
$this->flashMessenger->addMessage(LOGIN_MISSING_FORMVAL);
$this->_redirect('/membersarea/login');
}
}
Trying to seeing a person is logged in on the IndexController with the following code produces no results. hasIdentity returns a blank value.
public function indexAction()
{
if(Zend_Auth::getInstance()->hasIdentity())
{
$msg = "hasIdentity: YES";
}else{
$msg = "hasIdentity: NO";
}
$this->view->msg = $msg;
}

Zend_Session::rememberMe(); in the bootstrap solved this issue

Related

Fatal error: require_once(): Failed opening required ... Novice programmer, appreciate any guidance

I'm a novice in server-side programming so any advice is appreciated.
I have some PHP files uploaded on a virtual server (000webhost.com) and I'm having trouble with locating a file I'm requiring in another PHP file. The register.php is attempting to "require_once" the update_user_info.php
Here's the code for register.php (Which I've taken from a tutorial and adjusted it with my variables):
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'../update_user_info.php');
$db = new update_user_info();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST ['password']) && isset($_POST['branch']) && isset($_POST['gender'])) {
// receiving the post params
$username = $_POST['username'];
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$branch = $_POST['branch'];
$gender = $_POST['gender'];
// check if user is already existed with the same email
if ($db->CheckExistingUser($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->StoreUserInfo($username, $name, $email, $password, $branch, $gender);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["user"]["username"] = $user["username"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["branch"] = $user["branch"];
$response["user"]["gender"] = $user["gender"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter (username, name, email or password) is missing!";
echo json_encode($response);
}
?>
And here's a screenshot of the error that's occurring when attempting to visit the link containing the register.php:
Screenshot of the error
What I've tried so far:
1- tried to use require_once __DIR__."/../filename.php"; and lots more of the same, basically tinkering the statement with different language constructs and constants.
2-Read tutorials on the correct way to use require once but their cases is almost always very different. Either they are using WAMP/XAMPP -meaning they have a local path not a virtual one- So no luck there.
3- tried to change .htaccess file, as someone said in a post that it solved his problem.
4- I'm certain that both files are uploaded to the same directory. Yet it says "No such file".
Does anyone have an idea of where the error could be stemming from? Thanks in advance!

Zend redirector not working properly

I have just uploaded my app into a shared hosting environment and it does not seem to be working properly.
I have 2 plugins registered. One checks for session timeout and the other check for session is created after logged in.
the pproblem is that after the second plugin(security.php) kicks in it suppose to redirect the user to the login screen because session has not been created yet. Upon redirection the page displays :The page isn't redirecting properly.
I am not sure what is happenning since everything works fine locally.Below are my two files i mentioned here.
Security.php(here you can see that i have tried couple options, but nothing worked).
class Plugins_security extends Zend_Controller_Plugin_Abstract
{
public function preDispatch (Zend_Controller_Request_Abstract $request)
{
$auth = Zend_Auth::getInstance();
$moduleName = $request->getModuleName();
//$vc = new Zend_Application_Resource_View();
if ($request->getModuleName() != "auth")
{
$auth = Zend_Auth::getInstance();
if (! $auth->hasIdentity())
{
//$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper(
//'redirector');
$flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
$flashMessenger->addMessage(array('message' => 'Sua sessão expirou. Favor logar novamente', 'status' => 'info'));
//$this->_redirect('/auth/login/',array(‘code’ => 301));
$r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$r->gotoSimple("index", "login", "auth");
//header('Location: /auth/login/');
//return;
}
}
}
}
timeout.php
class Plugins_timeout extends Zend_Controller_Plugin_Abstract
{
protected $_auth = null;
protected $_acl = null;
protected $_flashMessenger = null;
protected static $_ZEND_SESSION_NAMESPACE_EXPIRATION_SECONDS= 900;
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
Zend_Session::start();
$moduleName = parent::getRequest()->getModuleName();
if($moduleName !='auth'){
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > self::$_ZEND_SESSION_NAMESPACE_EXPIRATION_SECONDS)) {
// last request was more than 30 minates ago
session_destroy(); // destroy session data in storage
session_unset(); // unset $_SESSION variable for the runtime
$front = Zend_Controller_Front::getInstance();
$_baseUrl=$front->getBaseUrl();
Zend_Debug::dump(time() - $_SESSION['LAST_ACTIVITY']);
header("Location:$_baseUrl/auth/login/index/timeout/1" );
}else{
$_SESSION['LAST_ACTIVITY']= time();
}
}
}
}
Any help is appreciated. I need to deploy this app ASAP.
thank you.
I think you want:
$r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$r->gotoSimpleAndExit("index", "login", "auth"); // Note the 'AndExit' suffix.
$r->gotoXXX() just sets the correct header and codes in the $response object, but allows the rest of the dispatch to continue. In contrast, the AndExit part immediately sends the response to the client and exits.
[Not clear why AndExit would not be required in your local environment, though...]

Symfony 2.1 Autologin after facebook login

I'm creating an intranet, therefore all users have account automatically created for them. They then go to a url to create their password. All that works great. I'm now trying to allow them to "attach" their Facebook account to their user account. This is where my troubles have started...
I've successfully gotten the user to authenticate properly after a facebook login with this
method in SecurityController
public function loginCheckFacebookAction()
{
$request = $this->getRequest();
$session = $request->getSession();
$response = new Response();
$sessionUser = $this->getUser();
$facebook = $this->get('facebook');
$fbUser = $facebook->getUser(); // facebook id
if ($fbUser) {
try {
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository("IntranetBundle:User");
$user = $repo->findUserByFBID($fbUser);
if($user){
$targetPath = $session->get("_target_path");
$firewall = "secured_area";
$roles = $user->getRoles();
$rolesArray = array();
foreach($roles as $role):
$rolesArray[] = $role->getRole();
endforeach;
$token = new UsernamePasswordToken($user, $user->getPassword(), $firewall, $rolesArray);
$event = new InteractiveLoginEvent($this->getRequest(), $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
$this->get('security.context')->setToken($token);
/*
If I uncomment out either of the following redirects
the redirect happens but the user is not authenticated properly
If I comment them out I'm just rendering my error template. The user
however, is authenticated properly.
*/
if(isset($targetPath)){
//return $this->redirect($targetPath);
} else {
//return $this->redirect($this->generateUrl("ssla_intranet_homepage"));
}
}
} catch (FacebookApiException $e) {
$user = null;
}
// I just render this template to be able to view debug bar.
//User is authenticated properly.
$pageParameters = $this->getPageParameters();
$pageParameters["page"] = "error";
$pageParameters["error"] = array();
$pageParameters["error"]["message"] = "Something went wrong with authentication";
return $this->render('IntranetBundle:Error:index.html.twig', $pageParameters);
}
Do I need to register a listener for all interactive_login events that then handles all post-login redirection rather than trying to redirect within the same method?
First project using Symfony, and this is killing me. Any thoughts?
By the way, I've looked into the FOSFacebookBundle, but wanted to be able to authenticate with a number of different methods, including doctrine, gmail, facebook, and twitter.

Zend authenticate returns white screen

This is the most frustrating ever. It is nearly impossible to find errors when all you get is a white screen!!!
This code is used on other projects and it works fine there so syntactically, it is correct. But SOMETHING must be wrong in the configuration...
Here is the code:
protected function _process($values)
{
// 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);
if ($result->isValid()) {
$user = $adapter->getResultRowObject();
$auth->getStorage()->write($user);
return true;
}
return false;
}
protected function _getAuthAdapter()
{
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('Users')
->setIdentityColumn('username')
->setCredentialColumn('password')
->setCredentialTreatment('md5(?)');
return $authAdapter;
}
This is in my auth controller and gets called after I set up the adapter, etc. If I put a die("foo"); right before the $result line, I see it. If I put it right after the $result line, I get a WSOD and the system stops. I know there is not enough here for anyone to debug my code but I was hoping someone else had had this problem and could give me a hint as to what to try to fix this??? I have double checked the database, the column names, etc. I need to know what kinds of things may make the line:
$result = $auth->authenticate($adapter);
result in a white screen of death??? Any ideas? I have all error display turned on in application.ini.
I am running Zend 1.11.12 on this server. Does that make a difference? The server where it is working is running is running 1.12.0-9
Thanks for any ideas you might have.
EDIT::: I added code for my _getAuthAdapter.
Enable the error reporting for your app. Set all error reporting to 1 in your configs/application.ini file -
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
Also, instead of returning true or false, try to print a message, or redirect to a different page to know.
Try a var_dump on the $adapter to see the resulting object.
I've never used Zend_Auth to authenticate. You should be able to do that with your adapter. (assuming your $adapter is an instance of Zend_Auth_Adapter_DbTable for example)
$adapter = $this->_getAuthAdapter();
// this will tell you if there's something wrong with your adapter
if (!($adapter instanceof Zend_Auth_Adapter_DbTable)) {
throw new Exception('invalid adapter');
}
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$result = $adapter->authenticate();
if ($result->isValid()) {
}
I tried like below,
public function loginAction() {
$this->_helper->layout->disableLayout();
$users = new Application_Model_DbTable_Admin();
$this->_redirector = $this->_helper->getHelper('Redirector');
$form = new Application_Form_LoginForm();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
if ($form->isValid($_POST)) {
$consumer = new Zend_OpenId_Consumer();
$username = $this->_request->getPost('username');
$password = $this->_request->getPost('password');
if ($username <> '' && $password <> '') {
$auth = Zend_Auth::getInstance();
$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(), 'admin');
$authAdapter->setIdentityColumn('username')
->setCredentialColumn('password');
$authAdapter->setIdentity($username)
->setCredential(md5($password));
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
$storage = new Zend_Auth_Storage_Session();
$storage->write($authAdapter->getResultRowObject());
$this->_auth_user = $auth->getStorage()->read();
$this->_redirect('admin/index/');
}
else
$this->view->errorMessage = "Invalid username or password. Please try again.";
}
else
$this->view->errorMessage = "Username or password should not be empty!!!.";
}
}
}
If your Adapter doesn't work try it:
public function _getAuthAdapter() {
$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('table_name')
->setIdentityColumn('user_name')
->setCredentialColumn('password');
return $authAdapter;
}
And in application.ini
resources.db.isDefaultTableAdapter = true

Session won't be created in Mozilla Firefox

I am working on a purchase system in my assignment and trying to solve the problem by using a session to store data in the process.
Although I'm experiencing a problem in Mozilla Firefox, which cannot for some reason work with the session I have created. There's most likely no doubt that I must have made some kind of mistake.
The process is as follows:
User fills form -> Clicks submit -> [Validation process] -> User reviews confirm page
Here is the relevant code from the controller:
public function indexAction() {
$this->gatewayForm = new Payment_Form_Gateway;
$save = $this->validate();
$this->view->gatewayForm = $save['form'];
$this->view->alert = $save['alert'];
}
public function validate() {
# get form
$form = $this->gatewayForm;
if ($this->_request->isPost()) {
# get params
$data = $this->_request->getPost();
# check validate form
if ($form->isValid($data)) {
$session = new Zend_Session_Namespace('formData'); // name space creation
$session->data = $data;
$this->_helper->redirector('confirm', 'gateway', 'payment');
} else {
$alert = array('Pay failed');
}
$form->populate($data);
}
return array('form' => $form, 'alert' => empty($alert) ? null : $alert );
}
public function confirmAction() {
$this->_helper->viewRenderer->setNoRender(true); // disable std. view
$session = new Zend_Session_Namespace('formData');
$data = $session->data;
if(isset($data)) {
$this->_helper->viewRenderer->setNoRender(false);
} else {
$this->_helper->redirector('index', 'gateway', 'payment');
}
}
Things go wrong in the confirmAction in Firefox, the session namespace seems to be empty? Although this does not occur in Safari, Chrome, IE etc.
Thanks in advance.
I reinstalled Firefox and removed config and cache files which did the magic. Problems solved!