Laravel 4 validator for password field in edit account - php

I need to check if a user has posted the same password as the one in the database. Field for old password is 'oldpass'. The custom validator i created is called 'passcheck'. It should fail or pass accordingly.
My UsersController code below doesnt work. What could have I have done wrong?
$rules = array(
'oldpass' => 'passcheck',
);
$messages = array(
'passcheck' => 'Your old password was incorrect',
);
Validator::extend('passcheck', function($attribute, $value, $parameters)
{
if(!DB::table('users')->where('password', Hash::make(Input::get('oldpass')))->first()){
return false;
}
else{
return true;
};
});
$validator = Validator::make($inputs, $rules, $messages);

You should use something like this,
$user = DB::table('users')->where('username', 'someusername')->first();
if (Hash::check(Input::get('oldpass'), $user->password)) {
// The passwords match...
return true;
}
else {
return false;
}
So, you have to get the record using username or any other field and then check the password.
#lucasmichot offered even shorter solution:
Validator::extend('passcheck', function ($attribute, $value, $parameters)
{
return Hash::check($value, Auth::user()->getAuthPassword());
});

I would make it like this:
/**
* Rule is to be defined like this:
*
* 'passcheck:users,password,id,1' - Means password is taken from users table, user is searched by field id equal to 1
*/
Validator::extend('passcheck', function ($attribute, $value, $parameters) {
$user = DB::table($parameters[0])->where($parameters[2], $parameters[3])->first([$parameters[1]]);
if (Hash::check($value, $user->{$parameters[1]})) {
return true;
} else {
return false;
}
});
This validator rule will make database query to check current user's password
You can make it even shorter and save query:
Validator::extend('passcheck', function ($attribute, $value, $parameters) {
return Hash::check($value, Auth::user()->getAuthPassword());
});

Please dont tie your rule to an Html element. Use the parameters Laravel provides to create your custom rules. This would be (asuming that you have a user authenticated):
Validator::extend('passcheck', function($attribute, $value, $parameters) {
return Hash::check($value, Auth::user()->password); // Works for any form!
});
$messages = array(
'passcheck' => 'Your old password was incorrect',
);
$validator = Validator::make(Input::all(), [
'oldpass' => 'passcheck',
// more rules ...
], $messages);

Related

Laravel validation difference between 2 dates

I need to check some special validation in my action store
public function store(Request $request) {
$this->validate($request, [
'practice'=>'required|max:100',
'project'=>'required',
'work_place'=>'required',
'telephone_1'=>'required',
'date_recurring_for_beginning' => 'required|date',
'date_recurring_for_end' => 'required|date|after_or_equal:date_recurring_for_beginning',
]);
RequestCollaborator::create($request->all());
return redirect()->route('requestsCollaborator.index')
->with('flash_message',
trans('request.request_created'));
}
I have to validate if the difference between date_recurring_for_beginning and date_recurring_for_end is 3 months?
there is any solution for doing this or I have to create a custom validation?
You can use Validator::extend() and can create your custom validation rule. Like
Validator::extend('valid_date_range', function ($attribute, $value, $parameters, $validator) {
$dateBeginning = \Carbon::createFromFormat('Y-m-d', $parameters[0]); // do confirm the date format.
$dateEnd = \Carbon::createFromFormat('Y-m-d', $value);
return $dateBeginning->diffInMonths($dateEnd) == $parameters[1];
});
You can use this like:
'date_recurring_for_end' => 'required|date|valid_date_range:date_recurring_for_beginning,3'
For more details about the custom validation. Please follow the documentation.
https://laravel.com/docs/5.8/validation
Create a custom validation rule within your app/Providers/AppServiceProvider:
public function boot()
{
Validator::extend('date_difference', function ($attribute, $value, $parameters, $validator) {
$firstDate = Carbon::parse($parameters[0]);
$secondDate = Carbon::parse($parameters[1]);
$minDifference = (int)$parameters[2];
if($firstDate->diffInMonths($secondDate) < $minDifference)
return false;
return true;
});
}
To use this rule:
$this->validate([
'some_field' => 'date_difference:date_one,date_two,3',
]);
Hope it helps.

update profile password laravel 5

I am working in laravel 5.1 and my update profile was working but will not encrypted and not working now.
When I try to update the user table will also password_confirmation field and causes a conflict in the database. I do not understand.
In the form says successfully but the database does not update any
Code
public function updatePassword() {
$passwordData = Input::except('_token');
$validation = Validator::make($passwordData, User::$passwordData);
if ($validation->passes()) {
array_forget($passwordData,'password_confirmation');
User::where(array(
'password' => Hash::make(Input::get('password'))
));
Session::flash('password', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil/password');
} else {
return Redirect::to('backend/perfil/password')->withInput()->withErrors($validation);
}
}
user
public static $passwordData = array(
'password' => 'required|confirmed',
'password_confirmation' => 'required'
);
Follow this simple steps to get rid of anything
Step 1 : Get the password from the form
$PasswordData = Input::all();
Step 2 : Validate your password
Validator::extend('pwdvalidation', function($field, $value, $parameters) {
return Hash::check($value, Auth::user()->password);
});
Step 3 : Define the validation rule in your User Model
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|alphaNum|min:5|max:10',
'NewPassword_confirmation' => 'required',
);
Note : You shall define your own rule according to your need
Step 4 : If the rule is passed, then update else throw error messages to your view
$validator = Validator::make($PasswordData, User::$rulespwd, $messages);
if ($validator->passes()) {
$user = User::find(Auth::user()->id);
$user->password = Input::get('NewPassword');
$user->save();
return Redirect::to(Session::get('urlpath') . '/changepassword')->withInput()->with('Messages', 'The Password Information was Updated');
} else {
return Redirect::to(Session::get('urlpath') . '/changepassword')->withInput()->withErrors($validator);
}

form validation laravel 5

on my profile update form i have fullname password and confirm password fields . currently my validations are works only for
empty fields and password mismatch. but how can i add password charactor limits validations as well ?
password should be min:5 and max 15 charactors.
please advice.
public function changePasswordPost()
{
$user = Auth::user();
if (Input::get('password')) {
if (Input::get('password') !== Input::get('confirm_password')) {
return Redirect::route('admin-change-password')->with('error', 'Password field is not identical to Confirm Password.');
}
$user->update();
return Redirect::route('admin-change-password')->with('success', 'You have successfully updated login details.');
}
return Redirect::route('admin-change-password')->with('error', 'Input Missing');
}
You need to do something like this:
use Validator;
public function changePasswordPost(Request $request)
{
$user = Auth::user();
if ($request->get('password')) {
if (($request->get('password') !== $request->get('confirm_password')) ||
(Validator::make($request->all(), ['password' => 'min:5|max:15'])->fails())) {
return redicrect()->route('admin-change-password')->with('error', 'Password field is not identical to Confirm Password.');
}
$user->update();
return redirect()->route('admin-change-password')->with('success', 'You have successfully updated login details.');
}
return redirect()->route('admin-change-password')->with('error', 'Input Missing');
}
I haven't tested this code but the point is that you need to use Validator class from laravel. Note that I have changed some of the stuff to use laravel-5.1 friendly API.
Note that you can get cleaner code by adding Validation before you do anything. Something like this:
public function changePasswordPost(Request $request)
{
/**
* This basically captures your password matching
* and password length cases in a compact way so
* you don't need all the if statements.
*/
$validation = Validator::make($request->all(),
['password' => 'required|min:5|max:15',
'confirm_password' => 'required|same:password']);
if ($validation->fails())
{
response()->redirect('admin-change-password')->with('error', 'bad input');
}
/**
* Here you do the rest of the processing like updating the database.
*/
}

Rule for Checking Old Password and New Password

I am checking for Old Password and New Password with Confirmation Password.
Here i want to check with whether OldPassword and New Password should not be same.
How can i do this ?
Here is my Rule :
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|min:1|max:10',
'NewPassword_confirmation' => 'required',
);
Here is my controller code for the validation :
$PasswordData = Input::all();
Validator::extend('pwdvalidation', function($field, $value, $parameters)
{
return Hash::check($value, Auth::user()->password);
});
$messages = array('pwdvalidation' => 'The Old Password is Incorrect');
$validator = Validator::make($PasswordData, User::$rulespwd, $messages);
if ($validator->passes())
{
$user = User::find(Auth::user()->id);
$user->password = Input::get('NewPassword');
$user->save();
return Redirect::to('changepassword')->with('Messages', 'The Password Information was Updated');
}
Note : I am using model for validation rule.. How can i do this in model ??
Just use the different validation rule - as described in the Laravel docs
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|min:6|max:50|different:OldPassword',
'NewPassword_confirmation' => 'required',
);
Also - why are you limiting a password to 10 chars? That is silly - there is no reason to limit it at all. All your are doing is reducing your application security.

Input validation in laravel?

I have a Input validation to change user password, when i tried to submit the form i got always an error that the new password and confirm password are not matched even, this is my post action :
public function doChangePassword()
{
if(Auth::check())
{
$validator = Validator::make(Input::all(), User::$updatePasswordRules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('change-password')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
} else {
// store
$user = User::find(Auth::user()->id);
if(Auth::user()->password==Input::get('new_password')){
$user->password = Hash::make(Input::get('new_password'));
$user->save();
}
else{
return Redirect::to('change-password')->with('message', 'The password is not correct');
}
// redirect
Session::flash('message', 'Successfully updated password!');
return Redirect::to('login');
}
}
else{
return Redirect::to('login');
}
}
this is my rules :
public static $updatePasswordRules = array(
'password'=>'required|alpha_num|between:6,12',
'new_password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
so please if someone has an idea i will be very appreciative
It's because Laravel expects (for your specific case) confirmed field to be named new_password_confirmation
From doc "The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input."
Thus rules should look like (also change input name in form):
public static $updatePasswordRules = array(
'password'=>'required|alpha_num|between:6,12',
'new_password'=>'required|alpha_num|between:6,12|confirmed',
'new_password_confirmation'=>'required|alpha_num|between:6,12'
);
Or you can do it with same validation rule (if don't want to update form inputs):
public static $updatePasswordRules = array(
'password'=>'required|alpha_num|between:6,12',
'new_password'=>'required|alpha_num|between:6,12|same:password_confirmation',
'password_confirmation'=>'required|alpha_num|between:6,12'
);

Categories