Zend authenticate returns white screen - zend-framework

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

Related

Zend_Auth Identity not persisting between controllers

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

How to migrate mysqli to pdo

Hi I was wondering how I would migrate a mysqli php file to use PDO. Would anyone be able to take a look at my code and see if I'm on the right track?
This is my original (mysqli) code:
<?php
// connecting to database
$conn = new mysqli('xxxxxx', 'xxxxxx', 'password', 'xxxxxx');
$match_email = 'email';
$match_passhash = 'passhash';
if (isset($_POST['email'])) {
$clean_email = mysqli_real_escape_string($conn, $_POST['email']);
$match_email = $clean_email;
}
if (isset($_POST['passhash'])) {
$clean_passhash = mysqli_real_escape_string($conn, $_POST['passhash']);
$match_passhash = sha1($clean_passhash);
}
$userquery = "SELECT email, passhash, userlevel, confirmed, blocked FROM useraccounts
WHERE email = '$match_email' AND passhash = '$match_passhash'
AND userlevel='user' AND confirmed='true' AND blocked='false';";
$userresult = $conn->query($userquery);
if ($userresult->num_rows == 1) {
$_SESSION['authorisation'] = 'knownuser';
header("Location: userhome.php");
exit;
} else {
$_SESSION['authorisation'] = 'unknownuser';
header("Location: userlogin.php");
exit;
}
?>
And this is my attempt to migrate it to PDO:
<?php
// connecting to database
$dbh = new PDO("mysql:host=xxxxxx; dbname=xxxxxx", "xxxxxx", "password");
$match_email = 'email';
$match_passhash = 'passhash';
if (isset($_POST['email'])) {
$clean_email = mysqli_real_escape_string($conn, $_POST['email']);
$match_email = $clean_email;
}
if (isset($_POST['passhash'])) {
$clean_passhash = mysqli_real_escape_string($conn, $_POST['passhash']);
$match_passhash = sha1($clean_passhash);
}
$userquery = "SELECT email, passhash, userlevel, confirmed, blocked FROM useraccounts
WHERE email = ':match_email' AND passhash = ':match_passhash' AND
userlevel='user' AND confirmed='true' AND blocked='false';";
$stmt = $dbh->prepare($query);
$stmt->bindParam(":match_email", $match_email);
$stmt->bindParam(":match_passhash", $match_passhash);
$stmt->execute();
$userresult = $conn->query($userquery);
if ($userresult->num_rows == 1) {
$_SESSION['authorisation'] = 'knownuser';
header("Location: userhome.php");
exit;
} else {
$_SESSION['authorisation'] = 'unknownuser';
header("Location: userlogin.php");
exit;
}
?>
I'm also not sure how to count the number of rows returned in PDO.
If anyone would be able to help me out that wold be very great.
A million thanks in advance!
When using prepared statements and $stmt->bindValue() or $stmt->bindParam() you do not need to escape values with mysqli_real_escape_string(), PDO will do that for you.
Just remember to set a correct data type for the value. That is the third argument in the bind functions and it is a string by default so your code here is fine. I would only use bindValue() instead of bindParam() as you do not need references.
$stmt->execute() will run your prepared statement as a query. The other $conn->query() does not work with prepared statements. It is for raw queries, like you used to have with MySQLi.
When $stmt->execute() runs your response is saved in the $stmt object. For row count use $stmt->rowCount().

Zend Authentication and Login - accepts foo and foo1! both for a saved foo password

I'm trying to script an authentication and login script and am quiet there.. I have a password 'password' saved in my database... it works with the password 'password' however should not work with 'password1!' or prefix or suffix two characters more.... IT shouldn't accept it... but if I enter something different (different string, or a few more characters), it gives me a proper error...
That is the only row in my database table... there are no duplicate entries..
Following is the code
public function validate_login($valuethrown) {
$username = $valuethrown['username'];
$email = $valuethrown['email'];
$password = $valuethrown['password'];
echo "Values thrown to the model are : $username, $email, $password";
$authAdapter = $this->getAuthAdaptor();
$authAdapter->setIdentity($email)
->setCredential(md5($password));
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
$data = $authAdapter->getResultRowObject(null,'password');
$auth->getStorage()->write($data);
$this->_redirect('home');
} else {
echo "</br>Wrong Password</br>";
}
//check login details
}
public function getAuthAdaptor() {
$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('users')
->setIdentityColumn('email')
->setCredentialColumn('password');
return $authAdapter;
}
HELP!!!!

How do I pass _SESSION('userName') from this Zend_Auth method to the layout?

I'm having a difficult time understanding how Zend_Session_Namespace is integrated with Zend_Auth. I have this method I'm using as the action to Authenticate my login page-it is working correctly and redirecting to the /monthly view:
public function authAction(){
$request = $this->getRequest();
$registry = Zend_Registry::getInstance();
$auth = Zend_Auth::getInstance();
$DB = $registry['DB'];
$authAdapter = new Zend_Auth_Adapter_DbTable($DB);
$authAdapter->setTableName('users')
->setIdentityColumn('UserName')
->setCredentialColumn('Password');
// Set the input credential values
$uname = $request->getParam('UserName');
$paswd = $request->getParam('Password');
$authAdapter->setIdentity($uname);
$authAdapter->setCredential($paswd);
// Perform the authentication query, saving the result
$result = $auth->authenticate($authAdapter);
// TRYING TO SET THE NAMESPACE
$this->session = new Zend_Session_Namspace('UserName');
if($result->isValid()){
$data = $authAdapter->getResultRowObject(null,'password');
$auth->getStorage()->write($data);
$this->_redirect('/monthly');
}else{
$this->_redirect('/login');
}
}
But I need to be able to store UserName as a Zend_session and call it from monthly controller. I'm not doing things right because I just get a blank screen when I try and do this:
public function indexAction()
{
$this->view->userName = Zend_Session_Namespace('UserName');
}
With the lines:
$data = $authAdapter->getResultRowObject(null,'password');
$auth->getStorage()->write($data);
You're writing all the user's information, except the password, which is OK. Where ever you need to access the logged in user's details, you can do something like (updated as per your comment):
public function indexAction() {
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {
$userData = $auth->getIdentity();
$this->view->user = $userData;
}
}
in the view file (index.phtml) just: echo $this->user->firstname
That's it. If one day you decide to change the storage for Zend_Auth from session, to, for example, database, this piece of code will still work.
Youre not useing the correct namespace. Zend_Auth use the Zend_Auth namespace. The namespace is the structure, not the key for a value. so your session looks something like this:
Array('Zend_Auth' => array ('UserName' => 'myname')
Well thats not accurate exactly because you havent stored the user name unless youve provided for this directly in your adapter. youll need to do something like:
$auth->getStorage()->UserName = 'myusername';
Then you can access with $authData = new Zend_Session_Namespace('Zend_Auth'); $username = $authData->UserName;.
Take a closer look at how the Zend_Auth_Adapter_Db works.
This is my approach and it s working nice:
1-i start by defining an init function in the bootstrap
protected function _initSession()
{
$UserSession = new Zend_Session_Namespace('UserSession');
$UserSession->setExpirationSeconds(/* you may fix a limit */);
Zend_Registry::set('UserSession', $UserSession);
}
/* in the Login action,after correct username & pwd */
// Create session
$UserSession = Zend_Registry::get('UserSession');
// Get the user from database or just from fields
//you have to make sure that the psswd is encrypted use MD5 for example..
$db = Zend_Db_Table::getDefaultAdapter();
$user = $db->fetchRow("SELECT * FROM user_table WHERE user_email = '".$user_email."'");
//then you assign to $user to $UserSession variable :
$UserSession->user = $user;
//finaly don't forget to unset session variable in the Logout action ...

Zend Framework User Authentication

What is the best practice for user website/REST authentication in ZV MVC? How and where to put the code in the ZF framework? Can you provide me a code example?
I have a website and a REST server written in Zend Framework but no user session jet implemented.
THX!
Authentication is setup in the _initAutoload of the bootstrap file, e.g. like this:
if(Zend_Auth::getInstance()->hasIdentity()) {
Zend_Registry::set('role', Zend_Auth::getInstance()
->getStorage()->read()->role);
}else{
Zend_Registry::set('role', 'guests');
}
In case of a REST authentication you might need to authenticate by just passing the login parameters instead of logging in through a form.
So it might look like this in your AuthenticationController:
private function getAuthAdapter() {
$authAdapter = new Zend_Auth_Adapter_DbTable(
Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('users') // the db table where users are stored
->setIdentityColumn('email')
->setCredentialColumn('password')
->setCredentialTreatment('SHA1(CONCAT(?,salt))');
return $authAdapter;
}
public function logoutAction() {
Zend_Auth::getInstance()->clearIdentity();
$this->_redirect('index/index');
}
public function loginAction(){
if (Zend_Auth::getInstance()->hasIdentity()){
$this->_redirect('index/index');
}
if ($request->isPost()){
$username = $request->getPost('username');
$password = $request->getPost('password');
if ($username != "" && $password != "") {
$authAdapter = $this->getAuthAdapter ();
$authAdapter->setIdentity($username)
->setCredential($password);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if($result->isValid()){
$identity = $authAdapter->getResultRowObject();
$authStorage = $auth->getStorage();
$authStorage->write($identity);
$this->_redirect ( 'index/index' );
}
}
}
}
If you need more help on zend_auth and zend_acl you might have a look at this how to.