parameter mismatch,pattern is a string while replacement is an array - laravel

Trying to resend login details to a user through his mail.what I want to do is after the user has click on the forgotten password link, a form is displayed requesting for his email to be posted.after the email has been posted, I check if the email corresponds to an email in the users table and send details.
Here's my controller:
public function postResendPassword()
{
$posted = Input::get();
$email = $posted['email'];
$user = User::where('email', '=', $email)->first();
$user_password= $user->password_confirmation;
$user_username = $user->username;
$user_email = $user->email;
$to = $user->email;
$subject = " login details request";
$message =
<h3>login details</h3>
email : $user_email
login password : $user_password
regards;
mail($to, $subject, $message);
}
how do I go about this and fix this error

Related

Welcome email with create password link in laravel7

I'm creating an one form where the admin register the new users and then an email is sent to this new user with a welcome message and a link to create a new password.
This last part I'm having problems as I can't find info on how to generate the token and the link.
This link should redirect the user to a create password page, which is different than the reset password.
Thanks !
Below is my add user controller:
public function contactSave(Request $request)
{
$token = $request->_token;
$user= new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $password;
$user->save();
if($user->id)
{
$CustomerContact= new CustomerContact;
// $CustomerContact->name = $request->name;
// $CustomerContact->email = $request->email;
$CustomerContact->phone = $request->phone;
$CustomerContact->address = $request->address;
$CustomerContact->user_id = $user->id;
$CustomerContact->country_id = $request->country;
$CustomerContact->state_id = $request->state;
$CustomerContact->comment = $request->comment;
$CustomerContact->organization = $request->organization;
$CustomerContact->captcha = $request->captcha;
$CustomerContact->save();
$details = [
'title' => 'Hi '.$request->name.'',
'body' => 'Your account has been created successfully. Request you set your password with this link',
// 'link' => URL::route('password/reset/'.$token)
];
\Mail::to($request->email)->send(new \App\Mail\ContactMail($details));
}
return redirect('contacts')->with('success', 'User created successfully.');
}
Current I am just sending mail to user mail id. I am not getting how to send password reset (password set link) url into that mail.
On that link click forgeot password form open and user can reset there passowrd.
Anyone idea then let me know.

How to reset Password Using PHP Codeigniter

Am working on a Password reset system whereby the user who forgot his password can request for password reset link by submitting his email used in registration. I successfully create the email, it sent the link and I test the link by clicking on it. The link went through and load the reset page but my problem is how to make the system recognise the user who click through and get all the details including Name, Token, email with which the system will confirm that the user is the user who requested the link.
The following is what I have done so far:
Controller
public function preset(){
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_error_delimiters("<div class='alert alert-warning'><span type='button' class='close' data-dismiss='alert'>&times</span>","</div>");
if($this->form_validation->run() == false){
$this->load->view('passwordrecovery.php', $data);
}
else{
$eMail = $this->input->post('email');
$this->db->where("email = '$eMail'");
$this->db->from("useraccount");
$countResult = $this->db->count_all_results();
if($countResult >=1){
// $data['firstName'] = '';
// $data['lastName'] = '';
$this->db->where("email = '$eMail'");
$getUserData =$this->db->get("useraccount")->result();
foreach($getUserData as $userD){
$data['firstName'] = $userD->firstname;
$data['lastName'] = $userD->lastname;
}
$sender_email = 'xxx#gmail.com';
$user_password = 'xxxxxx';
$token = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 50);
$subject = 'Password Reset';
$message = '';
$message .= "<h2>You are receiving this message in response to your request for password reset</h2>"
. "<p>Follow this link to reset your password <a href='".site_url()."/authenticate/resetpassword/.$token' >Reset Password</a> </p>"
. "<p>If You did not make this request kindly ignore!</p>"
. "<P class='pj'><h2>Kind Regard: Votemate</h2></p>"
. "<style>"
. ".pj{"
. "color:green;"
. "}"
. "</style>"
. "";
// Configure email library
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = $sender_email;
$config['smtp_pass'] = $user_password;
$config['mailtype'] = 'html';
// Load email library and passing configured values to email library
$this->load->library('email', $config);
//$this->email->set_newline("rn");
$this->email->set_mailtype("html");
// Sender email address
$this->email->from($sender_email);
// Receiver email address
$this->email->to($eMail);
// Subject of email
$this->email->subject($subject);
// Message in email
$this->email->message($message);
if ($this->email->send()) {
$eMail = $this->input->post('email');
$ipadd = $this->input->ip_address();
$insert = array(
'email' => $eMail,
'ipaddress' => $ipadd,
'token' => $token
);
$this->db->insert('passwordreset', $insert);
$mail = $this->session->set_userdata('email');
$data['success'] = 'Email Successfully Send !';
$this->load->view('linksent.php', $data);
} else {
$data['error'] = '<p class="error_msg">Invalid Gmail Account or Password !
</p>';
}
$this->load->view('passwordrecovery.php', $data);
}
if($countResult <= 0){
//user already registered
$data['error'] = "<div class='alert alert-warning'> Invalid
email address<span type='button' class='close' data-
dismiss='alert'>&times</span></div>";
$this->load->view('passwordrecovery.php',$data);
}
}
}
View
<div>
<h1>Password Recovery</h1>
<h3>Enter your email to receive the password reset link in
your Inbox</h3>
<br/>
<?php echo form_open('authenticate/preset');?>
<?php echo $error;?>
<div class="form-group">
<input type="text" name="email" required="required">
</div>
<div class="form-group">
<input type="submit" value="Send" class="btn-success
btn" >
</div>
<?php echo form_close()?>
<br/><br/><br/>
</div>
Database: The following is database where I store the info:
CREATE TABLE `passwordreset` (
`resetid` int(11) NOT NULL,
`email` varchar(150) NOT NULL,
`ipaddress` varchar(25) NOT NULL,
`token` varchar(512) NOT NULL
) ENGINE
The help I need is how to get the details (Name, email, token) of the user who click the link from his email and use it to validate and also use it to update his password. Thanks
pass user email or token in url or in hidden field when user click on verify link and check in controller method.
<a href="<?=site_url('user_verification?user_email=' . $user_email . '&user_code=' . $user_code);?> Click To Verifiy Email </a>
user_verification controller
public function user_verification_get()
{
$user_email = $this->input->get('user_email');
$user_code = $this->input->get('user_code');
$data=$this->admin_model->user_verification($user_email,$user_code);
if($data)
{
$data['message'] = 'Success.';
}
else
{
$data['message'] = 'Not Valid User.';
}
$this->load->template('verify', $data);
}
Model
public function user_verification($user_email,$user_code){
$this->db->select('user_email');
$this->db->where('user_email',$user_email);
$this->db->where('user_code',$user_code);
$query = $this->db->get('users');
if($query->row_array() > 0)
{
$data['user_isactive'] = true;
$this->db->where('user_email',$user_email);
$this->db->update('users',$data);
return $query->row_array();
}
return false;
}
You have to create a database table to store the tokens. Before sending the email, You must generate a unique token and add it into a separate table. The password reset link must contain encoded token and userID. Once the password reset link is clicked, you must check the encoded token and UserID in the link matches to the entry in database? If yes, then show the change password page, If not, you must show a message "Link is expired" or whatever.
Here is the hint of code from my project.
$act_code = md5(rand(0,1000).'uniquefrasehere');
$activate['UserID'] $USERID;
$activate['TokenNumber'] = $act_code;
$activate['UserEmail'] = $email;
$activate['TokenTime'] = time();
$str_tmp = $this->db->insert_string('forgetpasswordtoken', $activate);
$query_tmp = $this->db->query($str_tmp);
Once the link is clicked, You must check using the following code:
$record = $this->user_model->checkforgot($uid[0], base64_decode($uid[1]));
if($record == true){
$data['uid'] = $uid[1];
}
else
{
$msg = "You have already changed your password or your link was expired.!";
}
And What the checkforgotpassword function does? Here is below:
function checkforgot($token, $id)
{
$qry = $this->db->query("SELECT * FROM forgetpasswordtoken WHERE TokenNumber = '".$token."' AND UserID = $id");
$num_row = $qry->num_rows();
if($num_row!=0)
{
$del = $this->db->delete('forgetpasswordtoken', array('TokenNumber' => $token, 'UserID' => $id));
return true;
}
else
{
return false;
}
}
You can further add the time limit of few hours before the link expires.
Let me know after adding this in your project.
Thanks,

Change password for logged in user (codeigniter)

Is there any solution how to make change password for logged in user? i want to make a change password for logged in user, the code i made only change user password with user id number 1. it doesn't change for logged in user. so any idea?
this is my controller:
public function update(){
$this->form_validation->set_rules('password', 'Current Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('newpass', 'New Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confpassword', 'Confirm Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
if($this->form_validation->run()){
$cur_password = $this->input->post('password');
$new_password = $this->input->post('newpass');
$conf_password = $this->input->post('confpassword');
$this->load->model('queries');
$userid = '1';
$passwd = $this->queries->getCurrPassword($userid);
if($passwd->password == $cur_password){
if($new_password == $conf_password){
if($this->queries->updatePassword($new_password, $userid)){
echo 'Password updated successfully';
}
else{
echo 'Failed to update password';
}
}
else{
echo 'New password & Confirm password is not matching';
}
}
else{
echo'Sorry! Current password is not matching';
}
}
else{
echo validation_errors();
}
This is my model:
public function getCurrPassword($userid){
$query = $this->db->where(['id'=>$userid])
->get('users');
if($query->num_rows() > 0){
return $query->row();
} }
public function updatePassword($new_password, $userid){
$data = array(
'password'=> $new_password
);
return $this->db->where('id', $userid)
->update('users', $data); }
You can initialize a session when the user logs in to the system at the beginning, and store the information of the user in that session, like this:
function login() {
$query = $this->db->select(*)
->from('table_name')
->where('your parameters....');
return $query->row();
}
function index() {
$userid = $this->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('current_userId', $userid);
}
You have now stored the id of currently logged IN user in the session. You can access the id by $this->session->userdata('current_userId');. Replace your $userid = '1' by the session data. Also, you will have to load the session library in order to do so.

resetting password in codeigniter

i'm new to codeigniter, and i am attempting to create a password reset system
this is my controller:
public function changePassword(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
$data['title'] = 'Change my Password | Watch Stop';
$this->load->view('template/header', $data);
$this->load->view('watch_stop/vpassword', $data);
$this->load->view('template/footer');
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function reset_password(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
//validating form
$this->form_validation->set_rules('old_password','Old Password','trim|required|min_length[5]|md5');
$this->form_validation->set_rules('new_password','New Password','trim|required|min_length[5]|matches[cnew_password]|md5');
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
if ($this->form_validation->run() == FALSE)
{
$this->changePassword();
//$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Failed to update password</div>');
}else {
$query=$this->customer_model->change_password();
$data = array( "main_content" => 'includes/memberadmin/memberadmin_cpass_process',
"query" => $query
);
$this->load->view('includes/memberadmin/template',$data);
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
this is my model:
function change_password(){
$this->db->select('id');
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('password',$this->input->post('old_password'));
$query=$this->db->get('user');
if ($query->num_rows() > 0)
{
$row = $query->row();
if($row->email===$this->session->userdata('email'))
{
$data = array(
'new_password' => $this->input->post('new_password')
);
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('new_password',$this->input->post('old_password'));
if($this->db->update('user', $data))
{
return "Password Changed Successfully";
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Wrong Old Password";
}
}
When i click on the update button in my reset password page, i am getting the following error for my new password confirmation field: Unable to access an error message corresponding to your field name Confirm Password.()
please help!
1) there are two pipe signs near required||md5
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
change it to
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required|md5');
2) changing input to md5 at this stage is not good.
You have to use password_hash function.
Read More >> http://php.net/manual/en/function.password-hash.php
3) You forgot to load model. $this->load->model('customer_model');

Using Google ReCaptcha

I am keen on using Google ReCaptcha. I have got the captcha on the page using the public key but don't know how to use the private key in my form processor document:
<?php
//SMTP SETTINGS
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.webhost.co.nz'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ‘xxxxx#xxxxxxxx.co.nz'; // SMTP username
$mail->Password = ‘xxxxx##xxxxxx’; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->Port = 465;
$mail->isHTML(true); // Set email format to HTML
//SMTP SETTINGS
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
print_r($_POST);
$mailheader = "From: $email";
$to = "tony#finelinecreative.co.nz"; // Here is email send to
$subject = "Finelinecreative Enquiry";
$message = "Name: $name<br/>Email: $email<br/>Message: $message";
// Send the mail
$mail->From=$mail->Username;
$mail->FromName = 'finelinecreative';
$mail->addAddress($to);
$mail->addReplyTo($email, $email);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->IsHTML(true);
$result = $mail->send();
header('location: http://www.finelinecreative.co.nz/index.php/thanks');
?>
Ideas please?
There's a great tutorial at https://codeforgeek.com/2014/12/google-recaptcha-tutorial/ that explains it pretty well.
In essence, you're checking if the $_POST variable 'g-recaptcha-response' exists (which, by including recaptcha on your form, is sent along with the other values on the form). If it is, you send a file_get_contents call (sending the secret key, the g-recaptcha-response POST value, and the user's IP address). You decode the result of that (which is sent as JSON, and you probably want to access it as key-value pairs), and find out whether the query was successful.
This is the relevant portion of their implementation.
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>You are spammer ! Get the #$%K out</h2>';
} else {
// Send the email. In your case, you can wrap pretty all of your preprocessor in this.
}

Resources