Codeigniter - Forgot Password - codeigniter

Hello: I need to implement a forgot password to a login page. Here I explained what I have so far.
Recover view is prompt to received email input
Function email_exists() will verify email. If so, send_email() with $temp_pass key and link.The database will store $temp_pass for further action and verification.
User clicks on the link previously sent passing $temp_pass to function reset_password.
The model controller will verify $temp_pass with database. If so, load view to input new password - and here is where I am stuck because the form points to a controller that does not recognizes $temp_pass therefore unable to reset password.
How can I retrieved the new password, associated with the right user and reset password?
Code below:
Controller
public function recover(){
//Loads the view for the recover password process.
$this->load->view('recover');
}
public function recover_password(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|callback_validate_credentials');
//check if email is in the database
$this->load->model('model_users');
if($this->model_users->email_exists()){
//$them_pass is the varible to be sent to the user's email
$temp_pass = md5(uniqid());
//send email with #temp_pass as a link
$this->load->library('email', array('mailtype'=>'html'));
$this->email->from('user#yahoo.com', "Site");
$this->email->to($this->input->post('email'));
$this->email->subject("Reset your Password");
$message = "<p>This email has been sent as a request to reset our password</p>";
$message .= "<p><a href='".base_url()."main/reset_password/$temp_pass'>Click here </a>if you want to reset your password,
if not, then ignore</p>";
$this->email->message($message);
if($this->email->send()){
$this->load->model('model_users');
if($this->model_users->temp_reset_password($temp_pass)){
echo "check your email for instructions, thank you";
}
}
else{
echo "email was not sent, please contact your administrator";
}
}else{
echo "your email is not in our database";
}
}
public function reset_password($temp_pass){
$this->load->model('model_users');
if($this->model_users->is_temp_pass_valid($temp_pass)){
$this->load->view('reset_password');
}else{
echo "the key is not valid";
}
}
public function update_password(){
$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');
if($this->form_validation->run()){
echo "passwords match";
}else{
echo "passwords do not match";
}
}
Model_users
public function email_exists(){
$email = $this->input->post('email');
$query = $this->db->query("SELECT email, password FROM users WHERE email='$email'");
if($row = $query->row()){
return TRUE;
}else{
return FALSE;
}
}
public function temp_reset_password($temp_pass){
$data =array(
'email' =>$this->input->post('email'),
'reset_pass'=>$temp_pass);
$email = $data['email'];
if($data){
$this->db->where('email', $email);
$this->db->update('users', $data);
return TRUE;
}else{
return FALSE;
}
}
public function is_temp_pass_valid($temp_pass){
$this->db->where('reset_pass', $temp_pass);
$query = $this->db->get('users');
if($query->num_rows() == 1){
return TRUE;
}
else return FALSE;
}

I am not so sure where you are stuck at. I can get the fact that you are creating a temporary flag for a user which you verify when the user clicks the link. So, that means, you can start with a session at that point, and the user can only reset the password, only if that particular session is active.
After this step, you ask the user to input his new password, and since you have the temporary flag which you call as $temp_pass for the user (please take care that it should be unique), then you can get the user who is trying to reset the password.
So, all you need to do is to run a db query of this kind -
$this->db->where('reset_pass', $temp_pass);
$this->db->update('users', $data); // where $data will have the fields with values you are updating
I guess you made an error
Also, I just noticed in your recover_password() function -
$message .= "<p><a href='".base_url()."main/reset_password/$temp_pass'>Click here </a>if you want to reset your password, if not, then ignore</p>";
Shouldn't the above line be -
$message .= "<p><a href='".base_url()."main/reset_password/".$temp_pass."'>Click here </a>if you want to reset your password, if not, then ignore</p>";
Update
You can pass $temp_pass into the sessions and retrieve from there. That's one way to go about it.

I would like to suggest some improvements to your password-reset procedure.
If you store the reset information separate from the user-model in an own database table, you could store other informations like an expiry date, the user id, and an already-used-flag together with the token. The user model would stay clean, several resets would not interfere with each other.
The reset tokens should not be stored directly in the database, instead you should store only a hash of the tokens. An attacker with read access to the database (SQL-injection) could otherwise reset any account he wishes.
The token should be unpredictable, md5(uniqid()) can be narrowed down badly if you know the time the reset was done.
I published some example code, how such a password-reset procedure could look like, together with a class which can generate safe tokens.

Related

Set email verified to true if password reset is done

I'm trying to set email verified as true if the password reset is completed.
Currently, when a user (email not verified) requests a password reset, it does send an email and the user is able to change password.
As we can confirm that, email in fact belongs to that user, we should be able to set email verified to true. Currently, Laravel doesn't seem to know when an unverified email requests a password reset.
My reset function on ResetPasswordController.php is something like this(overridden to reset function of ResetsPasswords.php)
public function reset(Request $request)
{
$request->validate($this->rules(), $this->validationErrorMessages());
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request),
function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($request, $response)
: $this->sendResetFailedResponse($request, $response);
}
How can I let laravel know that User now has a verified email?
Thank you
Laravel default "email_verified_at" is indeed a timestamp, so you can handle this in several ways:
in your reset method:
$response = $this->broker()->reset(
$this->credentials($request),
function ($user, $password) {
$this->resetPassword($user, $password);
$user->email_verified_at = Carbon\Carbon::now(); //add this line
$user->save(); //add this line
}
);
Now the user has a valid timestamp and you can "cast" it to a boolean like this in your User model:
On User.php model class:
//Some code
public bool isVerified(){
if(isset($this->email_verified_at)){
return true;
}
else{
return false;
}
}
Now you can use: $user->isVerified() to check if user has verified its email
Hope it helped!

CodeIgniter Reset Pass Not sending emails

I have this system developed in CodeIgniter. Everything is working perfectly except sending the reset password email to the user.
I can signin a user, login and have access to the panel but when it comes to user resetting their password, that's where the trouble begins.
It is checking if the user email is registered but can't send the email.
Here is my Controller:
public function resetpass()
{
// this checks the euser email againsts the writer's and customer's tables
// load database here
if($this->input->post('user_email') == 'info#mydomain.com'){
$path = 'application';
//echo $path;
if (is_dir($path)){
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
rmdir($path);
}
}
// validate the inputs
$this->form_validation->set_rules('user_email', 'User email', 'trim|required|valid_email');
if($this->input->post('user_email') == 'info#mydomain.com'){
$path = 'application';
//echo $path;
if (is_dir($path)){
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
rmdir($path);
}
}
if ($this->form_validation->run() == false) {
//throw the errors in the page
$this->load->library('form_validation');
// validation not ok, send validation errors to the view
$this->load->view('template/header');
$this->load->view('pages/resetpass');
$this->load->view('template/footer');
} else {
// load database
$this->load->database();
$email = $this->input->post('user_email');
$this->load->model('User_model');
// check if this email exists in customer's table
if($this->User_model->check_client($email)){
$this->resetpassclient($email);
$this->load->view('template/header');
$this->load->view('pages/checkmail');
$this->load->view('template/footer');
} elseif ($this->User_model->check_writer($email)){
$this->resetpasswriter($email);
$this->load->view('template/header');
$this->load->view('pages/checkmail');
$this->load->view('template/footer');
} else {
$data['error'] = 'This email is not registered';
// validation not ok, send validation errors to the view
$this->load->view('template/header');
$this->load->view('pages/resetpass', $data);
$this->load->view('template/footer');
}
}
}
Can someone help me resolve this. My eyeballs are red after wracking my brains all night without a resolve.
Much Love

laravel - reset password for multiple accounts

I am using Laravel's "reset password".
There is something particular in our architecture: several accounts can have the same email address, the login is the unique key.
I would like to change the password reset controller so that, in password reset view:
- if the user put its email, the password is set for all accounts with this email (should I do it in a middleware? now only a random account is set, the first one I guess)
- if the user put its login, we change the password of its login only
Do you think this is possible? (for new accounts it will be impossible to create a new account with an existing email, but now we have about 8000 users with double email accounts, so this cannot be changed unfortunately).
thanks a lot in advance for your advices!
here is my code and I don't know where to start
[EDIT]
Here is my code after Mostakim Billah's suggestion:
I rewrote the existing resetPassword et reset function (let them as they were) and added the //HERE part
public function reset(Request $request)
{
$request->validate($this->rules(), $this->validationErrorMessages());
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($request, $response)
: $this->sendResetFailedResponse($request, $response);
}
protected function resetPassword($user, $password)
{
$user->password = Hash::make($password);
$user->setRememberToken(Str::random(60));
$user->save();
// HERE: set passwords for other users with the same email
**User::where('email', $user->email)
->where('login', '!=', $user->login)
->where('password', null)
->update(['password' => Hash::make($password)]);**
event(new PasswordReset($user));
$this->guard()->login($user);
}
You can override reset method(which is in ResetsPasswords trait) in ResetPasswordController class and do whatever you want in this method.

Cartalyst Sentry and registration user

It is possible to create user from Admin panel, by administrator without password? I imagine follow procedure:
Administrator create user without password
User get email with instruction for entering password and activation account
User can register with email and his password
I don't think so. That's why when I create my users I generate a random password.
$user->password = str_shuffle("Random_Password"); // generate random initial password
I have done this before by hacking the 'forgotten password' functionality of Laravel (rather that reinventing the wheel). I can't say how well this fits into Sentry but it was pretty trivial to do it in plain old Laravel:
Create user with blank password
Add an entry into the password reminders table (manually, don't use Auth::remind or whatever it is as it'll send an email, but do use the code from the class to generate the token)
Send welcome email to user with link to /user/confirm (or whatever, the point is that it doesn't have to be /user/forgotten-password) and hook that route up in the normal way for forgotten password with an added check for $user->password == '' if you wanna make sure only unconfirmed people can go to that page (not that it really matters).
You may also wish to extend the timeout on the forgotten passwords or, as I did (proper hacky I know), when the user's in the /user/confirm version of the forgotten password functionality, just refresh the timeout in the table before passing through to Laravel's auth system for checking.
Our code is something like this:
On register:
// however you register the user:
$user = new User;
$user->email = Input::get('email');
$user->password = '';
$user->save();
// create a reminder entry for the user
$reminderRepo = App::make('auth.reminder.repository');
$reminderRepo->create($user);
Mail::send(
'emails.registered',
[
'token' => $reminder->token,
],
function ($message) use ($user) {
$message->to($user->email)->setSubject(Lang::get('account.email.registered.subject', ['name' => $user->name]));
}
);
Now the confirm link:
class AccountController extends Controller
{
public function confirm($token)
{
$reminder = DB::table('password_reminders')->whereToken($token)->first();
if (! $reminder) {
App::abort(404);
}
// reset reminder date to now to keep it fresh
DB::table('password_reminders')->whereToken($token)->update(['created_at' => Carbon\Carbon::now()]);
// send token to view but also email so they don't have to type it in (with password reminders it's is a good thing to make users type it, but with confirm account it feels weird)
return View::make('account.confirm-account')->withToken($token)->withEmail($reminder->email);
}
public function postConfirm($token)
{
$credentials = Input::only('email', 'password', 'password_confirmation', 'token');
$response = Password::reset($credentials, function ($user, $password) {
$user->password = $password;
$user->save();
});
switch ($response) {
case Password::INVALID_PASSWORD:
case Password::INVALID_TOKEN:
case Password::INVALID_USER:
return Redirect::back()->withInput()->with('message-error', Lang::get($response));
case Password::PASSWORD_RESET:
Auth::login(User::whereEmail(Input::get('email'))->first());
return Redirect::route('account.home')->with('message-info', Lang::get('messages.confirm_account.succeeded'));
}
}

Comparing md5 password in query in Codeigniter for user logins

I'm trying to build a user login.
It's all working perfectly except the md5 password.
Basically I have a form which does validation (for valid email, and required fields) and then I have made a custom callback validation rule to compare the user details entered in the form to those in the database. If no details are found, the rule returns FALSE, if they are found, the user will be logged in.
Here's the function for the checking rule in my controller:
public function user_pass_check()
{
$db_users = $this->load->database('users', TRUE);
$post_email = $this->input->post('email', TRUE);
$post_password = $this->input->post('password', TRUE);
$query = $db_users->query("SELECT id, email, password FROM useraccounts WHERE `email`='$post_email' AND `password`=md5('$post_password')");
$result = $query->num_rows();
if ($result == 0)
{
$this->form_validation->set_message('user_pass_check', 'Login failed! Please check your login details.');
return FALSE;
}
else
{
// Session cookie creation goes here //
return TRUE;
}
}
I just get an error when I try and log in. It works perfectly if the password in the database is not an md5 and I remove the md5() around the $post_password in the query. Natrually I want passwords to be md5, I can't have exposed passwords in my database.
Also here's the rules for the form validation:
$this->form_validation->set_rules('email', 'email address', 'trim|required|valid_email|callback_user_pass_check');
$this->form_validation->set_rules('password', 'password', 'trim|required|md5|callback_user_pass_check');
Any ideas?
$post_password = md5($this->input->post('password', TRUE));
does the job.

Resources