I get the wrong error messages. My purpose is following :
1. checking username / pw combination, and if it doesn't match, "wrong username/pw combination" error through validator.
2. captcha (mews) is troubling me. Even user enters true captcha chars (no case-sensitive by config) I get the error message.
Here is my validator :
FYI: i have a table "user" instead of users, and i can use it nicely in other controllers.
protected function loginValidator()
{
$message = array(
'exists:user,username' => 'Wrong username/pass combination',
'exists' => 'Wrong :attribute.',
'required' => ':attribute cannot be empty',
'captcha' => 'Wrong captcha'
);
return Validator::make(Input::all(),[
'usernameInput' => 'required|exists:user,username',
'passwordInput' => 'required',
'captchaInput' => 'captcha|required'
], $message);
}
Even if username/pass combination is true, i get wrong captcha message.
Thanks in advance.
protected function loginValidator()
{
$validator = Validator::make(
array(
'name' => 'Dayle',
'password' => 'lamepassword',
'email' => 'email#example.com'
),
array(
'name' => 'required',
'password' => 'required|min:8',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
$data['messages'] = $validator->messages()->all();
}
else
{
//complete validation
}
return View::make('home.login', $data);
}
Related
So, I have controller method which validates user and updates their information.
public function updateBasicInfo(Request $request)
{
$basic_info = Validator::make($request->all(), [
'fullname' => 'required|min:2|max:255',
'phone_number' => 'required|numeric|min:10',
'email' => 'required',
'country' => 'required',
'address' => 'required',
], [
'phone_number.min' => "The phone number must be at least 10 digits",
]);
if($basic_info->fails())
{
return response()->json([
'errors'=> $basic_info->errors()->all(),
]);
}
else
{
$basic_info = $basic_info->validated();
$user = request()->session()->get('id');
$currentUser = User::firstWhere('username', $user->username);
$currentUser->name = $basic_info['fullname'];
$currentUser->phone_number = $basic_info['phone_number'];
$currentUser->email = $basic_info['email'];
$currentUser->save();
UserDetail::firstWhere(['username' => $user->username])->update([
'address'=>$basic_info['address'],
'country' => $basic_info['country'],
]);
$current_user = $currentUser;
Mail::to($current_user->email)->send(new ProfileMail($user));
return response()->json(['success'=> 'Profile Updated Sucessfully']);
}
}
I want to update user but I don't want two users to have the same email and I also want the user email to change only if it's value has been changed in the database.
Check to make sure that only the user has that email in the whole table and update it to prevent double email records
Please, how do I do this?
I have tried calling the isDirty() method,nothing seems to work
You can use the unique validation rule for email with ignore to make sure that it doesn't receive an error if the new email is the same as the last email. (Unique validation only in comparison with other users). Check out this link.
$basic_info = Validator::make($request->all(), [
'fullname' => 'required|min:2|max:255',
'phone_number' => 'required|numeric|min:10',
'email' => 'required|unique:users,email,'.request()->session()->get('id'),
'country' => 'required',
'address' => 'required',
], [
'phone_number.min' => "The phone number must be at least 10 digits",
]);
The isDirty() method is to check if you set a value to any of the properties of instance. And it checks the change after it occured.isDirty()
I'm working with Laravel 5.8 and I have made this Controller method for creating some records inside the DB.
public function doTheUpload(Request $request)
{
try{
$request->validate([
'video' => 'nullable|mimes:mp4',
'video_thumb' => 'required|mimes:jpg,png,jpeg',
'video_name' => 'required',
'video_desc' => 'nullable',
'available_download' => 'nullable',
],[
'video.mimes' => 'video file format is not valid',
'video_thumb.required' => 'uploading video thumbnail is required',
'video_name.required' => 'you must enter name of video',
'video_thumb.mimes' => 'image thumbnail file format is not valid',
]);
// Do the upload process
}catch(\Exception $e){
dd($e);
}
}
But this will not working and return this error:
The given data was invalid.
This is basically because of the form validation requests and when I remove those validations from the method, it will work absolutely fine.
So what is wrong with those form request validation that returns this error?
If you know, please let me know... I would really really appreciate any idea or suggestion from you guys.
Thanks.
When you use Laravel's validation, you should let Laravel handle the errors, because when a rule fails, Laravel automatically throws an exception.
So the first advise is no to use a try-catch block in your validation routine.
As Laravel docs states:
Displaying The Validation Errors
So, what if the incoming request parameters do not pass the given
validation rules? As mentioned previously, Laravel will automatically
redirect the user back to their previous location. In addition, all of
the validation errors will automatically be flashed to the session.
In addition, I suggest you not to use validation in the controllers because according to good practices, it is recommended to create separate formRequest for validation, so you should slightly modify you controller to include validator class:
<?php
namespace App\Http\Controllers;
...
use App\Http\Requests\UploadVideoRequest;
...
public function doTheUpload(UploadVideoRequest $request)
{
/*
* Here where are calling validation as UploadVideoRequest
*/
// logic for valid uploaded video
}
Now you have to create a form request, maybe using php artisan make:request UploadVideoRequest
This command will create a form request class under app/Http/Requests, and you should fill it as:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UploadVideoRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
/*
* here you should check if the user is authorized to upload video
* or let in true if anyone can do that
*/
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'video' => 'nullable|mimes:mp4',
'video_thumb' => 'required|mimes:jpg,png,jpeg',
'video_name' => 'required',
'video_desc' => 'nullable',
'available_download' => 'nullable',
];
}
/**
* Define messages to return if an error is detected.
*
* #return array
*/
public function messages()
{
return [
'video.mimes' => 'video file format is not valid',
'video_thumb.required' => 'uploading video thumbnail is required',
'video_name.required' => 'you must enter name of video',
'video_thumb.mimes' => 'image thumbnail file format is not valid',
];
}
}
By using this approach Laravel is validating user input and managing any error via Exceptions.
Regards.
You must specify exactly what you are validating:
$request->validate([
'request.video' => 'nullable|mimes:mp4',
'request.video_thumb' => 'required|mimes:jpg,png,jpeg',
'request.video_name' => 'required',
'request.video_desc' => 'nullable',
'request.available_download' => 'nullable',
], [
'request.video.mimes' => 'video file format is not valid',
'request.video_thumb.required' => 'uploading video thumbnail is required',
'request.video_name.required' => 'you must enter name of video',
'request.video_thumb.mimes' => 'image thumbnail file format is not valid',
]);
An example from my codes:
$requestData = $request->request_data;
// data
$company_name = $requestData['company_name'];
$company_type = $requestData['company_type'];
$company_address = $requestData['company_address'];
$latitude = $requestData['latitude'];
$longitude = $requestData['longitude'];
$company_branch_count = $requestData['company_branch_count'];
$yes_radio = strval($requestData['yes_radio']);
$no_radio = strval($requestData['no_radio']);
$company_contact_user_first_name = $requestData['company_contact_user_first_name'];
$company_contact_user_last_name = $requestData['company_contact_user_last_name'];
$company_contact_user_email = $requestData['company_contact_user_email'];
$company_contact_user_password = $requestData['company_contact_user_password'];
$company_contact_user_phone = $requestData['company_contact_user_phone'];
$company_kvkk_ok = strval($requestData['company_kvkk_ok']);
$shipping_method_yourself = $yes_radio === 'true' && $yes_radio != $no_radio ? 1 : 0;
if ($company_kvkk_ok == 'false') {
return json_encode([
'operation_status' => 'error',
'error_messages' => 'no',
]);
}
// Validate
$validator = Validator::make($request->all(), [
"request_data.company_name" => "required|string|min:5",
"request_data.company_type" => "required|in:0,1,2,3,4,5,6,7,8,9,10,11,12",
"request_data.company_address" => "required",
"request_data.latitude" => "required",
"request_data.longitude" => "required",
"request_data.company_branch_count" => "required|integer",
"request_data.yes_radio" => "required",
"request_data.no_radio" => "required",
"request_data.company_contact_user_first_name" => "required",
"request_data.company_contact_user_last_name" => "required",
"request_data.company_contact_user_email" => [
'required',
'email',
Rule::unique('users', 'email')->where(function ($query) use ($company_contact_user_email) {
return $query->where('email', $company_contact_user_email);
}),
Rule::unique('companies', 'company_contact_user_email')->where(function ($query) use ($company_contact_user_email) {
return $query->where('company_contact_user_email', $company_contact_user_email);
}),
],
"request_data.company_contact_user_password" => "required|min:6",
"request_data.company_contact_user_phone" => "required",
"request_data.company_kvkk_ok" => "required",
], [
'request_data.company_name.required' => __('company name required'),
'request_data.company_name.string' => __('company name must be string'),
'request_data.company_name.min' => __('company name must be at least 5 characters'),
'request_data.company_type.required' => __('company type required'),
'request_data.company_type.in' => __('company type invalid'),
'request_data.company_address.required' => __('company address required'),
'request_data.latitude.required' => __('latitude required'),
'request_data.longitude.required' => __('longitude required'),
'request_data.company_branch_count.required' => __('company branch count required'),
'request_data.company_branch_count.integer' => __('company branch count must be integer'),
'request_data.yes_radio.required' => __('yes radio required'),
'request_data.no_radio.required' => __('no radio required'),
'request_data.company_contact_user_first_name.required' => __('company contact user first name required'),
'request_data.company_contact_user_last_name.required' => __('company contact user last name required'),
'request_data.company_contact_user_email.required' => __('company contact user email required'),
'request_data.company_contact_user_email.email' => __('company contact user email invalid'),
'request_data.company_contact_user_email.unique' => __('email already taken'),
'request_data.company_contact_user_password.required' => __('company contact user password required'),
'request_data.company_contact_user_password.min' => __('company contact user password must be at least 6 characters'),
'request_data.company_contact_user_phone.required' => __('company contact user phone required'),
'request_data.company_kvkk_ok.required' => __('company kvkk ok required'),
]);
if ($validator->fails()) {
$messages = $validator->messages();
return json_encode([
'operation_status' => 'not_validated',
'request' => $requestData,
'messages' => $messages,
]);
}
I'm trying the Laravel's Auth class but the method returns false always. Here's my code:
Controller :
public function postLogin()
{
// Declare the rules for the form validation.
//
$rules = array(
'email' => 'Required|Email',
'password' => 'Required'
);
// Get all the inputs.
//
$email = Input::get('email');
$password = Input::get('password');
// Validate the inputs.
//
$validator = Validator::make(Input::all(), $rules);
// Check if the form validates with success.
//
if ($validator->passes())
{
//echo $password; displays test
// Try to log the user in.
//
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
// Redirect to the users page.
//
return Redirect::to('account')->with('success', 'You have logged in successfully');
}
else
{
// Redirect to the login page.
//
return Redirect::to('account/login')->with('error', 'Email/password invalid.');
}
}
// Something went wrong.
//
return Redirect::to('account/login')->withErrors($validator->getMessageBag());
}
Seeder.php
public function run()
{
DB::table('users')->delete();
$users = array(
array(
'email' => 'test#test.com',
'password' => Hash::make('test'),
'first_name' => 'John',
'last_name' => 'Doe',
'created_at' => new DateTime,
'updated_at' => new DateTime,
)
);
DB::table('users')->insert( $users );
}
It will be because of framework bug. So try to update it.
composer update
Or
php composer.phar update
In your config/auth.php file
try changing from 'driver' => 'eloquent' to 'driver' => 'database'.
I am trying to get the confirmation password to work against the password field in my form. I went through the Validator methods and they all seem to work perfectly. However, when trying to confirm the password I get an error message everytime that they must match..scratching my head I can only determine it's because they are being hashed before going through validation. I am not sure how to get past this as they need to be hash before being entered into the database. Any ideas?
getSignUp Controller
public function getSignUp() {
$userdata = array(
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
'confirm_password' => Hash::make(Input::get('confirm_password')),
'user_zip_code' => Input::get('user_zip_code')
);
$rules = array(
'email' => 'required|email|unique:users,email',
'password' => 'required|min:5',
'confirm_password' => 'required|same:password',
'user_zip_code' => 'required'
);
$validation = Validator::make($userdata, $rules);
if($validation->fails()){
return Redirect::to('signup')->withErrors($validation)->withInput();
}
$user = new User($userdata);
$user->save();
return Redirect::to('login');
}
If anymore code is needed let me know. I just simply have the withErrors going to the blade template for the signup page
Don't pass the hashed password to the validator. Hash it before you save it:
public function getSignUp() {
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'confirm_password' => Input::get('confirm_password'),
'user_zip_code' => Input::get('user_zip_code')
);
$rules = ...
$validation = Validator::make($userdata, $rules);
if($validation->fails()){
return Redirect::to('signup')->withErrors($validation)->withInput();
}
$userdata['password'] = Hash::make($userdata['password']);
$user = new User($userdata);
$user->save();
return Redirect::to('login');
}
I'm trying to set up validation for user registration but I'm having troubles. When I only have the email,role and password fields in the $validation array (remove the others) it works and will save a new user. When I try to add the other fields it fails and gives the flash message error "The user could not be saved. Please, try again."
I'm pretty sure it's the re_password check. When I remove the validation for that it works. However, the re_password validation does display an error when the passwords are different, so I'm not sure where to look
Here's my users table
id | email | password | location | website | role | created | modified
Here's the validation requirements. To get it to save a new user I have to remove everything but email, password and role.
public $validate = array(
'email' => 'email'
,
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'message' => 'A password with a minimum length of 8 characters is required'
)
),
're_password' => array(
'required' => array(
'rule' => array('equalTo', 'password' ),
'message' => 'Both password fields must be filled out'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'author')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
),
'location' => array(
'valid' => array(
'rule' => array('notEmpty'),
'message' => 'Please select a location'
)
)
);
Here's the form (the options array is above, figured it's not necessary to show)
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('re_password', array('type'=>'password', 'label'=>'Re-Enter Password', 'value'=>'', 'autocomplete'=>'off'));
echo $this->Form->input('location', array('options' => $options, 'label' => 'Select Nearest Location'));
echo $this->Form->input('website',array('label'=>'Enter your website, such as www.example.com. '));
echo $this->Form->input('role', array('type' => 'hidden', 'default' => 'user'));
Here's the re_password checking function in the User model
function check_user_password($userid) {
$salt = Configure::read('Security.salt');
$this->User->id = $userid;
$hashed_password = $this->User->field('password');
// check password
if($hashed_password == md5($data['User']['re_password'].$salt)) {
return true;
} else {
return false;
}
}
And finally, here's the add function in UsersController
public function add() {
if ($this->request->is('post')) {
$this->User->create(); //create initiates a form on User/add.ctp
if ($this->User->save($this->request->data)) { //save the form data
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('controller' => 'demos', 'action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
Please let me know if there's anything else you need to see
I believe that your re_passwords valiadtion rule equalTo compares its value to string password and not the actual field. I like to use custom functions for this.
so try replacing re_passwords rule array
//'rule' => array('equalTo', 'password' ),
'rule' => array('equalToField', 'password'),
and declare equalToField function in that model
function equalToField($array, $field) {
return strcmp($this->data[$this->alias][key($array)], $this->data[$this->alias][$field]) == 0;
}
** Also in the future when you seem to have a problem with validation rules
try this in your controllers action (its faster than removing every single rule)
if ($this->User->save($this->request->data)) {
...
} else {
debug($this->User->validationErrors);
...
}
I hope this helps.
Hi Please use following code for your requirement :
override equalTo function by putting your own method in user model:
function equalTo( $field=array(), $compare_field=null )
{
foreach( $field as $key => $value ){
$v1 = $value;
$v2 = $this->data[$this->name][ $compare_field ];
if($v1 !== $v2) {
return FALSE;
} else {
continue;
}
}
return TRUE;
}
Attention, in #luboss answer, where he declares:
function equalToField($array, $field) {
return strcmp($this->data[$this->alias][key($array)], $this->data[$this->alias][$field]) == 0;
}
That cannot work as we are comparing inconsistent fields:
the left member of strcmp has already been hashed, but not the right member.
This happens as a CakePHP automation because the field is called password.
The way I got this to work was to reuse the hashing function in the equalToField helper:
public function equalToField($array, $field) {
$valueFirstOccurrence = $this->data[$this->alias][$field];
$valueSecondOccurrence = Security::hash($this->data[$this->alias][key($array)], $type = 'sha1', $salt = true) ;
return !strcmp($valueFirstOccurrence, $valueSecondOccurrence);
}
Other point :
If you are interested in adding a minLength validation field for your password field, you want to read this good post first:
minLength data validation is not working with Auth component for CakePHP