Laravel: Auth Attempt failed - laravel-4

I have tried the following codes. But the auth attempt failed.
// validate the info, create rules for the inputs
$rules = array(
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$userdata = array(
'Email' => Input::get('email'),
'Password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata)) {
// validation successful!
// redirect them to the secure section or whatever
// return Redirect::to('secure');
// for now we'll just echo success (even though echoing in a controller is bad)
echo 'SUCCESS!';
} else {
// validation not successful, send back to form
return Redirect::to('login')->with('message', 'Login Failed');
}
}
I have the following columns in Users table.
id,
Username,
Email,
created_at,
updated_at,
Password
I have changed the table name in model. Please advice. What's wrong?

Usually the convention is to make database columns lowercase. With the email column, that should not be a problem. As the documentation states, the 'email' field is only used as an example. http://laravel.com/docs/security#authenticating-users
To make Laravel use your capitalised password column. Open your user eloquent model and change:
public function getAuthPassword()
{
return $this->password;
}
to:
public function getAuthPassword()
{
return $this->Password;
}
Pretty sure that'll do the trick,

Related

Laravel 8 reset password in PWA

I am trying to establish a password reset system in a Laravel + SPA environment with Vuejs. Except for the form that starts the process ('I have forgotten my password'), the rest of the actions I want to be carried out in the standard Laravel way, outside the spa and using Laravel Auth. So I have:
web.php
//This sends a custom email notification.
Route::post('/forgot-password', 'UserController#reestablecerPassword')->middleware('guest')->name('password.email');
//Shows the standard view auth.passwords.reset, when we can reset password values.
Route::get('/reset-password/{token}', function ($token) {
return view('auth.passwords.reset', ['token' => $token]);
})->middleware('guest')->name('password.reset');
//Route to custom method in order to receive and process the previous form
Route::post('/reset-password', 'UserController#procesarReestablecerPassword')->middleware('guest')->name('password.update');
//this returns a simple view where it is reported that the password has been changed
Route::get('/changedpassword', function () {
return view('changedpassword');
})->name('changedpassword');
Methods in UserController.php
//Handles the response by email and the response to the front-end to inform that the email has been sent
public function reestablecerPassword(Request $request){
$request->validate(['email' => 'required|email']);
$status = Password::sendResetLink(
$request->only('email')
);
Log::info('status:');
Log::info($status);
$status == 'passwords.sent' ? $respuesta = response('OK', 200) : $respuesta = response('KO', 400);
return $respuesta;
}
//Process the request that contains the form data and reset the password. The program flow does not execute this method in production, the log is not written
public function procesarReestablecerPassword(Request $request) {
Log::info('entra a procesarReestablecerPassword con estos valores en la petición:');
Log::info($request);
$request->validate([
'token' => 'required',
'email' => 'required|email',
'password' => 'required|min:8|confirmed',
]);
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function ($user, $password) use ($request) {
$user->forceFill([
'password' => Hash::make($password)
])->save();
$user->setRememberToken(Str::random(60));
event(new PasswordReset($user));
}
);
return $status == Password::PASSWORD_RESET
? redirect()->route('changedpassword')->with('status', __($status))
: back()->withErrors(['email' => [__($status)]]);
}
The issue appears when we submit the reset-password view form, when I get the error:
The GET method is not supported for this route. Supported methods: POST.
Observing the operation in the web browser:
In the local environment, where the operation is correct, two actions happen after pressing the submit button of the form:
A first POST type is sent with the form data. Such as:
https://appname.com/reset-password
A 'Location' header is received to redirect to a second URL via GET that includes the user token. Being of type:
https://appname.com/reset-password/jkladjfñl9iu08adDjfjnnakRfpaiw
Well, in the production environment, this token is not found in the url received in the Location header (I don't know why this occurs)
Thanks in advance.

Laravel auth attempt not working or returning false always?

I've been looking all over the place (I checked all the other duplicate questions and answers ), no luck. I don't understand what am I doing wrong, all the values are coming from post, but Auth:attempt keeps on failing/returning false, if I try to implement login manually it won't authenticate as I am expecting, Also do I have to make or use separate methods like for validation, credentials, username ..etc ?
Here is my login Controller > login method
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'usermail' => 'required|max:255',
'password' => 'required_with:usermail',
],[
'password.required_with' => "The password field is empty."
]);
if ($validator->fails()) {
return redirect()
->route('admin.login')
->withErrors($validator)
->withInput();
}
$usermail = $request->get('usermail');
$password = $request->get('password');
$remember = $request->get('rememberMe');
if(filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$isEmailExist = User::where('user_email',$usermail)->first();
if($isEmailExist != null){
if(Auth::attempt([
'user_email' => $usermail,
'user_pass' => $password
])){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the email address <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid email address.'
]);
}
}else{
$isUsernameExist = User::where('user_login',$usermail)->first();
if($isUsernameExist != null){
if(Auth::attempt([
'user_login' => $usermail,
'user_pass' => $password
],$remember)){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the username <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid username. Lost your password?'
]);
}
}
}
And this is my user migration schema,
Schema::create('vw_users', function (Blueprint $table) {
$table->bigIncrements('ID');
$table->string('user_login','60')->unique()->default('');
$table->string('user_pass');
$table->string('user_email','100')->unique()->default('');
$table->rememberToken();
});
Here is how i seed user,
User::create([
'user_login' => 'admin',
'user_pass' => Hash::make("123456"),
'user_email' => 'admin#gmail.com',
]);
OK OK OK,
I made it work, I think in laravel framework we can only create the column name for the password is "password" field in database authentication table.
I updated the following changes:-
I renamed the password field name from migration schema the "user_pass" to "password". (Also updated in login controller and user model).
Added following code into user model:-
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
...
}
I checked twice to confirm so I revert back it didn't work.
If i make any sense to anyone please let me know and help me understand.
I've looked into very similar posts like this Laravel: How can i change the default Auth Password field name
can I please have a reference book or blog for all the laravel predefined libraries and functions? I know the vendor folder is full of surprises but still, I need more references.
Thank you so much for your time.

How-to Form confirmation response

I am a Laravel newbie. I have gone through tutorials successfully...this is my first production app for a client, using Laravel
I have a form and am able to get the submitted data into a database. The user is given a generic error though. After successful submission, I cannot redirect the user to a confirmation page. Any help is appreciated.
Here is the code from my controller (the store function):
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'lastname' => 'required',
'email' => 'required|email',
'phone' => 'required',
'date' => 'date|date_format:"m/d/Y"'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('nerds/create')
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
// store
$registration = new Registration;
$registration->firstname = Input::get('firstname');
$registration->lastname = Input::get('lastname');
$registration->email = Input::get('email');
$registration->date = date("Y-m-d", strtotime(Input::get('date')));
$registration->phone = Input::get('phone');
$registration->venue = Input::get('venue');
$registration->venueCity = Input::get('venueCity');
$registration->save();
// redirect
Session::flash('message', 'Successfully submitted, someone will contact you soon!');
return Redirect::to('thankyou');
}
}
Please make sure the app/storage folder has the full permissions. Apache should be able to write to that folder.
There must be a route to handle the 'Redirect::to'
The tutorial I followed failed to mention this fact.
Along with the code from my controller's store() function, the following route is necessary.
Route::get('/registration/thankyou', function()
{
return View::make('thankyou');
});

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)

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