The following code is the implementation of the authentication based on whether or not a user enters a password in the edit page of user data.
How could I simplify this code using only a few methods?
...
$user = User::findOrFail($id); //Get role specified by id
if($request->password === null){
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required|email|unique:users,email,'.$id
]);
$request->password = $user->password;
}
else{
//Validate name, email and password fields
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required|email|unique:users,email,'.$id,
'password'=>'required|min:6|confirmed'
]);
}
$input = $request->only(['name', 'email', 'password']); //Retreive the name, email and password fields
$roles = $request['roles']; //Retreive all roles
$user->fill($input)->save();
...
Specs
Laravel ver.5.6
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required|email|unique:users,email,'.$id,
'password'=>'nullable|required|min:6|confirmed'
]);
Use nullable rule in password validation. White saving the password use code like this:
if($request->password){
$user->password = bcrypt($request->password);
}
Related
how to make correct validation if i have input from where i can sign in with username or email, i want to if user will text username in field, it check if this username doesnt exist, then fail, also if he will choose to use email to sign in, then it will check if email doesnt exist then fail. (login form have only 2 inputs, login and password, in login u can text username or email)
my rule =
public function rules()
{
return [
'user' => 'required|min:3|exists:users,username,email]',
'password' => 'required',
];
}
You can use custom login as :
public function login(Request $request)
{
$request->validate([
'user' => 'required|min:3]',
'password' => 'required',
]);
}
$userName_or_Email = $request->user;
$password = $request->password;
$user = User::where('username',$userName_or_Email)->first();
if(empty($user)){
$user = User::where('email',$userName_or_Email)->first();
}
if(empty($user)){
return new Response()->with('error','Username or email not available in database');
}
if(Hash::check($password, $user->password)){
// Login successful code
}else{
return new Response()->with('error','Username or email not available in database');
}
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.
I am using Laravel 5.2, and I am trying to create a dashboard where the user can update his information, but I am facing one problem which is bypassing unique:users in validator.
if the user wants to keep same email, validator gives an error of 'The email has already been taken', also user should not change email to another email which is reserved by another user.
How can I avoid this validation in case if this user is the only user has this email.
my controller function:
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
// if fails, return response with errors
if($validator->fails())
return back()->withErrors($validator)->withInput();
$user = Auth::user();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = bcrypt($request->input('password'));
$user->update();
return back()->withInput();
}
Laravel's unique validator can take additional parameters that can help you exclude given ID from the unique check.
The syntax is:
unique:<table>,<column>,<id_to_exclude>
In your case, you'll need the follwing validation rule:
'email' => 'required|email|max:255|unique:users,email,'.$id
Just change your code to:
public function update(Request $request)
{
$id = Auth::user()->id;
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users'.$id,
'password' => 'required|min:6|confirmed',
]);
// if fails, return response with errors
if($validator->fails())
return back()->withErrors($validator)->withInput();
$user = Auth::user();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = bcrypt($request->input('password'));
$user->update();
return back()->withInput();
}
Why this works? Well the laravel Unique validation searches for the unique value in the table specified. So unique:users searches if the email exists in db. The user id here works as a way to exclude the check for this user.
Also, if you want that email should not be edited, then just exclude it from the request.
$input = $request->excpet(['email']); check docs
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.
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