Laravel 5.4 Can't login the user - laravel

When I register new User, it logs in, but when I logout and try to login it just redirects me back to login page with custom error message 'Check your credentials again'. I can't figure out what's wrong.

First you are not hashing the password. In RegistrationController change your store() function like this.
use Hash;
class RegistrationContoller extends Controller
{
...
public function store()
{
...
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password) //<-- you were missing this.
]);
}
}

Related

User cannot login that registers from a custom registration page In Laravel 8

I created a custom register controller. The user who registers through my custom register class cannot log in, but those who register from the default register page can log in. Am I missing something for the custom registration page?
class AdminController extends Controller
{
public function AdminAgentDataAdd(Request $request)
{
$password = Hash::make($request->password);
$request->merge(['password' => $password]);
$request->merge(['role' => 3]);
$DataAddCheck = User::create($request->all());
if ($DataAddCheck) {
return back()->with('successMsg',
'Agent Created Successfully');
} else {
return back()->with('successMsg',
'Something Went Wrong Try Again!');
}
}
}
Note: The user creates successfully in my DB.
This is how laravel/breez does the registration
// After the validation
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
// fields you added
'role'=>3,
'phone'=>$request->phone,
]);

How can I disable auto login after registration in laravel 8?

In using laravel 8 with fortify so I don have
App\Http\Controllers\Auth\RegisterController
Thanks in advance
First you must create a controller preferably in app\Http\Controllers\Auth called RegisteredUserController, in this controller you must overwrite the method store of the class RegisteredUserController.
Copy the store method to your new controller and delete the line $this->guard->login($user);.
It should look like this:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Laravel\Fortify\Contracts\RegisterResponse;
class RegisteredUserController
extends \Laravel\Fortify\Http\Controllers\RegisteredUserController
{
public function store(Request $request, CreatesNewUsers $creator): RegisterResponse {
event(new Registered($user = $creator->create($request->all())));
return app(RegisterResponse::class);
}
}
Finally change the default /register path that points to your new controller.
Route::post('/register', 'Auth\RegisteredUserController#store');
Fortify will automatically login an user only if you return the user from the CreateNewUser class. Instead of returning the created user, throw an exception along with a flash message. Fortify will try to redirect you to the home page and will return you back to the login page as user is not authenticated showing you the flash message. Below is a peek at the process in the file App\Actions\Fortify\CreateNewUser.
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique(User::class),
],
'password' => $this->passwordRules(),
])->validate();
$user = User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password'])
]);
event(new Registered($user));
flash('Registration successful! Awaiting approval from admin.')
->success()
->important();
throw new \Illuminate\Auth\AuthenticationException\AuthenticationException();
}
I think there might be other solution to hook into any of the Fortify events to do that even more gracefully.

Always remember users in Laravel

How could I make it so that in my laravel sign in controller, users are always remembered?
I tried making $remember_me = 1
but that doesn't seem to work.
Controller:
public function postSignin(Request $request, AppMailer $mailer) {
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$username = $request->get('email');
$password = $request->get('password');
$field = filter_var($username,FILTER_VALIDATE_EMAIL)? 'email': 'username';
Auth::attempt([$field => $username, 'password' => $password], true);
return redirect()->back()->with('info', 'You are now signed in.');
}
Start of Home controller:
public function getIndex() {
if (Auth::check()) {
if (Auth::viaRemember()) {
dd('test');
}
Edit: I changed the code a bit to explain why the current answer isn't working for me.
You may pass a boolean value as the second argument to the attempt method, which will keep the user authenticated indefinitely, or until they manually logout. Of course, your users table must include the string remember_token column, which will be used to store the "remember me" token.
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
// The user is being remembered...
}
If you are using the built-in LoginController that is shipped with
Laravel, the proper logic to "remember" users is already implemented
by the traits used by the controller.
If you are "remembering" users, you may use the viaRemember method to determine if the user was authenticated using the "remember me" cookie:
if (Auth::viaRemember()) {
//
}
EDIT :
Check your config/session.php setting:
'lifetime' => 10080,
'expire_on_close' => true,
Just set your expire_on_close to true
Hope this helps you!

Can Laravel Auth::attempt() handle relationships?

I'm using entrust for managing role based permissions in Laravel 5.3, and naturally using manual/custom logins for different user types. Is it possible for Auth::attempt() to handle foreign table relationships? Basically, I want to do something like this:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password, hasRole('teacher') => true])) {
return redirect()->intended('teacher/dashboard');
}
But I keep getting the error that hasRole() is an undefined function. I have included use Zizaco\Entrust\Traits\EntrustUserTrait; and use EntrustUserTrait;, which I thought would provide me with access to the function, but apparently not.
I appreciate the fact that hasRole() is a method for user objects, and at the time of checking I don't have a user object but I can't do a role check after attempt has succeeded because then the user has already been logged in, and if the role was wrong I would need to log them out as their credentials are correct, but not for the role; which seems slow and not pragmatic.
How should I go about handling this? Is there an alternative to Auth::attempt that I can use that will not log in the user, but check the user exists with specified input, and then run the role check, and then use another function to start an authenticated session?
If useful my LoginController is here:
<?php
namespace App\Http\Controllers\Teacher;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Validator;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class LoginController extends Controller {
use EntrustUserTrait;
public function showLoginForm() {
return view('teacher/login');
}
public function authenticate(Request $request) {
Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
])->validate();
if(Auth::attempt(['email' => $request->email, 'password' => $request->password, hasRole('teacher') => true])) {
return redirect()->intended('teacher/dashboard');
}
return redirect('admin/login')->with('invalid', 'Invalid username or password');
}
}
Any help or direction would be much appreciated. Thanks.
what you can do is:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password)) {
if($user = Auth::user()->hasRole('teacher')) {
return redirect()->intended('teacher/dashboard');
} else {
return redirect()->intended('teacher/dashboard');
}
}
so this is what I did on login check role
$user = User::whereEmail($request->email)->first();
// I added this is because the customer
// are not suppose to login from here
if(!$user || $user->hasRole(['customer'])){
return $this->sendFailedLoginResponse($request);
}
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
then if you wanna to change the route base on user role you can try to replace the redirectPath method by simply
public function redirectPath()
{
$user = Auth::user();
if($user->hasRole(['admin', 'system_admin']))
return '/backend';
elseif($user->hasRole(['teacher']))
return '/teacher';
}
I ended up manually doing the authentication check and using Auth::login($user) to create the authenticated session. This way the user was only logged in provided they met the role requirements for the specific login portal and controller.
public function authenticate(Request $request) {
Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
])->validate();
$user = User::where('email', $request->email)->first();
if($user) {
if(Hash::check($request->password, $user->password) && $user->hasRole('teacher')) {
Auth::login($user);
return redirect()->intended('teacher/dashboard');
}
}
return redirect('teacher/login')->with('invalid', 'Invalid username or password');
}

How to redirect after auth in Laravel?

When I authorize in Laravel 5.3 I redirect to /home page.
I tried to change this on: protected $redirectTo = '/order'; in file LoginController.
But It does not work, I am redirected on home still.
In my UserController.php , I hope email and passwords are the things you use for user signin.
public function userSignIn(Request $request)
{
$this->validate($request,[
'email' => 'required|email',
'password' => 'required'
]);
if(Auth::attempt(['email'=>$request['email'],'password'=>$request['password']])){
return redirect()->route('order');
}
return redirect()->back();
}
You must have a route for order in your route.php file.

Resources