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 );
Related
I used HybridAuth extension for the purpose of signing in as facebook.
The code which is causing error in Hybrid Auth is as follows:
try
{
$path1 = Yii::getPathOfAlias('ext.HybridAuth');
require_once ($path1 . '/hybridauth-' . HybridAuthIdentity::VERSION . '/hybridauth/Hybrid/Auth.php');
$config = $path1 . '/hybridauth-' . HybridAuthIdentity::VERSION . '/hybridauth/config.php';
// initialize Hybrid_Auth with a given file
$hybridauth = new Hybrid_Auth( $config );
// try to authenticate with the selected provider
$adapter = $hybridauth->authenticate( $provider_name );
// then grab the user profile
$user_profile = $adapter->getUserProfile();
}
catch(Exception $e)
{
}
i am using the below code to connect to salesforce using php
require_once ('SforcePartnerClient.php');
require_once ('SforceHeaderOptions.php');
require_once ('SforceMetadataClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("cniRegistration.wsdl");
$loginResult = $mySforceConnection->login("username", "password.token");
$queryOptions = new QueryOptions(200);
try {
$sObject = new stdclass();
$sObject->Name = 'Smith';
$sObject->Phone = '510-555-5555';
$sObject->fieldsToNull = NULL;
echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create($sObject, 'Account');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
echo $e->faultstring;
}
But the above code is connect to salesforce database.
But is not executing the create commands. it's giving me the below error message
Creating the following: Element {}item invalid at this location
can any one suggest me to overcome the above problem
MAK, in your sample code SessionHeader and Endpoint setup calls are missing
$mySforceConnection->setEndpoint($location);
$mySforceConnection->setSessionHeader($sessionId);
after setting up those, if you still see an issue, check the namespace urn
$mySforceConnection->getNamespace
It should match targetNamespace value in your wsdl
the value of $mySforceConnection should point to the xml file of the partner.wsdl.xml.
E.g $SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
Try adding the snippet code below to reference the WSDL.
$sfdc = new SforcePartnerClient();
// create a connection using the partner wsdl
$SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
$loginResult = false;
try {
// log in with username, password and security token if required
$loginResult = $sfdc->login($sfdcUsername, $sfdcPassword.$sfdcToken);
}
catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Fatal Login Error <b>" . $errors . "</b>";
die;
}
// setup the SOAP client modify the headers
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_SALESFORCE_URL_", "https://test.salesforce.com");
define ("_WS_NAME_", "WebService_WDSL_Name_Here");
define ("_WS_WSDL_", "soapclient/" . _WS_NAME_ . ".wsdl");
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
$urlLink = '';
try {
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
} catch ( Exception $e ) {
die( 'Error<br/>' . $e->__toString() );
}
Please check the link on Tech Thought for more details on the error.
Users on my website can login to Twitter and post their status on my website and twitter at once. I'm using https://github.com/abraham/twitteroauth to connect to Twitter. Login and posting is performed on different pages of website.
This is login script:
public function loginTwitter() {
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret']
);
$request_token = $twitter->getRequestToken($this->link('//User:connectFromTwitter'));
// Saving to session (Nette Framework)
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitterSession->oauth_request_token = $token = $request_token['oauth_token'];
$twitterSession->oauth_request_token_secret = $request_token['oauth_token_secret'];
if ($twitter->http_code == 200) {
$requestLink = $twitter->getAuthorizeURL($token);
$this->redirectUrl($requestLink);
} else {
echo 'Error';
}
}
This is callback script (posting works right after user has been logged in):
public function twitterOauth() {
// $_GET parameter oauth_verifier
$oauthVerifier = $this->getParam('oauth_verifier');
// Session section
$twitterSession = $this->getContext()->session->getSection('twSes');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->oauth_request_token,
$twitterSession->oauth_request_token_secret
);
$access_token = $twitter->getAccessToken($oauthVerifier);
$twitterSession->access_token = $access_token;
$user_info = $twitter->get('account/verify_credentials');
// Saving to DB to be able to post without login
$tm = new TwitterUserManager();
if (!$tm->isInDatabase($this->getUser()->getId())) {
$tu = new TwitterUser();
$tu->setUser($this->loggedUser);
$tu->setOauthProvider('twitter');
$tu->setOauthUid("'".$user_info->id."'");
$tu->setUsername("'".$user_info->screen_name."'");
$tu->setOauthToken("'".$access_token['oauth_token']."'"); // Saving the access token for further posting
$tu->setOauthSecret("'".$access_token['oauth_token_secret']."'");
$tm->persist($tu);
}
$twitter->post('statuses/update', array('status' => 'Hello ' . date('d.m.Y H:i:s'))); // <== HERE IT WORKS
$this->redirect('User:socialConnect'); // Redirect to another page
}
This is posting function (User posts from any page):
public function postToTwitter() {
$twitterSession = $this->getContext()->session->getSection('twitter');
$twitter = new TwitterOAuth(
$this->getContext()->params['social']['twitter']['consumerKey'],
$this->getContext()->params['social']['twitter']['consumerSecret'],
$twitterSession->access_token['oauth_token'],
$twitterSession->access_token['oauth_token_secret']
);
return $twitter->post('statuses/update', array('status' => 'Hello' . date('d.m.Y H:i:s')));
}
When I use posting function I get this error:
stdClass(2) {
request => "/1/statuses/update.json" (23)
error => "Could not authenticate you." (27)
}
Thanks for help in advance.
EDIT: Solution:
Use this to connect to Twitter (save all info into DB):
http://framework.zend.com/manual/1.12/en/zend.oauth.introduction.html
Use this to post from any page:
http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
Nice example:
http://www.joeyrivera.com/2010/twitter-api-oauth-authentication-and-zend_oauth-tutorial/
I always used the Zend-Framework-Component: http://framework.zend.com/manual/1.12/en/zend.service.twitter.html
I think it's simple and I could confirm, that it works. You just have to read through the tutorial (see link above).
I am developing a component for Joomla. It has integrations with popular social websites. I retrieve user information from database via given social profile. Then, I try to make this user login with the following code:
$fbuser = $facebook->api(
'/me',
'GET',
array(
'access_token' => $_SESSION['active']['access_token']
)
);
// Get a database object
$db =& JFactory::getDBO();
$query = "SELECT * FROM #__users WHERE email = '".$fbuser['email']."';";
$db->setQuery($query);
$row = $db->loadRow();
if(isset($row))
{
$app = JFactory::getApplication();
$user =& JUser::getInstance($row[0]);
$credentials = array();
$credentials['username'] = $user->get('username');
$credentials['password'] = $user->get('password'); // When I change this to related users plain password then it works
$options = array();
$options['remember'] = true;
$options['silent'] = true;
$app->login($credentials, $options);
}
else
{
return 'There is no account associated with facebook';
}
The problem is database return encoded password and this doesn't work. When I give decoded password to $credentials it works. What can be the problem?
One option is to create your own authentication plugin (quite simple task) that would log in any user with a specific password known only to you and the site.
Then you can supply that password along with known username.
For the sake of security, only allow that plugin to log in ordinary users, and not admins.
You need to MD5 hash the pwd (the way it's stored in the DB).
try this:
$salt = '19IQYkelXrqVH1Eht6PFOIZRe5T1SQHs';
$pwd = md5_hex($pwd . $salt) .":$salt";
$query = "select name,username,email,password from jos_users where password = $pwd;";
...
// --- login mamanam.com
$app = JFactory::getApplication();
$credentials = array();
$credentials['username'] = $username;
$credentials['password'] = $password;
$app->login($credentials);
Necessary parameters in array $credentials=array() for logon function Joomla! $app->login($credentials)
*Sorry my English is not so good
-> i am trying for new user registration customization.
-> for that i create form and hidden variable through call function from controller.
-> in controller save function i write this code but some inner function which not work in 1.7 so create problem here.
function register_save()
{
global $mainframe;
$db =& JFactory::getDBO();
// Check for request forgeries
JRequest::checkToken() or jexit( 'Invalid Token' );
//clean request
$post = JRequest::get( 'post' );
$post['username'] = JRequest::getVar('username', '', 'post', 'username');
$post['password'] = JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
$post['password2'] = JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
// get the redirect
$return = JURI::base();
// do a password safety check
if(strlen($post['password']) || strlen($post['password2'])) { // so that "0" can be used as password e.g.
if($post['password'] != $post['password2']) {
$msg = JText::_('PASSWORD NOT MATCH');
// something is wrong. we are redirecting back to edit form.
// TODO: HTTP_REFERER should be replaced with a base64 encoded form field in a later release
$return = str_replace(array('"', '<', '>', "'"), '', #$_SERVER['HTTP_REFERER']);
if (empty($return) || !JURI::isInternal($return)) {
$return = JURI::base();
}
$this->setRedirect($return, $msg, 'error');
return false;
}
}
// Get required system objects
$user = clone(JFactory::getUser());
$pathway = JFactory::getApplication();
//$pathway =& $mainframe->getPathway();
$config =& JFactory::getConfig();
//print_r($config)."<br>";
$authorize =& JFactory::getACL();
//print_r($authorize)."<br>"; /// some mistake here
$newUsertype = 'Registered';
// Bind the post array to the user object
if (!$user->bind( JRequest::get('post'), 'usertype' )) {
JError::raiseError( 500, $user->getError());
}
// Set some initial user values
$user->set('id', 0);
$user->set('usertype', $newUsertype);
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
$date =& JFactory::getDate();
$user->set('registerDate', $date->toMySQL());
// If user activation is turned on, we need to set the activation information
jimport('joomla.user.helper');
$user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
// If there was an error with registration, set the message and display form
if ( !$user->save() )
{
JError::raiseWarning('', JText::_( $user->getError()));
$this->register();
return false;
}
$obj1 = new stdClass();
$obj1->userid = $user->id;
$obj1->points = 0;
$obj1->posted_on = $date->toMySQL();
$obj1->avatar = '';
$obj1->thumb = '';
$obj1->params = 'notifyEmailSystem=1
privacyProfileView=0
privacyPhotoView=0
privacyFriendsView=0
privacyVideoView=1
notifyEmailMessage=1
notifyEmailApps=1
notifyWallComment=0';
$db->insertObject('#__community_users', $obj1, 'userid');
$extra_field = array(1=>2,2=>3,3=>4,4=>6,5=>7,6=>8,7=>9,8=>10,9=>11,10=>12,11=>14,12=>15,13=>16);
$i = 1;
$obj2 = new stdClass();
while($extra_field[$i] != "")
{
$obj2->id = '';
$obj2->user_id = $user->id;
$obj2->field_id = $extra_field[$i];
$obj2->value = '';
$db->insertObject('#__community_fields_values', $obj2, 'id');
$i++;
}
////////// end of joomsocial customisation///////////////////////////
// Send registration confirmation mail
$password = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
$password = preg_replace('/[\x00-\x1F\x7F]/', '', $password); //Disallow control chars in the email
UserControllerRegister::_sendMail($user, $password);
// Everything went fine, set relevant message depending upon user activation state and display message
$message = JText::_( 'Your account has been created and an activation link has been sent to the e-mail address you entered. Note that you must activate the account by clicking on the activation link when you get the e-mail before you can login.' );
$this->setRedirect('index.php', $message);
}
not insert record in table.
please help me.
I think you're right:
Joomla 1.5 ACL (Access Control Lists) is hierarchical: each user group inherits permissions from the groups below it.
In Joomla 1.7 ACL is not necessarily hierarchical. You can setup groups with whatever permissions you wish.
The difference between the ACL in Joomla 1.5 and 1.7 is not only in the behavior - but also in the implementation! which means that the authentication/registration mechanism will be implemented in different ways:
http://www.youtube.com/watch?v=ZArgffnPUo4