Auth::attempt($credentials) always returns false - php

Hi there I am new to laravel and I am trying to code functionality of my login form here are the codes:
this is how I create new user (works well)
public function action_newuser()
{
$email = Input::get('email');
$password = Input::get('password');
$new_user = Input::get('new_user', 'off');
$first_name= Input::get('firstname');
$last_name= Input::get('last_name');
$username= Input::get('username');
$user = new User();
$user->email = $email;
$user->password = Hash::make($password);
$user->first_name =$first_name;
$user->last_name= $last_name;
$user->username= $username;
try{
$user->save();
}
catch(Exception $e) {
echo "Failed to create new user!";
}
This is my login function:
public function action_login()
{
$password = Input::get('password');
$username= Input::get('username');
$remember= Input::get('remember', 'off');
if($remember =='off') $remember=FALSE;
if($remember =='on') $remember=TRUE;
$credentials = array(
'username' => $username,
'password' => $password,
'remember' => $remember
);
if( Auth::attempt($credentials))
{
return Redirect::to('dashboard/index');
}
else
{
#I put this line to check are the values passed from my form are correct.
echo $password.' ' .$username.' '. $remember;
}
}
When I submit login form it always shows a blank page has values of $password, $username and $remember values. This means Auth::attempt() is not working well.
What can be the problem?

Fool me!
Although I have checked it many times, I could not see the line 'username' => 'email', in auth config file.
it should be 'username' => 'username', since I am going to use username for login.

Check to make sure that your database password field is 60 characters.

To all laravel 4 developers who are facing the Auth::attempt() login failure with valid creditials!
Solution:
In app/config/app.php change type: 'cipher' => MCRYPT_RIJNDAEL_128 to 'cipher' => MCRYPT_RIJNDAEL_256 and re-hash all passwords
In Model add method:
public function setPasswordAttribute($pass) {
$this->attributes['password'] = Hash::make($pass);
}
In UserController:
//Create User or Register
public function postCreate() {
$input = Input::all();
$user = new User;
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user = User::create($input);
return Redirect::action("Frontend\HomeController#index");
}
//Login or Sign in
public function postSignin() {
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if (Auth::attempt($userdata, true)) {
Session::put('username', Auth::user()->username);
return Redirect::action("Frontend\HomeController#index");
} else {
return Redirect::action("Frontend\UserController#getLogin")
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
Hope i have helped someone out there

Related

Logout user from all browser when password is reset in laravel 5.6

When the user changes their password, they get Logged Out from the browser. However, if they are logged into another browser at the same time they stay logged in on the other browser.
I want to log out the user from all browsers they are logged into when they reset their password.
Here login controller.
function checklogin(Request $request)
{
$this->validate($request, ['email' => 'required|email', 'password' => 'required|string|min:3']);
$user_data = array(
'email' => $request->get('email') ,
'password' => $request->get('password')
);
$remember_me = $request->has('remember') ? true : false;
if (Auth::attempt($user_data, $remember_me))
{
return redirect()->intended('dashboard');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
send mail function as below
function sendEmail(Request $request)
{
$this->validate($request, ['email' => 'required|exists:users']);
$email = $request->email;
$name = User::where('email', $email)->first();
$name = $name->name;
$token = Password::getRepository()->createNewToken();
$link = url("password/reset?email=$email&token=$token");
$value = Password_resets::where('email', $email)->first();
if (isset($value))
{
Password_resets::where('email', $email)->update(['email' => $email, 'token' => $token]);
}
else
{
Password_resets::insert(['email' => $email, 'token' => $token]);
}
Mail::to($email)->send(new \App\Mail\ResetPassword($link, $name));
return redirect()->back()->with('success', 'Please check your Email for Password Reset');
}
password reset function as below
function resetpasswordchange(Request $request)
{
$passwordtoken = $request->input('passwordtoken');
$email = $request->input('email');
$user_password = $request->input('user_password');
$users['user'] = Password_resets::where('token', $passwordtoken)->where('email', $email)->get();
if (empty($users['user'][0]))
{
$settoken = '0';
}
else
{
$settoken = $users['user'][0]->token;
}
if (($settoken) == $passwordtoken)
{
$update = array(
'password' => bcrypt($user_password) ,
);
User::where('email', $email)->update($update);
/* Auth::logout();
auth()->logoutOtherDevices(bcrypt($user_password),'password');*/
return redirect()->route('login')->with('success', 'Password has been Updated.');
}
else
{
return redirect()->back()->with('error', 'Token & Email Not Match!.');
}
}
How I can logout the user from all browsers who they are logged already ?
Open App\Http\Kernel and inside the protected $middlewareGroups property uncomment the \Illuminate\Session\Middleware\AuthenticateSession::class middleware. This compares the password hash of the user to see if the session is valid or not.

Phalcon checkHash returns false (Always)

I'm struggling with a problem. I use the Phalcon framework.
The problem is, the $this->security->checkHash() function always returns false.
What I've checked so far:
Checked the length of the varchar password field (is 255) so the hash should fit perfectly inside the field.
Currently, the code looks like this:
The register function:
public function registerAction()
{
$postData = $this->request->getPost();
/*
* Validation
*/
$validation = new RegistrationValidation();
$validationMessages = $validation->validate($postData);
if (count($validationMessages)) {
// Validation Failed!
foreach ($validationMessages as $message)
$this->flashSession->error( $message);
$this->response->redirect( $_SERVER['HTTP_REFERER'] );
$this->response->send();
} else {
// Check Passwords Match
if($postData['password'] !== $postData['password-repeat']) {
$this->flashSession->error( "Passwords don't match");
$this->response->redirect( $_SERVER['HTTP_REFERER'] );
$this->response->send();
}
}
/**
* Begin registration Process
*/
$user = new Users();
$password = $this->request->getPost('pawword');
$password = $this->security->hash($password);
$user->username = $this->request->getPost('username');
$user->email = $this->request->getPost('email');
$user->register_ip = $_SERVER['REMOTE_ADDR'];
$user->password = $password;
$user->active = 0;
// Store user
$user->save();
$this->view->emailmsg = $this->sendVerificationMail($user->id, $user->email, $user->username);
}
the login function:
public function loginAction()
{
if ($this->request->isPost()) {
$email = $this->request->getPost("email");
$password = $this->request->getPost("password");
var_dump($password);
$user = Users::findFirstByEmail($email);
var_dump($this->security->checkHash( 'edrsvc', '$2y$12$ZERPY2Q3N0hUdG1XSkw5V.DqhYek97IZyrRQwq/UP/X7xO3PiPIpG' ));
var_dump($this->security->checkHash($password, $user->password));
var_dump(password_verify('edrsvc', '$2y$12$ZERPY2Q3N0hUdG1XSkw5V.DqhYek97IZyrRQwq/UP/X7xO3PiPIpG'));
die();
if ($user) {
if ($this->security->checkHash($password, $user->password)) {
var_dump($user);
die();
$this->_registerSession($user);
$this->flash->success(
"Welcome " . $user->name
);
// Forward to the 'invoices' controller if the user is valid
$this->dispatcher->forward(
[
"controller" => "index",
"action" => "index",
]
);
}
} else {
$this->security->hash(rand());
$this->flashSession->error(
'Wrong Email or password Back'
);
}
}
}
You can see those 3 var_dumps, which are actually functioning and not throwing exceptions, but always return false. The password is of course
correct and checked twice.
The workFactor is set to Phalcon's default workFactor.

"These credentials do not match our records." Laravel 5.3

i try to create function for change password member via Dashboard Admin, and when i am trying to do a login then get this error, and i am sure i enter correct values
this is my function for update member password
public function update(Request $request, $id)
{
$rules = array(
'username' => 'required|unique:members,username,'.$id,
'email' => 'required|unique:members,email,'.$id,
'password' => 'min:8',
'retype_password' => 'min:8|same:password'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
} else {
// Input
$username = Input::get('username');
$email = Input::get('email');
$now = new DateTime();
// get old password
$members = members::where('id',$id)->first();
if (!empty('password') && !empty('retype_password')) {
$password = $members->password;
}else{
$password = bcrypt(Input::get('password'));
}
// store
$store = members::find($id);
$store->status = 1;
$store->username = $username;
$store->email = $email;
$store->password = $password;
$store->updated_at = new DateTime();
$store->save();
// redirect
return redirect('system/members')->with('success','Data successfully updated');
}
}
and this is Model members
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Notifications\MemberResetPasswordNotification;
class members extends User
{
protected $table = "members";
protected $fillable = [
'username', 'email', 'password',
];
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new MemberResetPasswordNotification($token));
}
}
this is my login function :
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
any solutions for me?
Change the logic (if/else) and there is no field like empty('password') and empty('retype_password')
if (!empty(Input::get('password')) && !empty(Input::get('retype_password'))) {
# new password
$password = Hash::make(Input::get('password'));
}else{
# old Password
$password = $members->password;
}
Make sure this use Illuminate\Support\Facades\Hash; on top
And password re-check Laravel has the easiest way to do it.
In Form
<input type="password" name="password" >
<input type="password" name="password_confirmation" > # this should be password_confirmation retype_password filed in yours
In controller
Just add this rule
'password' => 'required|min:8|confirmed', # just add confirmed thats it
Edit
Use this to login
$username = Input::get('username');
$password = Input::get('password');
if (!Auth::attempt([ 'email' => $username, 'password' => $password])) {
# error
Session::flash('error', 'Invalid Username or Password !');
return Redirect::to('admin');
}
else {
# success
return Redirect::to('admin/dashboard');
}
You should change your logic:
if (empty($request->password) && empty($request->retype_password)) {
$password = $members->password;
}else{
$password = bcrypt(Input::get('password'));
}
I think you could use the if condition like this
if ($request->input('password') && $request->input('retype_password')) {
$password = bcrypt($request->input('password'));
}else{
$password = $members->password;
}
Hope this helps

Why Laravel 5 hashes password twice?

I set hash mutator for User model:
public function setPasswordAttribute($value)
{
\Log::info('Hash');
$this->attributes['password'] = \Hash::make($value);
}
Then I have a register function. The password hashes twice (checked in logs)
public function register(RegisterNewUser $request)
{
$user = new User();
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->email = $request->email;
$user->password = $request->password;
$user->admin = true;
$user->save();
$this->auth->login($user);
return redirect()->route('dashboard');
}
Actually the function was originally written like this:
$user = new User($request->all());
$user->admin = true;
$user->save();
With the same result. Password gets hashed twice and I can't figure why.
I even tried:
get('test', function() {
$user = \CRM\EloquentModels\User::create([
'email' => 'zzz#zzz.zzz',
'last_name' => 'zzz',
'password' => 123
]);
});
And it gets hashed twice. No idea...

Auth is not working in Laravel

I am trying this code. I am already save user name and Hash::make('123') in database.
it's my controller
class EntriesController extends BaseController {
public function getIndex()
{
$username = 'saqib';
$password = '123';
$hashPassword = Hash::make($password);
if (Auth::attempt(array('username' => $username, 'password' => $hashPassword), true))
{
echo "Correct";
}
else
{
echo "Wrong";
$queries = DB::getQueryLog();
print_r(end($queries));
}
}
}
and it's routes:
Route::get('/', 'EntriesController#getIndex');
The password not in hashed.
if (Auth::attempt(array('username' => $username, 'password' => $password), true))
if you are using Auth::attempt() you don't need to hash the password. Instead just do
if (Auth::attempt(array('username' => $username, 'password' => $password), true))
Please don't hash password. Please find your below code:-
class EntriesController extends BaseController {
public function getIndex()
{
$username = 'saqib';
$password = '123';
$hashPassword = Hash::make($password);
if (Auth::attempt(array('username' => $username, 'password' => $password), true))
{
echo "Correct";
}
else
{
echo "Wrong";
$queries = DB::getQueryLog();
print_r(end($queries));
}
}
}
Note: Please check you database table "password" field its should allow 64 characters to store into it.(Hash password contains 64 characters)

Categories