Why cannot authenticate a user using Auth::atempt in Laravel? - php

This is routes file and $users shows the values but login fails
Route::post('login', function () {
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if(Auth::attempt($user))
{
return Redirect::to('profile')
->with('flash_notice', 'You are successfully logged in.');
}
else
{
// authentication failure! lets go back to the login page
return Redirect::route('login')
->with('flash_error', 'Your username/password combination was incorrect.')
->withInput();
}
});
Modal:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}

When using the authentication mechanism provided by Laravel you should pass the following check list:
The database column where you store the password should be a string with a length of 60 characters.
The password should be stored encrypted, no plain. Since we are talking about BCrypt it has to be a value similar to: $2a$10$KssILxWNR6k62B7yiX0GAe2Q7wwHlrzhF3LqtVvpyvHZf0MwvNfVu.
You have to configure the security mechanism by editing the file located app/config/auth.php.
After that, you will eventually have your problem solved.

Related

Password Reset Not working in Laravel 5.4

I am new to laravel. I want to implement the login and registeration using laravel auth. I have implemented the login and registration flow successfully but I am not able to implement reset password.
I am facing the following issue:
1. After submitting the username/email some processing happens but I am not able to send the password reset link using the email. It always got a screen which says we have emailed your password reset link but nothing is happening. The entries are being made in the password_resets table.
Any help will be much appreciated.
I am using the gmail to send the password reset emails. After doing a lot of debugging everything looks fine apart from ResetPassword.php file which is executed till
public function via($notifiable)
{
// echo "<pre>".print_r($notifiable,1)."</pre>";exit("<br/>sdds");
return ['mail'];
}
There is a function in this file which is created to send the emails but this function is not going called. The function is given below :
/**
* Build the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
echo "<pre>".print_r($notifiable,1)."</pre>";exit();
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account.')
->action('Reset Password', route('password.reset', $this->token))
->line('If you did not request a password reset, no further action is required.');
}
Here are the main file used in this
Authorisation model class RetailUserAuth.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Auth\Passwords\CanResetPassword;
class RetailUserAuth extends Authenticatable
{
use Notifiable;
//protected $primaryKey = 'user_id';
protected $table = 'retail_user_auth';
public $timestamps = false;
protected $fillable = ['username', 'user_id', 'password','source','user_status'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
SendsPasswordResetEmails.php
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
trait SendsPasswordResetEmails
{
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\Http\Response
*/
public function showLinkRequestForm()
{
return view('auth.passwords.email');
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function sendResetLinkEmail(Request $request)
{
$this->validate($request, ['username' => 'required|email']);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('username')
);
//echo "</pre>".print_r($response,1)."</pre>";exit();
return $response == Password::RESET_LINK_SENT
? $this->sendResetLinkResponse($response)
: $this->sendResetLinkFailedResponse($request, $response);
}
/**
* Get the response for a successful password reset link.
*
* #param string $response
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendResetLinkResponse($response)
{
return back()->with('status', trans($response));
}
/**
* Get the response for a failed password reset link.
*
* #param \Illuminate\Http\Request
* #param string $response
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendResetLinkFailedResponse(Request $request, $response)
{
return back()->withErrors(
['username' => trans($response)]
);
}
/**
* Get the broker to be used during password reset.
*
* #return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker()
{
return Password::broker();
}
}
CanResetPassword.php
<?php
namespace Illuminate\Auth\Passwords;
use Illuminate\Auth\Notifications\ResetPassword as
ResetPasswordNotification;
trait CanResetPassword
{
/**
* Get the e-mail address where password reset links are sent.
*
* #return string
*/
public function getEmailForPasswordReset()
{
return $this->username;
}
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
}
ResetPassword.php
<?php
namespace Illuminate\Auth\Notifications;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class ResetPassword extends Notification
{
/**
* The password reset token.
*
* #var string
*/
public $token;
/**
* Create a notification instance.
*
* #param string $token
* #return void
*/
public function __construct($token)
{
//echo $token;exit('<br/>fdfdffd');
$this->token = $token;
}
/**
* Get the notification's channels.
*
* #param mixed $notifiable
* #return array|string
*/
public function via($notifiable)
{
// echo "<pre>".print_r($notifiable,1)."</pre>";exit("<br/>sdds");
return ['mail'];
}
/**
* Build the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
echo "<pre>".print_r($notifiable,1)."</pre>";exit();
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account.')
->action('Reset Password', route('password.reset', $this->token))
->line('If you did not request a password reset, no further action is required.');
}
}

Default User model throws error in laravel

The default model "User" in laravel throws error when I tried to use it. What I tried is,
$user = new User();
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->name = "Blah Blah";
$user->access_type = "admin";
$user->access_status = 1;
$user->save();
and the error thrown is
Symfony \ Component \ Debug \ Exception \ FatalErrorException
Call to undefined method User::save()
What is the issue? I also tried User::all() to retrieve the values, which also throws error Call to undefined method User::all().
Update1:
Here is my model
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
Update2:
I tried writing another model names and class name as Users, which works perfectly. But for authentication, it must be the User table right?
The reason for the issue is autoloader load wrong "User" model. Please have a look at the "/vendor/composer/autoload_classmap.php" file. Inside the return array value for the key "User" must be $baseDir . '/app/models/User.php
return array(
...,
'User' => $baseDir . '/app/models/User.php',
...,
);
Maybe User is a reserved word, just give the model another name say UserTbl
Still didn't received any answer to my question. Anyways now I'm running it using the new model named Users with the same doubt in mind.

Unable to Verify user in laravel

I'm new to laravel, so i started by creating a messaging application. User should be able to send message to each other. So i created migrations, seeds,models and also defined relationships in models. Everything was working fine. I was able to seed perfectly.
So i created a login page, applied validations. But now i'm unable to login.
Here is the route :
Route::group(array('prefix'=>'social'), function(){
Route::get('/', array('as' => 'loginformshow', 'uses' => 'LoginformController#showLogin'));
Route::post('loginform', array('as'=>'loginformdo', 'uses'=>'LoginformController#doLogin'));
Route::get('loggedin', array('as'=>'loggedin', 'uses'=>'LoginformController#loggedin'));
});
Here's the respective method in controller
public function doLogin(){
$rules = array('email'=> 'required|email', 'password'=>'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::to('social')->withErrors($validator)->withInput(Input::except('password'));
}else {
$userdata = array('email' => Input::get('email'), 'password' => Input::get('password'));
if(Auth::attempt($userdata)) {
return Redirect::route('loggedin');
}else echo "Invalid User";
}
}
Auth::attempt is returning false every time and so the output is Invalid User.
i used print_r to check the data received in $userdata and it's showing correct credentials.
Here's the User model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function conversationsReply(){
return $this->hasMany('ConversationReply', 'user_id', 'id');
}
}

Laravel attempt() doesn't work, getAuthIdentifier use wrong column

I want to use column email and password for login.
Password is hashed during registration and saved to the database ('driver' => 'database').
Email column is not primary key, but just unique.
AuthController.php:
// Get all the inputs
$userdata = array(
'email' => Input::get('username'),
'password' => Input::get('password')
);
// Declare the rules for the form validation.
$rules = array(
'email' => 'Required',
'password' => 'Required'
);
// Validate the inputs.
$validator = Validator::make($userdata, $rules);
// Check if the form validates with success.
if ($validator->passes())
{
// Try to log the user in.
if (Auth::attempt($userdata, true))
{
// Redirect to homepage
return Redirect::to('')->with('success', 'You have logged in successfully');
}
else
{
// Redirect to the login page.
return Redirect::to('login')->withErrors(array('password' => 'password invalid'))->withInput(Input::except('password'));
}
}
Anyway, I just got error:
ErrorException
Undefined index: id
It also shows me this:
public function getAuthIdentifier()
{
return $this->attributes['id'];
}
What I am doing wrong? Thanks
EDIT
User model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
getAuthIdentifier is an interface method. GenericUser class is implementating that method and requires user id.
So check do you really have id attribute on your model.
In case this helps someone in the future here is how I resolved this. As #WereWolf suggested you do want to set
protected $primaryKey = 'id';
in your model, but your driver should also be 'eloquent' in your auth.php config.
'driver' => 'eloquent',
This will tell laravel to use your Eloquent model as the user object instead of the generic user object from the database table.
You most probably didn't assign your primary key in the user table, the ID should be primary key and also you may add following in your User model to specify your custom primary key:
protected $primaryKey = 'id';
Make sure that, the primary key in the user table matched with this ($primaryKey), means that, must be same.

Login authentication fails in laravel 4

In Laravel4,I have written the following code in routes but it always redirect me to login page.
I have googled and found it on stack overflow too and tried all solutions but not succeeded.I am sure it would be a silly mistake but kindly track it out.Thank You
Routes:
Route::post('login', function ()
{
$user = array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'))
);
/* Store entered username and password in an array named as 'user' */
print_r($user);
if (Auth::attempt($user))
{
return Redirect::route('home')->with('flash_notice', 'You are successfully logged in.');
/* Authentication Success!!..Redirect user to home page */
}
else
{
return Redirect::route('login')
->with('flash_error', 'Your username/password combination was incorrect.')->withInput();
/* Authentication failure!! lets go back to the login page */
}
});
User Model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
// public $timestamps = false;
/**
* The primary key of the table.
*
* #var string
*/
protected $primaryKey = 'id';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
}
User Seeder:
<?php
class UserSeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
return array('table'=>'users',
array(
'username' => 'admin',
'password' => 'admin'
),
);
}
}
When you ask the Auth class to attempt a login, you pass in the username and pass as it is. But if you look into the method, it will first hash the password to make it secure and then match it with database entry. When you are storing it, from your present implementation, its not hashed.
As suggested above, you should make this change in your seeder:
array(
'username' => 'admin',
'password' => Hash::make('password')
),
Although I am not very sure if the way you are using seeder is correct by syntax, but if it works, just hash the password there.
You should hash your password.
array(
'username' => 'admin',
'password' => Hash::make('password')
),
You can find more information in the docs.

Categories