decryption and encryption password in yii - database

It is my code:
//save user in DB
$email='user1#email.com';
$username='user1';
$password='user1';
echo 'No hashed password='.$password.'<br>';
$user= new User();
$user->email=$email;
$user->username=$username;
$user->password=Yii::$app->getSecurity()->generatePasswordHash($password);
echo 'Hashed password='.$user->password;
echo '<br>';
$user->save();
//check user
$password2 ='user1';
$password2=Yii::$app->getSecurity()->generatePasswordHash($password2); //do hash
echo 'Hashed password2='.$password2;
$check_user=User::find()->where(['email' => $email])->one();
if($check_user) { //if user found
if (Yii::$app->getSecurity()->validatePassword($password2, $check_user->password)) {
echo 'Yes';
} else {
echo 'No';
}
}
I save my data(email,username,password) in DB . And when I want to check my password I always get NO.
How can I solve my problem?

You don't need to generate a new hash when checking the password. Just compare the information ($password2) with your saved hash ($check_user->password).
//check user
$password2 ='user1';
echo 'password2 = ' . $password2 . '<br />';
$check_user=User::find()->where(['email' => $email])->one();
if($check_user) //if user found
{
if (Yii::$app->getSecurity()->validatePassword($password2, $check_user->password)) {
echo 'Yes';
} else {
echo 'No';
}
}
You can find more information in the docs: here and here.

Related

Cant fix my if-else condition in login.php

I have created a condition to check if name and password are correct the only issue here is when i test it it goes complete the opposite of what i want. It doesnt matter if i put it right or wrong the message will always be "You have successfuly logged in". Im using PDO just to know
<?php
include('connection.php');
$name = $_POST['name'];
$password = $_POST['password'];
$data = $_POST;
$statment = $connection->prepare('SELECT * FROM registration WHERE name = :name AND password = :password');
if($statment){
$result = $statment->execute([
':name' => $data['name'],
':password' => $data['password']
]);
}
if($data['name'] == $name && $data['password'] == $password){
echo 'You have successfuly logged in';
}else {
die('Incorrect username or password');
}
?>
You have made your script overly complicated .. The easiest way is to bind and execute .. Then you can simply check if there are any rows, and THEN compare with your data array created from the executed statement.
<?php
include('connection.php');
$name = $_POST['name'];
$password = $_POST['password'];
$statment = $connection->prepare("SELECT name, password FROM registration
WHERE name = ? AND password = ?");
$statment ->bind_param("ss", $name, $password);
$statment ->execute();
$result = $stmt->get_result();
if ($result ->num_rows > 0) {
$data = $result->fetch_array();
}else{
echo "No results found";
}
if($data['name'] == $name && $data['password'] == $password){
echo 'You have successfuly logged in';
}else {
die('Incorrect username or password');
}
?>
(bear in mind I wrote that freehand, and it has not been tested or debugged, but the principals are there)
ON A SIDE NOTE
That being said .. You should never be storing passwords in a open "text" field. You should be encrypting them. The easiest way is to use bcrypt to build out a hash:
$options = [
'cost' => 12,
];
$newPass = password_hash($pass, PASSWORD_BCRYPT, $options);
And store that in your database .. Then you can compare it like so ..
if (password_verify($pss, $pwdCheck)
$pss being what was sent in from the form .. and $pwdCheck being the hash you SELECTED from the database -- Brought into your current code set, would look something like:
if($data['name'] == $name && password_verify($password, $data['password']){

Single Signon with Magento account from drupal

I have custom Magento script file as below which does login by just passing email and password to that PHP file.
It works fine when i'm making a call from browser.
But, I want to make this call through Drupal Module which i have created.
As i expected call is happening from Drupal module and i'm getting success message too. But login is not happening.
My hunch is that magento have some login restrictions which happening outside magento root folder.
Please find the source below.
Drupal directory - /www/drupal/
Magento directory - /www/drupal/store/
/www/drupal/store/api_config.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
require_once (dirname(dirname(realpath(__FILE__))).'/store/app/Mage.php');
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name' => 'frontend'));
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$response = array();
/www/drupal/store/api_login.php
<?php
require_once "api_config.php";
$session = Mage::getSingleton('customer/session');
//$session->start();
if (isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['password']) && !empty($_GET['password'] )) {
if (!filter_var($_GET['email'], FILTER_VALIDATE_EMAIL) === false) {
$email = $_GET['email'];
$password = $_GET['password'];
try {
if ($session->login($email, $password )) {
$response['status'] = 'success';
$response['data'] = array($_GET);
$response['message'] = array('User loggedin Successfully.');
} else {
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('User login failed.');
}
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
$value = Mage::helper('customer')->getEmailConfirmationUrl($email);
$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', $value);
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
break;
default:
$message = $e->getMessage();
}
//$session->addError($message);
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array($message);
echo $message;
$session->setUsername($email);
} catch (Exception $e) {
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array($e);
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}
} else {
//$session->addError('Login and password are required.');
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('Invalid Email address');
}
} else {
//$session->addError('Login and password are required.');
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('Login and password are required.');
}
print_r(json_encode($response, JSON_FORCE_OBJECT));die;
?>
/www/drupal/sites/all/modules/single_signon/single_signon.module
<?php
function single_signon_user_login(&$edit, $account) {
//store variable values
$postData = array();
$postData['email'] = $account->mail;
$postData['password'] = $edit['input']['pass'];
$inc = 1; //count of registration
if (!empty($postData['email']) && !empty($postData['password'])) {
// use of drupal_http_request
$data = http_build_query($postData, '', '&');
//$url = url('http://127.0.0.1/drupal/store/api_login.php?'.$data);
//$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
//print_r($url);
// the actual sending of the data
$JSONresponse = drupal_http_request('http://127.0.0.1/drupal/store/api_login.php?email=john#example.com&password=password');
//print_r($JSONresponse);die;
$response = json_decode($JSONresponse->data, true);
if ($response['status']=='success') {
$inc+=1;
$message = 'Logged in successfully('.$inc.')';
drupal_set_message($message, $type = 'status', $repeat = FALSE); //message goes here
} else {
$message = 'Logged in failed. Due to '.$response['message'].'('.$inc.')';
drupal_set_message($message, $type = 'error ', $repeat = FALSE);
}
} else {
$message = 'Not able to log inside store('.$inc.')';
drupal_set_message($message, $type = 'status', $repeat = FALSE); //message goes here
}
}
?>
Any suggestions for findings to solve this mystery would be really helpful.
I'm not sure to understand it well : You have a php script using data send in the URL (GET) to connect a user in a session. And you would like the Drupal server to use it to connect directly to your Magento.
I think your code is working, but unfortunately it could not help the user to connect to Magento.
As this is the Drupal server asking for the connection, it would be the Drupal server session that will be connected and not the navigation user one.
If the user have to be connected, in his navigator, to the Magento server, it has to be the navigator witch must call the Magento script directly.
It could be done in an iframe or via Ajax I think.
I think you can also find some other solutions, as OAuth, but it will need a lot more of coding.
EDIT
I found some interesting subject about your problem :
Getting logged in user ID from Magento in external script - multiple session issue?
Magento Session from external page (same domain)
Magento external login will not create session cookie
I think you have to manually create the Magento session cookie on the user navigator, from the Drupal script.
You'll need to send back to Drupal the SessionID from Magento, using this method (I think, you'll have to verify) :
$response['sessionId'] = $session->getEncryptedSessionId();
And inside the Drupal script, you'll have to record a new cookie with the Magento session information. Maybe you have to have a look at a working Magento cookie to see how it is defined and what is its name.
if ($response['status']=='success') {
...
setcookie('frontend', $response['sessionId'], time() + 3600 * 24 * 180, '/');
...
}
You'll probably have to declare, in the settings of Magento, the path for cookies at '/'.
Can you give an example of the structure of the session cookie from Magento ?

Wordpress: Conditionally show stripped tag or post title. "Array" gets printed

What I'm trying to achieve:
Show either the post tag (without the link) or the title.
If a tag exists, that gets printed if it doesn't, the title gets used.
Issue: I've used get_the_tags() as suggested in the Codex to get the tag without the link and that works, yet it gets the word "Array" printed as a preffix, too.
<?php
if( has_tag() )
{
echo $posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
}
}
else { echo the_title(); };
?>
What am I missing?
You are echo ing $posttags which is an array. If you echo an array it will echo array as output
<?php
if( has_tag() )
{
This is printing Array as prefix ----> echo $posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
}
}
else { echo the_title(); };
?>
Please remove that echo , so your new code will be
<?php
if( has_tag() )
{
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
}
}
else { echo the_title(); };
?>
Hope this helps you

File upload does not work on cakePHP 2.x

I am trying to upload the user pictures, but with the following example nothing is getting saved into the database and no errors are given. I know that the validation has to be done and it will once I get the files to be stored.
Here are the snippets from the view file:
<?php
echo $this->Form->create('User', array('enctype' => 'multipart/form-data'));
echo $this->form->input('upload', array('type' => 'file'));
echo $this->Form->end('Submit');
?>
The controller:
public function add() {
if ($this->request->is('post')) {
if(!empty($this->data['User']['upload']['name'])){
$file = $this->data['User']['upload'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/users/' . $file['name']);
$this->data['User']['image'] = $file['name'];
}
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('The employee has been saved');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('The employee could not be saved. Please, try again.');
}
}
}
change your view like this
<?php echo $this->Form->file('Document.submittedfile'); ?>
and your controller like this
public function fileupload() {
if ($this->request->is('post') || $this->request->is('put')) {
//die();
$file = $this->request->data['Document']['submittedfile'];
//$this->pdfadd1->save($this->request->data);
move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/cakephp3/cakephp1/cakephp/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Thanks for the submission'));
return $this->redirect(array('controller' => 'users','action' => 'index'));
}
}
dnt forget to create a folder in webroot or in any other place(for uploaded files)
Check the following link :
http://www.jamesfairhurst.co.uk/posts/view/uploading_files_and_images_with_cakephp
public function uploadFilesIphone($folder, $formdata, $replace , $itemId = null) {
// setup dir names absolute and relative
$folder_url = WWW_ROOT.$folder;
$rel_url = $folder; //echo
// create the folder if it does not exist
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
// if itemId is set create an item folder
if($itemId) {
// set new absolute folder
$folder_url = WWW_ROOT.$folder.'/'.$itemId;
// set new relative folder
$rel_url = $folder.'/'.$itemId;
// create directory
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
}
// list of permitted file types, this is only images but documents can be added
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png','application/octet-stream');
// loop through and deal with the files;
$key = array();
$value = array();
foreach($formdata as $key => $value)
{
if($key == is_array($value))
{
$filename = str_replace(".", $replace , $value['name']);
}
// replace spaces with underscores
// assume filetype is false
$typeOK = false;
// check filetype is ok
foreach($permitted as $type)
{
if($key == is_array($value))
{
if($type == $value['type'])
{
$typeOK = true;
break;
}
}
}
// if file type ok upload the file
if($typeOK) {
// switch based on error code
if($key == is_array($value))
{
switch($value['error'])
{
case 0:
// check filename already exists
if(!file_exists($folder_url.'/'.$filename))
{
// create full filename
$full_url = $folder_url.'/'.$filename;
$url = $rel_url.'/'.$filename;
// upload the file
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
else
{
// create unique filename and upload file
// ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$full_url = $folder_url.'/'.$now.$filename;
$url = $rel_url.'/'.$now.$filename;
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
// if upload was successful
if($success)
{
// save the url of the file
$result['urls'][] = $url;
}
else
{
$result['errors'][] = "Error uploaded $filename. Please try again.";
}
break;
case 3:
// an error occured
$result['errors'][] = "Error uploading $filename. Please try again.";
break;
default:
// an error occured
$result['errors'][] = "System error uploading $filename. Contact webmaster.";
break;
}
}
elseif($value['error'] == 4)
{
// no file was selected for upload
$result['nofiles'][] = "No file Selected";
}
else
{
// unacceptable file type
$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
}
}
}
return $result;
}

JRequest::getVar is keeping previous values even after refreshing

I am writing a mail function as a module in joomla 3. e mail works fine, but when i reload the page and insert a different email and send, but it seemed to return the previous email by JRequest::getVar function. Is there a way to solve this issue? thanks in advance..
this is the code i used:
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DS . 'helper.php');
//declaration
$input = JFactory::getApplication()->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
echo '<script>
var php_var = "chk is first:'.$email.'";
alert(php_var);
</script>';
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
echo '<script>
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);
</script>';
$input = JFactory::getApplication();//i have tried $app also
$input ->setUserState('mod_mycontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_myecontact', 'default_tmpl'));
}else{
require(JModuleHelper::getLayoutPath('mod_mycontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
#Mario this is the helper code:
class ModLittleContactHelper{
public function SendMail($email, $fname, $lname) {
$body = "<p style='font-family:arial;font-size:20px;'>Hi " . $fname . " " . $lname . ",</p>";
$body.="<p style='font-family:arial;font-size:20px;'>Welcome to Crowd Logistics! Please verify your email address below.</p><br/><br/>";
$body.= "<hr><br/>";
$body.= "<p style='align:center;background-color:#40B3DF;font-family:arial;color:#FFFFFF;font-size:20px;'><a href='http://suriyaarachchi.com/crowdlogistics/index.php?option=com_content&view=article&id=192' target='_blank'>Verify " . $email . "</a></p>";
$body.= "<br/><hr><br/>";
$body.="<p style='text-align:right;font-family:arial;font-size:20px;'>Or, paste this link into your browser:<br/>";
$body.= "http://crowdlogistics/index.php?option=com_content&view=article&id=192<br/><br/>";
$body.= "Thanks.<br/>";
$body.= "CrowdLogistics</p><br/>";
$mailer = & JFactory::getMailer();
$mailer->setSender('info#crowdlogistics.com');
$mailer->addRecipient($email);
$mailer->setSubject('Mail from CrowdLogistics - Confirm your email');
$mailer->setBody($body);
$mailer->IsHTML(true);
$send = & $mailer->Send();
return $send;
}
Since you're trying to run your code on Joomla 3, there are a few things that are wrong. Below os your code, corrected where I was able to correct it. Now you have to test it in your module environment with the class being instantiated (in other words, test the below code in your module).
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'helper.php');
//declaration
$doc = JFactory::getDocument();
$app = JFactory::getApplication();
$input = $app->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
$doc->addScriptDeclaration('
var php_var = "chk is first:'.$email.'";
alert(php_var);
');
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
$doc->addScriptDeclaration('
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);');
$app->setUserState('mod_littlecontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
break;
}else{
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
First, JRequest class is deprecated in J3. You should use JInput:
$input = JFactory::getApplication()->input;
$your_var = $input->get('your_var');
Then, regarding the email, you probably need to unset the session variables when the success is achieved (mail sent), or in other words, when you don't need them any longer.
$app = JFactory::getApplication();
// your_var is the variable you want to unset
$app->setUserState('mod_your_module.your_var', null);
Hope it helps
you can use this code
$email = $input->get('email', 0 , 'STRING','');
4th argument for the default value,

Resources