authentication in zend - php

I am using zend auth for authentication. and everything works fine on my local machine.
But when i try to connect to remote server for database than problem starts.
It is not able to login. Is is some problem with session or what..?
$db = new Zend_Db_Adapter_Pdo_Mysql(array(
'host' => 'localhost',
'username' => 'root',
'password' => '123456',
'dbname' => 'saet'
));
$form = new Default_Form_Login();
if ($this->getRequest()->isPost()) {
//$db = Zend_Registry::get('db');
$adapter = new Zend_Auth_Adapter_DbTable($db);
$adapter->setTableName('users')
->setIdentityColumn('username')
->setCredentialColumn('password')
->setCredentialTreatment('MD5(?)');
$credentialsArray = $this->_request->getParams();
$adapter->setIdentity($credentialsArray['username'])
->setCredential($credentialsArray['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$userInfo = $adapter->getResultRowObject(null, 'password');
// the default storage is a session with namespace Zend_Auth
$authStorage = $auth->getStorage();
$authStorage->write($userInfo);
$this->_helper->FlashMessenger('Successful Login');
return $this->_helper->redirector('index');
} else {
$this->_helper->FlashMessenger->addMessage(array('error',"Invalid Username/Password"));
return $this->_helper->redirector('login');
}
now when i change the db details to remote server. it fails to log in. i m new in zend. and i get application error.

To display errors change your application.ini file as follows
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
and then give us the error.

Related

F3 Framework: how to make sure that caching is working correctly?

I'm getting the database credentials from AWS secrets manager and storing it in the cache so that it doesn't have to be fetched from AWS on every request.
The problem is that, if I change the secret name for testing, F3 won't be able to connect to the database. That means that it's detecting the secret name getting changed even though I tell F3 to check that only if it wasn't able to find anything cached.
use Aws\SecretsManager\SecretsManagerClient;
$f3->set('CACHE', true);
if ($f3->exists('dbusername')) {
$username = $f3->get('dbusername');
$password = $f3->get('dbpassword');
$host = $f3->get('dbhost');
$port = $f3->get('dbport');
} else {
$secretName = getenv('AWS_SECRET_NAME');
$client = new SecretsManagerClient([
'version' => 'latest'
]);
$secretManager = $client->getSecretValue([
'SecretId' => $secretName,
]);
$db = json_decode($secretManager['SecretString']);
$username = $db->username;
$password = $db->password;
$port = $db->port;
$host = $db->host;
}
$f3->set('dbusername', $username);
$f3->set('dbpassword', $password);
$f3->set('dbhost', $host);
$f3->set('dbport', $port);
I'm testing on my PC, I don't know if that code would work on a server, not sure if the issue from my PC or if I'm not caching correctly.
It turns out that the cache wouldn't work unless a ttl (time to live) is specified. Here's how to cache the values above for 24 hours.
$f3->set('dbusername', $username, 86400);
$f3->set('dbpassword', $password, 86400);
$f3->set('dbhost', $host, 86400);
$f3->set('dbport', $port, 86400);

OAuth2 The grant type was not specified

I follow this steps, but when execute this:
curl -u testclient:testpass http://localhost/token.php -d 'grant_type=client_credentials'
receive this
{"error":"invalid_request,"error_description":"The grant type was not specified in the request"}
How i should put the 'grant_type' in request in this case
These are two files
server.php
$dsn = 'mysql:dbname=oauth2;host=localhost';
$username = 'root';
$password = '';
// error reporting (this is a demo, after all!)
ini_set('display_errors',1);error_reporting(E_ALL);
require_once('../src/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();
$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
$server = new OAuth2\Server($storage);
$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage)); // or any grant type you like!
token.php
require_once __DIR__.'/server.php';
// Handle a request for an OAuth2.0 Access Token and send the response to the client
$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
try this:
curl -u testclient:testpass http://localhost/token.php -d grant_type=client_credentials
These are two files
server.php
$dsn = 'mysql:dbname=oauth2;host=localhost';
$username = 'root';
$password = '';
// error reporting (this is a demo, after all!)
ini_set('display_errors',1);error_reporting(E_ALL);
require_once('../src/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();
$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
$server = new OAuth2\Server($storage);
$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage)); // or any grant type you like!
token.php
require_once __DIR__.'/server.php';
// Handle a request for an OAuth2.0 Access Token and send the response to the client
$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();

Zend: no database addapter present error

I am following a tutorial to make a login form. If the user is authenticated, simply redirect the user to the Home page. If login fails, show the error. I have the error
No database adapter present
Stack trace:
#0 \Zend_Include\library\Zend\Auth\Adapter\DbTable.php(139): Zend_Auth_Adapter_DbTable->_setDbAdapter(NULL)
#1 \application\controllers\AccountController.php(24): Zend_Auth_Adapter_DbTable->__construct(NULL)
I reread the tutorial, but the code is identical and I have no idea why I have this error.
my loginAction() in Account Controller
$form = new Application_Model_FormLogin(array('action'=>'/account/login'));
// if the form is submitted
if ($this->getRequest()->isPost()){
if ($form->isValid($this->_request->getPost())) {
$db = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName('accounts');
$authAdapter->setIdentityColumn('email');
$authAdapter->setCredentialColumn('pswd');
$authAdapter->setCredentialTreament('MD5(?) and confirmed=1');
$authAdapter->setIdentity($form->getValue('email'));
$authAdapter->setCredential($form->getValue('pswd'));
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
// did the user successfully login
$account = new Application_Model_Account();
$lastLogin = $account->findByEmail($form->getValue('email'));
$lastLogin->last_login = date('Y-m-d H:i:s');
$lastLogin->save();
$this->_helper->flashMessenger->addMessage('You are logged in');
$this->redirector('Index', 'index');
}else{
. . .
}
}else{
. . .
}
$this->view->form = $form;
}
Try the follwoing, before you use Zend_Db_Table:
$dbAdapter = Zend_Db::factory ( 'PDO_MYSQL', $objDbConfig);
AbstractTable::setDefaultAdapter ( $dbAdapter );

Upload to YouTube using Zend - via a proxy

I've been successfully uploading videos to YouTube using some code I found (Zend with YouTube API).
I modified it so that I can upload via a proxy server, but I've hit a brick wall. I've commented which lines I added to implement the proxy support. Here is the code:
<?php
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Http_Client_Exception'); //added for proxy support
Zend_Loader::loadClass('Zend_Http_Client'); //added for proxy support
Zend_Loader::loadClass('Zend_Http_Client_Adapter_Proxy'); //added for proxy support
Zend_Loader::loadClass('Zend_Gdata_App_HttpException'); //added for proxy support
$config = array(
'adapter' => 'Zend_Http_Client_Adapter_Proxy',
'proxy_host' => 'MY_PROXY_IP',
'proxy_port' => 8080,
'proxy_user' => 'USER',
'proxy_pass' => 'PASS'
); //added for proxy support
$proxiedHttpClient = new Zend_Gdata_HttpClient('http://www.google.com/', $config); //added for proxy support
try
{
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'YOUTUBE EMAIL ID',
$password = 'YOUTUBE PASSWORD',
$service = 'youtube',
$client = $proxiedHttpClient, //changed from "$client = null"
$source = 'mysource',
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
}
catch (Zend_Gdata_App_Exception $e)
{
$arry['data']['flag'] = false;
$arry['data']['msg'] = 'Username or Password Invalid.';
print_r(json_encode($arry));
die();
}
$httpClient->setConfig($config); //added for proxy support
$developerKey='DEVELOPER KEY';
$applicationId = 'not require';
$clientId = 'not require';
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
$fileName = "FILENAME";
$fileType = "video/mp4";
$newEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource($fileName);
$filesource->setContentType('video/mp4');
$filesource->setSlug($fileName);
$newEntry->setMediaSource($filesource);
$newEntry->setVideoTitle("VIDEO TITLE");
$newEntry->setVideoDescription("VIDEO DESCRIPTION HERE");
$newEntry->setVideoCategory("VIDEO CATEGORY HERE");
$newEntry->setVideoTags("VIDEO TAGS");
try {
$newEntry = $yt->insertEntry($newEntry, 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads', 'Zend_Gdata_YouTube_VideoEntry');
$state = $newEntry->getVideoState();
if ($state)
{
$videourl = $newEntry->getVideoWatchPageUrl();
$arry['data']['flag'] = true;
$arry['data']['url'] = $videourl;
$arry['data']['msg'] = "Video Uploaded Successfully.";
}
else
{
$arry['data']['flag'] = false;
$arry['data']['msg'] = "Not able to retrieve the video status information yet. " ."Please try again later.\n";
}
}
catch (Zend_Gdata_App_Exception $e) {
$arry['data']['flag'] = false;
$arry['data']['msg'] = $e->getMessage();
}
echo "<pre>";
print_r($arry);
?>
When I execute the PHP from the command line, the message it gives back is:
Trying to write but we are connected to the wrong proxy server
The proxies I've been testing with definitely work - in fact, if I use a broken proxy it just says "Username or Password is invalid." I only get the error message above when using working proxies.
Any guidance or solution would be greatly appreciated.
I had the same problem and I found a solution that worked for me. I used the built in cURL Adapter instead of the Proxy adapter.
See my example below...
$config = array(
'adapter' => 'Zend_Http_Client_Adapter_Curl',
'curloptions' => array(CURLOPT_FOLLOWLOCATION => true, CURLOPT_PROXY => "proxy:port", CURLOPT_PROXYUSERPWD => "username:password")
);
This code is using turned down GData API and deprecated clientlogin
Please update to v3 API, here are PHP examples to get you started.

Jommla connect to another database using Multisites extension

I'm using Joomla 2.5 and Multisites extensions. When I'm on page X Joomla is using X-database, on page Y using Y-database - it's ok. Unfortunately I have to switch to another database. How I said $db = JFactory::getDbo(); connect to current site database, because Multisites extension works that every page has his own configuration file with database parameters. Any ideas?
Here is solution:
$option['driver'] = 'mysqli';
$option['host'] = 'localhost';
$option['user'] = 'root';
$option['password'] = '';
$option['database'] = 'joomla';
$option['prefix'] = 'a45gy_';
JFactory::destroy();
$db = JDatabase::getInstance($option);
if (JError::isError($db)) {
jexit('Database Error: ' . $db->toString());
}
if ($db->getErrorNum() > 0) {
JError::raiseError(500, 'JDatabase::getInstance: Could not connect to database <br />');
}
parent::setDbo($db);
try it.
$dbX = JDatabase::getInstance(array ('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'prefix'=>null));
$dbY = JDatabase::getInstance(array ('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'prefix'=>null));

Categories