How do I log in a user in Laravel? - laravel

I'm practicing manual authentication in Laravel for learning purposes, following along laracasts.com and reading the manual user authentication related documentation here - https://laravel.com/docs/5.4/authentication#authenticating-users
My login controller code is as follows:
public function loginSubmit() {
$email = request('email');
$password = request('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return 'logged in';
} else {
return 'not logged in';
}
Albeit the password not being hashed, I am using the Auth::attempt with the correct email and password information but am not able to return 'logged in'. How can I get the login to work with Auth::attempt ?

You need to hash the password
use Illuminate\Support\Facades\Hash;
$password = Hash::make($request->password);

Related

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.

Check If user has a role In Laravel 5.5

I'm using entrust package to manage roles and I have used passport for authentication since it is API's.
Actually what I need is want to check user has a role,
I have tried with below code but it doesn't work
public function Adminlogin()
{
if(Auth::attempt(['email' => request('email'), 'password' => request('password')]))
{
$user = Auth::user();
if($user->hasRole('admin'));
{
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
return response()->json(['error'=>'Abort'], 403);
}
else
{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
I want to generate access token only if user has admin role,If user has no role admin then show abort message.
if(Auth::user()->hasRole('admin'))
should work.
But you don't explain what is not working in your case so...

change password not working in laravel 5.4

i have tried to change password in laravel 5.4 it changed successfully but after that when i am trying to login again with new password it throws an error credential do not match.
here is my code-
public function UpdatePassword(Request $request)
{
$this->validate($request, [
'old_password' => 'required',
'password' => 'required|string|min:6|confirmed',
]);
$old_password = $request->old_password;
if (Hash::check($old_password, Auth::user()->password)) {
# code...
Auth::user()->update(['password'=>bcrypt($request->new_password)]);
return back()->with('message','password chnaged successfully.');
} else {
# code...
return back()->with('message_error','Please Enter Correct Old Password.');
}
}
please let me know whats wrong with code?
You've used confirmed in the password validation. You will need to pass in password or password_confirmation into the update function, not new_password
Auth::user()->update(['password'=>bcrypt($request->password_confirmation)]);
'bcrypt' the new password and then update it.
$password = bcrypt(Input::get('password'));
$user = User::where('email', $request->email)->first();
if ($user) {
$user->password = $password;
$user->save();
}
Hope this will helpful for you.

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.

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.

Resources