In yii how to send password reset link - yii

In yii i am creating forget password functionality.For this user enters email id.If this email id is correct then i want to retrieve securityQuestion id from database and display that question to user.if his answer is correct then password reset link will get send to user's email id. In controller i had made action as
public function ActionForget{if(isset($_POST['email']))
{ $record=User::model()->find(array(
'select'=>'primaryEmail',
'condition'=>'PrimaryEmail=:email',
'params'=>array(':email'=>$_POST['email']))
); if($record===null) {
$error = 'Email invalid';
} else {
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
$mailer->IsSMTP();
$mailer->IsHTML(true);
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "ssl";
$mailer->Host = "smtp.gmail.com";
$mailer->Port = 465;
$mailer->CharSet = 'UTF-8';
$mailer->Username = "abc#shailani.com";
$mailer->Password = "abc";
$mailer->From = "xyz#shailani.com";
$mailer->FromName = "Balaee.com";
$mailer->AddAddress($record);
$mailer->Subject = "welcome to Balaee";
$mailer->IsHTML(true);
$mailer->Body = "<h1>Thanks to showing interest </h1><br>click on link for other detail ".$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($mailer->Send()) {echo "Please check mail";}
else {echo "Fail to send your message!"; }}}
else{ $this->render('emailForm'); //show the view with the password field}}
I am having password.php as view file for entering primary email id and submit button
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'email-form',
'enableClientValidation'=>true,
));
echo CHtml::textField('email');
echo CHtml::submitButton('Send');
$this->endWidget();
But after submiiting primary email id by user,no action takes place. So can please someone tell me what changes i need to do

Shouldn't the name of the controller method be actionForgot instead of ActionForgot. PHP is case sensitive, also when you render the page send the model with it like this->render->('emailForm',$email) where $email is your model name

Ok I like the start, and here are some of the fixes to the existing code above.
However what was your plan once you successfully sent the e-mail; see the existing code gets you a url that looks like this http://yoursite.com/yourapp/user/forget and that will bring you right back to the form in which you enter your email, thus creating a giant loop.
See the link should in fact create be validated and thus giving the user access to their user record. You need some other function to validate and allow for the password change.
<code>
public function actionForget() {
if(isset($_POST['email'])) {
$record=User::model()->findByAttributes(array('email' => Yii::app()->request->getPost('email')));
if ($record != NULL) {
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
$mailer->IsSMTP();
$mailer->IsHTML(true);
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "ssl";
$mailer->Host = "smtp.gmail.com";
$mailer->Port = 465;
$mailer->CharSet = 'UTF-8';
$mailer->Username = "yourgmailacccount#gmail.com";
$mailer->Password = "P#ssWord";
$mailer->From = "yourfromemail#yourdomain.com";
$mailer->FromName = "HQ-DEV-01";
$mailer->AddAddress($_POST['email']);
$mailer->Subject = "welcome to CES Document Site";
$mailer->IsHTML(true);
$mailer->Body = "<h1>Thanks, please</h1><br>
click on link for other detail
".$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($mailer->Send()) {
echo "Please check your email";
}
else {
echo "Fail to send your message!";
}
} else {
echo 'Email invalid';
}
else {
$this->render('password');
Yii::app()->user->setFlash('error', "Email is not valid!");
//echo 'Email invalid';
}
}
else{ $this->render('password'); //show the view with the password field}}
Yii::app()->user->setFlash('info', "Enter a valid e-mail!");
}
}

Related

how to update customer email from another form in prestashop

I am validating mobile number and retrieving customers email address and allowing customers to change the emaill address in that form and now I need to update the email address how to do this from my custom controller, ie how to call the Customer class and update my email address in prestashop
elseif (Tools::isSubmit('update_email')) {
$otp_mobile_num = trim(Tools::getValue('otp_mobile_num'));
$update_email = Tools::getValue('update_email_address');
$old_email = Tools::getValue('old_email_address');
//d($otp_mobile_num);
if($old_email!= $update_email) {
//d($update_email);
// Checked the email address is already in use, in case he changed his email address
if (Validate::isEmail($update_email) && !empty($update_email)) {
if (Customer::customerExists($update_email)) {
$this->errors[] = Tools::displayError('An account using this email address :('.$update_email.') has already been registered.', false);
}
}
} else {
$this->errors[] = Tools::displayError('You must change the email address!');
}
}
Below is my seperate form :
You can try updating directly the Context Customer:
elseif (Tools::isSubmit('update_email')) {
$otp_mobile_num = trim(Tools::getValue('otp_mobile_num'));
$update_email = Tools::getValue('update_email_address');
$old_email = Tools::getValue('old_email_address');
//d($otp_mobile_num);
if($old_email!= $update_email){
//d($update_email);
// Checked the email address is already in use, in case he changed his email address
if (Validate::isEmail($update_email) && !empty($update_email)) {
if (Customer::customerExists($update_email)) {
$this->errors[] = Tools::displayError('An account using this email address :('.$update_email.') has already been registered.', false);
} elseif(Context::getContext()->customer->id == null) {
$this->errors[] = Tools::displayError('You must be logged in');
} else {
Context::getContext()->customer->email = $update_email
if(Context::getContext()->customer->save()) {
// Customer updated correctly
} else {
$this->errors[] = Tools::displayError('An error occured');
}
}
}
}else{
$this->errors[] = Tools::displayError('You must change the email address!');
}
}

change password code is not working

I was just working on a password changing program for my website, it resulted in all my users passwords changed into the same password.
The code which I used is displayed below.
If any one could help me out it would be a big thanks to him/her.
//if form has been submitted process it
<br/>
if(isset($_POST['submit'])){
$stmt = $db->prepare('SELECT password FROM user WHERE password = :hashedpassword');
$stmt->execute(array(':hashedpassword' => $_POST['password']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(strlen($_POST['password']) < 3){
$error[] = 'Password is too short.';
}
if(strlen($_POST['passwordConfirm']) < 3){
$error[] = 'Confirm password is too short.';
}
if($_POST['password'] != $_POST['passwordConfirm']){
$error[] = 'Passwords do not match.';
}
//if no errors have been created carry on
if(!isset($error)){
//hash the password
$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
try {
//insert into database with a prepared statement
$sql="UPDATE user SET password = :hashedpassword";
$stmt = $db->prepare($sql);
$stmt->execute(array(
':hashedpassword' => $hashedpassword
));
//redirect to index page
header('Location: login.php?action=resetAccount');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}

In yii login functionality when password is wrong

In yii i am creating login functionality. When user enters correct username but wrong password i want to make serach in database for this correct username and want to put that username's id into loginattemmpt table and display wrong password message to him. So can please someone help me.
in userIdentity.php save data in table .
public function authenticate() {
$user = User::model()->findByAttributes(array('username' => $this->username));
if ($user === null) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
}
elseif($user->password !== crypt($this->password, $salt))
{ // save $user->id in attempt table here .
$this->errorCode = self::ERROR_PASSWORD_INVALID;
}else{
//set id
}
and in file from where authenticate function is called setError.
$this->_identity = new UserIdentity($this->username, $this->password);
if (!$this->_identity->authenticate())
if ($this->_identity->errorCode === UserIdentity::ERROR_USERNAME_INVALID) {
$this->addError('password', 'Incorrect email Id');
}elseif($this->_identity->errorCode === UserIdentity::ERROR_PASSWORD_INVALID){
$this->addError('password', 'Incorrect Password');
}

Joomla onUserAuthenticate

In the Joomla source, I found a method caled onUserAuthenticate, which could not be found in the API (through google), but its functionality is the similar to onLoginUser... So, after login/password check I need to run some more code via this function. As a result, I have true/false - depending on it I need to set users' authorization completely. Even if the user's login/password is correct, but my code returns false -> authorization fail...
I am trying something like:
functionon UserAuthenticate($credentials,$options,&$response){
jimport('joomla.user.helper');
$username=mysql_real_escape_string($credentials['username']);
$password=mysql_real_escape_string(md5($credentials['password']));
//my code returns $result
if($result!=NULL){
$response->status=JAUTHENTICATE_STATUS_SUCCESS;
$response->error_message='';
}
else{
$response->status=JAUTHENTICATE_STATUS_FAILURE;
$response->error_message=JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
}
onUserAuthenticate is an event not a method. You use plugins to listen for Joomla events, in this case usually a user plugin would listen for this. When the event happens your code will run.
http://docs.joomla.org/Plugin
You can try this for custom login form-
$app = JFactory::getApplication();
$data = array();
$data['return'] = '';
$data['username'] = JRequest::getVar('username', '', 'method', 'username');
$data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
// Get the log in options.
$options = array();
// Get the log in credentials.
$credentials = array();
$credentials['username'] = $data['username'];
$credentials['password'] = $data['password'];
// Perform the log in.
$error = $app->login($credentials, $options);
if (!JError::isError($error)) {
$response->status=JAUTHENTICATE_STATUS_SUCCESS;
$response->error_message='';
}else{
$response->status=JAUTHENTICATE_STATUS_FAILURE;
$response->error_message=JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
If you want authenticate solution on function "onUserAuthenticate" you should check it yourself if user credential is valid or not And you do it with this code :
function onUserAuthenticate($credentials, $options, &$response)
{
$response->type = 'Joomla';
// Joomla does not like blank passwords
if (empty($credentials['password'])) {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED');
return false;
}
// Initialise variables.
$conditions = '';
// Get a database object
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, password');
$query->from('#__users');
$query->where('username=' . $db->Quote($credentials['username']));
$db->setQuery($query);
$result = $db->loadObject();
if ($result) {
$parts = explode(':', $result->password);
$crypt = $parts[0];
$salt = #$parts[1];
$testcrypt = JUserHelper::getCryptedPassword($credentials['password'], $salt);
if ($crypt == $testcrypt) {
$user = JUser::getInstance($result->id); // Bring this in line with the rest of the system
$response->email = $user->email;
$response->fullname = $user->name;
$response->status = JAuthentication::STATUS_SUCCESS;
$response->error_message = '';
print_r("You login correct Sir");
die();
} else {
print_r("you enter wrong credential");
die();
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_INVALID_PASS');
}
} else {
print_r("you enter blank credential");
die();
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_NO_USER');
}
return true;
}

Login with Kohana auth module - what am I doing wrong?

I'm trying to login with the following controller action, but my login attempt keeps failing (I get the 'invalid username and/or password' message). What am I doing wrong? I also tried the other method given in the examples in the auth documentation, Auth::instance()->login($user->username, $form->password);, but I get the same result. Kohana version is 2.3.4.
public function login() {
$auth = Auth::instance();
if ($auth->logged_in()) {
url::redirect('/account/summary');
}
$view = new View('login');
$view->username = '';
$view->password = '';
$post = $this->input->post();
$form = new Validation($post);
$form->pre_filter('trim', 'username')
->pre_filter('trim', 'password')
->add_rules('username', 'required');
$failed = false;
if (!empty($post) && $form->validate()) {
$login = array(
'username' => $form->username,
'password' => $form->password,
);
if (ORM::factory('user')->login($login)) {
url::redirect('/accounts/summary');
} else {
$view->username = $form->username;
$view->message = in_array('required', $form->errors()) ?
'Username and password are required.' :
'Invalid username and/or password.';
}
}
$view->render(true);
}
Figured out my problem... Something in my registration process is missing, because it's creating the user record but not the role-to-user assoc record. Login needs a specific role to log in to, or it won't work even with a valid username and password. Manually inserting the record allowed my to log in, so I'll just have to debug my registration action a bit.