Rule for Checking Old Password and New Password - php

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.

Related

How to change password in laravel laravel 5.2

I have three fields
1- password
2- new password
3- password_confirmation this is change password functionality.
I have allow the condition on password that must be 8 characters one upper one lower and one special character
but i cannot change my password its going on my validator fails:
My Controller code:
public function changepassword(Request $request){
$user = Auth::guard()->user();
$request_data = $request->All();
$validator = $this->admin_credential_rules($request_data);
if($validator->fails()) {
return \Illuminate\Support\Facades\Redirect::to('mujucet')
->with("modal_message_danger", "password must be at least 8 characters, one upper and lower case, and a number");
} else {
$current_password = $user->password;
if(md5($request_data['password']) == $current_password) {
$user_id = $user->id;
$obj_user = User::find($user_id);
$obj_user->password = md5($request_data['new_password']);
$obj_user->save();
return \Illuminate\Support\Facades\Redirect::to('mujucet')
->with("modal_message_success", "Password has been changed successfully");
} else {
return \Illuminate\Support\Facades\Redirect::to('mujucet')
->with("modal_message_danger", "wong old password");
}
}
}
public function admin_credential_rules(array $data){
$messages = [
'new_password.required' => "Zdejte nové heslo.",
'password.required' => "Zadejte souÄasné heslo.",
];
$validator = Validator::make($data, [
'password' => 'required|min:8|regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/|confirmed',
'new_password' => 'required|min:8|regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/|confirmed',
], $messages);
return $validator;
}
i am stuck into this problem i need your help.
Any help will be highly appreciated!
What errors does the validator give you? You can retrieve them with $validator->errors().
Looking at the code I think you'll need to remove the confirmed rule from the password field validator (since you don't need to confirm the old password). Then you'll need to change the new password confirmation field to have the name new_password_confirmation.
Your three fields should be: password, new_password and new_password_confirmation.
The validator should be:
$validator = Validator::make($data, [
'password' => 'required|min:8|regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/',
'new_password' => 'required|min:8|regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/|confirmed',
], $messages);
Have you overridden the default hasher to use MD5 for passwords? By default Laravel uses bcrypt which is a lot more secure for hashing sensitive data.

Laravel 5 custom login with username OR email using the Attempt method

In my laravel app, at the start I had decided to create my own custom login controller, rather than use the base one.
public function postSignin(Request $request, AppMailer $mailer) {
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('info', 'Could not sign you in with those details.');
}
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'verified' => 0]))
{
$mailer->sendEmailConfirmationTo(Auth::user());
Auth::logout();
return redirect()->back()->with('info', 'Email verification required.');
}
Auth::user()->last_login = new DateTime();
Auth::user()->save();
return redirect()->back()->with('info', 'You are now signed in.');
}
And now I want to edit this so that users can also login with their usernames and not just their emails, using the same field. However, the attempt method is confusing. It seems to expect an email even after I switch the values around.
The Auth documentation isn't very helpful in this case either. It asks me to add this:
public function username()
{
return 'username';
}
in the login controller, but obviously this is for a default setup.
You can use the 'FILTER_VALIDATE_EMAIL' checker.
$username = $request->get('username');
$password = $request->get('password');
$remember_me = $request->get('remember_me','1');
$field = filter_var($username,FILTER_VALIDATE_EMAIL)? 'email': 'username';
if(Auth::attempt([$field => $username,'password' => $password],$remember_me)){
//Auth successful here
}
Meaning FILTER_VALIDATE_EMAIL do check the string whether it is in email format or not.
I hope this sample code helps you.
-ken

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);
}

Laravel - Confide - Save Change Password

I managed to save a new password or change a password for a logged in user.
public function saveNewPassword() {
$rules = array(
'old_password' => 'required',
'password' => 'required|confirmed|different:old_password',
'password_confirmation' => 'required|different:old_password|same:password_confirmation'
);
$user = User::findOrFail(Auth::user()->id);
// Validate the inputs
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
} else {
$password = Input::get( 'password' );
$passwordConfirmation = Input::get( 'password_confirmation' );
if(!empty($password)) {
if($password === $passwordConfirmation) {
$user->password = $password;
$user->password_confirmation = $passwordConfirmation;
}
} else {
unset($user->password);
unset($user->password_confirmation);
}
// Save if valid. Password field will be hashed before save
$user->save();
}
// Get validation errors (see Ardent package)
$error = $user->errors()->all();
if(empty($error)) {
Session::flash('message', 'Successfully saved!');
return Redirect::back();
} else {
Session::flash('error', $error);
return Redirect::back();
}
}
The problem I have is, how to check the Old Password, that is equal to the current password? Any Ideas? Does Confide has his own methods for changing passwords?
I use this sollution for changing the password. In your rules you have one error: password_confirmation should be the same as password not password_confirmation.
Here is the complete and tested function:
public function changePassword($id){
$rules = array(
'old_password' => 'required',
'new_password' => 'required|confirmed|different:old_password',
'new_password_confirmation' => 'required|different:old_password|same:new_password'
);
$user = User::find(Auth::user()->id);
$validator = Validator::make(Input::all(), $rules);
//Is the input valid? new_password confirmed and meets requirements
if ($validator->fails()) {
Session::flash('validationErrors', $validator->messages());
return Redirect::back()->withInput();
}
//Is the old password correct?
if(!Hash::check(Input::get('old_password'), $user->password)){
return Redirect::back()->withInput()->withError('Password is not correct.');
}
//Set new password to user
$user->password = Input::get('new_password');
$user->password_confirmation = Input::get('new_password_confirmation');
$user->touch();
$save = $user->save();
return Redirect::to('logout')->withMessage('Password has been changed.');
}
This also works if you dont work with Confide.
From the github of confide:
Integrated with the Laravel Auth and Reminders component/configs.
So I would guess using the Auth::validate() method will do the trick.

how to check if a user email already exist

In laravel, when a new user is registering to my site and the email they use already exist in the database. how can tell the user that the email already exist ?. I am new to laravel framework. A sample code would be nice too.
The validation feature built into Laravel lets you check lots of things, including if a value already exists in the database. Here's an overly simplified version of what you need. In reality you'd probably want to redirect back to the view with the form and show some error messages.
// Get the value from the form
$input['email'] = Input::get('email');
// Must not already exist in the `email` column of `users` table
$rules = array('email' => 'unique:users,email');
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
echo 'That email address is already registered. You sure you don\'t have an account?';
}
else {
// Register the new user or whatever.
}
);
Laravel has built-in human readable error messages for all its validation. You can get an array of the these messages via: $validator->messages();
You can learn more about validation and what all you can do with it in the Laravel Docs.
Basic Usage Of Unique Rule
'email' => 'unique:users'
Specifying A Custom Column Name
'email' => 'unique:users,email_address'
Forcing A Unique Rule To Ignore A Given ID
'email' => 'unique:users,email_address,10'
Adding Additional Where Clauses
You may also specify more conditions that will be added as "where" clauses to the query:
'email' => 'unique:users,email_address,NULL,id,account_id,1'
The above is from the documentation of Laravel
You could add:
public static $rules = [
'email' => 'unique:users,email'
];
You can add more rules to the $rules like:
public static $rules = [
'email' => 'required|unique:users,email'
];
It will automatically produce the error messages
and add:
public static function isValid($data)
{
$validation = Validator::make($data, static::$rules);
if ($validation->passes())
{
return true;
}
static::$errors = $validation->messages();
return false;
}
to the model User.php
Then in the function you're using to register, you could add:
if ( ! User::isValid(Input::all()))
{
return Redirect::back()->withInput()->withErrors(User::$errors);
}
if(sizeof(Users::where('email','=',Input::get('email'))->get()) > 0) return 'Error : User email exists';
The great resource is only Laravel Documentation #
enter link description here
I also did like below when integrating user management system
$user = Input::get('username');
$email = Input::get('email');
$validator = Validator::make(
array(
'username' => $user,
'email' => $email
),
array(
'username' => 'required',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
echo 'invalid credentials;';
// we can also return same page and then displaying in Bootstap Warning Well
}
else {
// Register the new user or whatever.
$user = new User;
$user->email = Input::get('email');
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();
$theEmail = Input::get('email');
// passing data to thanks view
return View::make('thanks')->With('displayEmail', $theEmail);
}
public function userSignup(Request $request, User $data){
# check user if match with database user
$users = User::where('email', $request->email)->get();
# check if email is more than 1
if(sizeof($users) > 0){
# tell user not to duplicate same email
$msg = 'This user already signed up !';
Session::flash('userExistError', $msg);
return back();
}
// create new files
$data = new User;
$data->name = $request->name;
$data->email = $request->email;
$data->password = md5($request->password);
$data->save();
//return back
Session::flash('status', 'Thanks, you have successfully signup');
Session::flash('name', $request->name);
# after every logic redirect back
return back();
}
I think when u try something like this you earn a smooth check using Model
We can use the Validator.
In your Controller.
$validator = $request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
]);
In View
#error('email') <span class="text-danger error">{{ $message }}</span>#enderror
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'email' => 'required|min:4|email|unique:users',
'password' => 'required',
]);
Try This

Categories