Laravel validator check existence for multiple fields - validation

I'm creating a user login form where user can use his/her username or email to login with Laravel, so on the backend, I want to validate if the user input is either an existed username or an existed email address, something like
$validator = Validator::make(
array('username_or_email' => $username_or_email),
array('username_or_email' => 'exists:users,username|exists:users,email)
);
but I doubt the above is the correct syntax for it, so how should I write my validator?

Assuming you don't allow # in username you could do it this way:
if (strpos($username_or_email, '#') === false) {
$rule = 'exists:users,username';
}
else {
$rule = 'exists:users,email;
}
$validator = Validator::make(
array('username_or_email' => $username_or_email),
array('username_or_email' => $rule)
);

Related

How to Force a Unique Rule To Ignore A Specific User in Laravel 4?

On my set-password view, I want to allow user to edit their own user name and email.
In my controller, I force my validation to ignore the validation on the user with the same activation code.
I still get the error message.I know, I am missing a step, I not sure how to fix this.
Can you give me a quick tip or point out what I missed ?
I've tried, and here is what I come up with.
Code
public function postSetPassword(){
$user = User::where('code','=', Input::get('code'))->firstOrFail();
$code = $user->code;
$validator = Validator::make(Input::all(), array(
'password' =>'required|min:6',
'password_again' =>'required|same:password',
'logo_path' =>'max:255',
'username' =>'required|unique:users,username,'. $code,
'email' =>'required|email|unique:users,email,'. $code,
... more ...
There's probably many ways to do this but one that comes to my mind is this. Just don't validate the username or email if the user hasn't changed it.
$user = User::where('code','=', Input::get('code'))->firstOrFail();
$validationRules = array(
'password' =>'required|min:6',
'password_again' =>'required|same:password',
'logo_path' =>'max:255'
);
if($user->email != Input::get('email')){
$validationRules['email'] = 'required|email|unique:users,email';
}
if($user->username != Input::get('username')){
$validationRules['username'] = 'required|unique:users,username';
}
$validator = Validator::make(Input::all(), $validationRules);

How to set remember_token NULL in laravel

I have an application in laravel which have a Users table with a column remember_tokenand the User model has the three function mentioned here: http://laravel.com/docs/upgrade#upgrade-4.1.26
getRememberToken(), setRememberToken($value), getRememberTokenName()
In my login form, I have email, password and a remember me checkbox field. What I want is if user ticked that Remember Me checkbox, then only laravel should remember the user, else it should set the column as NULL.
But at the moment it is remembering it all the time, and I don't know how to set it to NULL.
My doLogin function code is below:
public function doLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required|alphaNum|min:7'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$remember = Input::get('remember');
$userData = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userData, true)) {
return Redirect::to('/');
} else {
return Redirect::to('login')->with('loginError', 'Incorrect email or password.');
}
}
}
Please tell me what modification I need to make so that it set remember_token as null in database when remember checkbox is not ticked by user.
To quote the documentation
If you would like to provide "remember me" functionality in your
application, you may pass true as the second argument to the attempt
method, which will keep the user authenticated indefinitely (or until
they manually logout).
You are hard coding the second parameter to true instead of using the value taken from the user input.
You are already setting the input to the $remember variable, so try passing that instead.
Auth::attempt($userData, $remember)

Laravel Updating a record

I'm having troubles updating a record. I have a page where users can register, this works flawlessly and has 4 fields: email, username, password and confirm password. This is a simple registration page and I dont want to turn off the visitors by presenting a lot of stuff to be filled out like full name and country, so these 2 fields can be updated on their "update profile" page. The profile page is separated into areas, the main area is a single form where only these 2 fields can be updated so no username, email, password fields here - only fullname and country.
Controller Update Profile Code
$user = User::find($id);
$user->fullname = Input::get('fullname');
$user->country = Input::get('country');
if (!$user->save())
{
return Redirect::to('edit-profile')->withInput()->withErrors($user->errors());
} else {
return Redirect::to('edit-profile')->withMessage('Profile successfully updated!');
}
My User Model rules. I'm using Ardent:
public static $rules = array(
'username' => 'required|between:3,20|unique:users|alpha_dash',
'email' => 'required|email|unique:users',
'password' => 'required|min:5|confirmed',
'password_confirmation' => 'min:5',
'fullname' => 'between:5,50',
'country' => 'between:3,50'
);
Problem here is that it returns an error message saying "Passwords do not match.". So it seems like Laravel is adding the password field in the query and also tries to validate if the passwords match. I do not want to create a separate model or a separate rules for this. How can I solve this?
To make it work when you do not display a password you can test if you are displaying it, then make it a required field, in the controller:
if ($user->exists){
$user::$rules['password'] = (Input::get('password')) ? 'required|min:5|confirmed' : '';
$user::$rules['password_confirmation'] = (Input::get('password')) ? 'required' : '';
}
$user->save();

user login laravel 4

can't manage to login anybody an idea? i still get redirected back to the login page
Route::post('login', function() {
// get POST data
$email = Input::get('username');
$password = Input::get('password');
if ( Auth::attempt(array('email' => $email,'password' => $password) ))
{
return Redirect::to('home');
}
else
{
// auth failure! lets go back to the login
return Redirect::to('login')
->with('login_errors', true);
}
});
change
if ( Auth::attempt(array('email' => $email,'password' => $password) ))
to
if ( Auth::attempt(array('username' => $email,'password' => $password) ))
Laravel has a setting that lets you specify the username as either 'username' or 'email' (or whatever else you may choose), check config. Like above indicated...
if ( Auth::attempt(array('username' => $email,'password' => $password) ))
Also, Laravel expects a hashed password by default.
To use email as username, try adding this to User model:
protected $primaryKey = 'email';
Also make sure email is the primary key on your 'user' table.

CodeIgniter password not validating against database

I've setup my login functions in CodeIgniter (email/password). The email field is validating properly against the database, but as long as the email is validated any password is accepted--even blank passwords.
I need to figure out why only the email field is being checked against the database and how to get the password field to validate against the database.
Sidebar: I'm planning to encrypt the passwords next, but want to be sure the field is validating against the database first. Then I'll add the security layers.
From the login controller:
function login_validation()
{
$this->load->model('foo_model');
$query = $this->foo_model->validate();
if($query)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('foodash');
}
else
{
$this->index(); // login page
}
}
From the foo model:
function validate()
{
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('footable');
if($query->num_rows == 1)
{
return true;
}
}
}
FIGURED IT OUT:
I was masking my password field using jquery so that the text wasn't visible when entered. I had to change the name of my password field--once I changed it in the model, everything worked perfectly.
FIGURED IT OUT:
I was masking my password field using jquery so that the text wasn't visible when entered. I had to change the name of my password field--once I changed it in the model, everything worked perfectly.
Try returning false in your validate() function after your IF statement.
Also try a different syntax:
$query = $this->db->get_where('footable', array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
));
The password is validating against the database, but the return value of validate() is undefined, when the email or password is wrong. This can result in unpredictable results. I recommend:
function validate()
{
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('footable');
return ($query->num_rows() == 1);
}

Resources