Can't authenticate user with Laravel Auth::Atempt - laravel

I'm struggling myself trying to find the reason but can't. It always falss to "else". I'm using sqliteand this is my code:
public function doLogin(Request $request)
{
$email = $request['email'];
$password = $request['password'];
if ( Auth::attempt(['email' => $email, 'password' => $password]) )
return redirect()->route('home');
return redirect()->back();
}
route
Route::post('/doLogin',['as' => 'doLogin', 'uses' => 'Auth\LoginController#doLogin']);
Already printed the variables, the values are exatcly the same as the database.
Possible cause of the problem ?
Testing the Variable Receiving Value (Prints the right values)
$usuario = \App\User::find(1)->pluck('email', 'password');
return ($usuario);
Printed Value:
{"teste123":"teste#teste.com"}
Also, If I try this:
public function doLogin(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
dd($request->all());
}
I get this:
array:4 [▼
"_token" => "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
"email" => "teste#teste.com"
"password" => "teste123"
"action" => null
]
Is it normal action = null ?

It looks like you're storing your passwords in your database as plaintext, and that seems to be the issue. You should never do this, as if you have a security leak, then the infiltrator could easily have access to all of your users' passwords.
That also seems to be the issue as to why your Auth::attempt is failing. Auth::attempt goes into SessionGuard.php, which eventually calls validateCredentials from EloquentUserProvider.php. This function hashes the password it is given and checks that against what is in the database. Laravel is expecting your password in the database to be hashed (by default it is bcrypt), so the passwords are not matching. It hashes the plaintext password from the $request so it no longer matches the plaintext in your DB.
Laravel comes with the command php artisan make:auth. If you use this, then you shouldn't have to do your doLogin function. You can just send the logins along the default route. Then when you're testing, sign up your account through the registration to ensure that it's saved in your database in a hash, instead of plaintext.

Related

How to get Laravel Login query? I can't pass the login page

I wanna get the Login query because I have some problem on login page.
Actually there's no error when I used Laravel Migrations (the login system worked at all), after a day, I tried again but using SQL Manually and got a problem.
I wanna know what does Laravel do with sql query, seems laravel do query on wrong fields.
I've tried to use DD($request->all()); and the output like this
Die Dump output
^ If you notice at the password, it doesn't encrypted.
But in my database, it's encrypted
password field
And this happen if i didn't use DD
Login credentials do not match
function on LoginController.php for login using username or email, i found this code from this tutorial
protected function validateLogin(Request $request)
{
$this->validate(
$request,
[
'identity' => 'required|string',
'password' => 'required|string',
],
[
'identity.required' => 'Username or email is required',
'password.required' => 'Password is required',
]
);
// dd($request->all());
}
/**
* #param Request $request
* #throws ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
$request->session()->flash('login_error', trans('auth.failed'));
throw ValidationException::withMessages(
[
'error' => [trans('auth.failed')],
]
);
}
You can try something mentioned here: https://laracasts.com/discuss/channels/general-discussion/authenticate-on-custom-fields-laravel-53
basically laravel is looking for a specific field name while using default auth, but since yours differ from that you have to change them manually
Please try to use laravel's default authenticatication using this command
php artisan make:auth

Password with FirstOrCreate

I want to use FirstOrCreate for a new user.
Like that:
$user = User::FirstOrCreate([
'name' => $request->username,
'email' => $request->email,
'password' => User::generatePassword()
]);
generatePassword() just generate a random 8 chars string string.
Thing is is doesn't work because it's looking for a user that has this password value.
So, it works when there is no user with this email, but when there is it gives me a constraint error.
What should be the cleanest way to fix it???
You've made a grammatical error. ::firstOrCreate searches based on criteria provided, and if it's not found, it will create the database entry and return the model with that data. ::firstOrNew does that without saving the model automatically.
So, you would want this.
$user = User::firstOrNew([
'email' => $request->email,
]);
We do not include name or password because we are not checking to see if Josh with josh#stackoverflow.com using password foobar123 exists, we just want to know if josh#stackoverflow.com has an account.
Your controller logic seems a bit weird because we would first want to validate that information before creating a model, but I'll roll with it.
$user = User::firstOrNew([
'email' => $request->email,
]);
// This model does not have a DB record.
if (!$user->exists)
{
$user->name = $request->username;
$user->password = User::generatePassword();
$user->save();
}
return $user;
With that logic, we find a record based on email. If the record exists, we pass it. If it does not, we assign it a username and generate a password for it before creating the record and then pass it.

Lumen, authentication attempt always returns false (jwt or auth)

I made a small API with the php lumen framework.
Now I'm integrating a jwt authentication (following this tuto http://laravelista.com/json-web-token-authentication-for-lumen/) for my application but as I attempt to login, it always returns false...
It doesn't seem to be a problem with jwt directly because the token generation works but only the login doesn't work. As I saw, jwt use the Lumen Auth:: to login, so to be sure I tried to login with Auth::attempt() directly instead of JWTAuth::attempt, but the result is false too...
Here is my code:
try
{
$validation = $this->validate($request, [
'email' => 'required|email',
'password' => 'required'
]);
$credentials = $request->only('email', 'password');
$isAuthenticated = Auth::attempt($credentials) || JWTAuth::attempt($credentials);
$user = User::first();
$token = JWTAuth::fromUser($user);
$result = [
'isAuthenticated' => $isAuthenticated,
'token' => $token
];
// ... catch exceptions + return $result or errors from exceptions
I made some search to correct the common mistakes with this kind of problems, and I already checked that:
I have a table named users
in which I have a password column and an email column (full lowercase names)
db password column is varchar(140)
and tried to create and login a user like this:
$user = new User;
$user->email = 'example#domain.com';
$user->password = Hash::make('passwordExample');
$user->save();
//And login with it:
$userData = array(
'email' => 'example#domain.com',
'password' => 'passwordExample');
return (string) Auth::attempt($userData));
my auth config contains :
'driver' => env('AUTH_DRIVER', 'eloquent'),
'model' => env('AUTH_MODEL', 'App\Models\User'),
'table' => env('AUTH_TABLE', 'users'),
my App\Models\User model implements Illuminate\Contracts\Auth\Authenticatable and use Illuminate\Auth\Authenticatable
But no changes... I always get a 'false' !
What can be the problem?
Here are the framework version I use (from composer.json)
"laravel/lumen-framework": "5.1.*",
"vlucas/phpdotenv": "~1.0",
"doctrine/dbal": "~2.3",
"illuminate/mail": "^5.1",
"tymon/jwt-auth": "^0.5.6",
"basicit/lumen-vendor-publish": "^1.0",
"illuminate/support": "5.1.25",
"illuminate/routing": "5.1.25"
Note : I also notice that for the same password hashed twice, the result is not the same. As I read, it's normal and the Auth knows how to check the hashed stored password. But I don't get it... How does he check the password if the hashed result is never the same? It stores a salt for each hash?
Well... Took me a while but I figured out how to login properly...
If I set the password without hashing it :
$user = User::select('id', 'email')
->where('email', $email)
->first();
$user->password = $newPassword;
$user->save();
and I look in the db what was inserted, the password is stored encrypted...
Then if I try to login with :
$this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required'
]);
$credentials = $request->only('email', 'password');
if ( $token = JWTAuth::attempt($credentials) )
...
it works properly.
So my problem was that I hashed twice the password before inserting it.
But I don't really understand why it's automatically hashed because as I saw in the doc, I have to do it explicitely. So if anyone can give me the reason, I would be very intersted to know it.
Anyway, I should have used Hash::needsRehash($hashed) directly...

Laravel Auth:attempt not working in test?

I've been trying to simply change a password, and then authenticate it, and Auth::attempt has been returning false:
$email = "test6#mycompany.com";
$pass = md5("123");
$credentials= [ 'email' => $email,
'password' => $pass];
$user = User::where("email" , $email)->first();
$user->password = $pass;
$user->save();
dd(Auth::attempt($credentials));
I also have this part in the user model...
public function setPasswordAttribute($pass){
$this->attributes['password'] = Hash::make($pass);
}
Does anyone have any ideas what could I be doing wrong?
This always happen, just as I post the question, I have an epiphany...
my password field was too short to contain the password so it always saved only part of the hashed string.

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)

Resources