Laravel Authentication doesn't work - php

I'm working with laravel 5.2, and I have a problem with customized authentication. It doesn't log the user on .
Here you can find my code for the function:
public function login(Request $request)
{
$this->validateLogin($request);
$email = $request->get('email');
$user = User::where('email', $email)->first();
if(! is_null($user))
{
if (Auth::login($user))
{
return redirect('/profile');
}
}
else
{
$this->register($request);
}
}
In the place of Auth::login, I tried also the function attempt and check, but nothing was working ...
It logs the user, but it showed a blank page, without redirecting to the url.

You are seeing a blank page instead of being redirect to '/profile' because your second if condition is never true as
Auth::login($user)
never returns a null even if user is logged in
so basically
if (Auth::login($user))
{
return redirect('/profile');
}
this is if condition is never satisfied in your case.
You can try this
public function login(Request $request)
{
$this->validateLogin($request);
$email = $request->get('email');
$user = User::where('email', $email)->first();
if(! is_null($user))
{
Auth::login($user);
if (Auth::check())
{
return redirect('/profile');
}
}
else
{
$this->register($request);
}
}
Auth::check();
will return true if the user is logged in and will be redirected to '/profile'.

Related

Double authentication connection cannot be redirected

I am trying to set up a double authentication page under laravel, for that I add a checkTotp method that verifies that the user has activate double authentication and redirect this user to the page in question.
The problem is that I am not redirected and the code continues to execute.
public function login(Request $request)
{
$this->validateLogin($request);
...
$this->checkTotp($request);
dd('after');
...
}
protected function checkTotp(Request $request)
{
$user = User::where('email', $request->get('email'))->first();
if (!is_null($user->totp_key)) {
$request->session()->put('user_id', $user->id);
return redirect('login/totp');
}
}
What happens is that I enter the checkTotp method but the redirect does not work. My output is the dd('after'). I don't understand why I am not redirected. Can someone help me?
Quentin
The checkTotp function returns a redirect, but you want the login function to return that redirect, such that it is passed to the browser. You might want to move the redirect to the main function and let checkTOTP just return true/false.
public function login(Request $request)
{
$this->validateLogin($request);
...
if ($this->checkTotp($request)) return redirect('login/totp');
dd('after');
...
}
protected function checkTotp(Request $request)
{
$user = User::where('email', $request->get('email'))->first();
if (!is_null($user->totp_key)) {
$request->session()->put('user_id', $user->id);
return true;
}
return false;
}

RedirectIfAuthenticated redirect if attempt to open other login form

I have two login forms with two different tables.One is default with /login route and the other has route /myportal. I have extra logincontroller
protected $redirectTo = '/student-home';
public function showLoginForm()
{
return view('my_portal');
}
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/my_portal');
}
protected function guard()
{
return Auth::guard('web_student');
}
public function username ()
{
return 'username';
}
This login is working fine. But, I am having problem with RedirectIfAuthenticated
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
else if(Auth::guard('web_student')->check())
{
return redirect('student-home');
}
return $next($request);
}
Now, if the user is already logged in, it is redirected to /student-home only if the route is /login and not /my-portal. i.e only if i click on regular form not this extra form I created. How can I redirect to student-home if user clicked on /my-portal?
You can connect a controller to the my-portal route with :
Route::get('test', 'exampleController#example') ;
Then in the controller function, you can check if the user is already logged in by
public function example() {
if(Auth::check()) {
//This condition will run if the user is logged in !
return redirect('student-home');
}
//Do whatever you want if user is not logged in!
}
Hopefully, this answers your question!
Please change your RedirectIfAuthenticated middleware like this
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if(guard == 'web_student') {
return redirect('student-home');
}else return redirect('/home');
}
return $next($request);
}
The problem with your code is that the following segment will always true if a user is logged in. You have to check for whether or not a specific guard is set, inside this if statement if you want to redirect them accordingly.
if (Auth::guard($guard)->check()) {
return redirect('/home');
}

Auth doesn't work on custom middleware

I have modified Login function in LoginController and this is what I have written
public function login(Request $request)
{
$data = $request->all();
if($this->validateLogin((array)$data))
{
$cred = $request->email;
$cred_p = $request->password;
//if()
$user = User::select('id', 'password')->where('email','=',$cred)->first();
if(count($user) == 1)
{
if(Hash::check($cred_p, $user->password))
{
$user_id = $user->id;
$status = User_status::select('is_active', 'is_completed')->where('user_id','=',$user_id)-> first();
$active = $status->is_active;
//dd($status->is_active);
if($active == 0)
{
return redirect()->to('/login')->withErrors(['status'=>"Your account is blocked. Please contact administrator or visit here <a href='/support/acount-blocked'>Support Center</a>"]);
}
else
{
$this->attemptLogin($request);
$this->sendLoginResponse($request);
}
}
else
{
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
}
else
{
return $this->sendFailedLoginResponse($request);
}
}
else
{
return $this->sendFailedLoginResponse($request);
}
}
This seems to work fine and Auth::user() is working but when I add new middleware that is IsCompletedMiddleware and I check dd(Auth::user()); this returns null value.
public function handle($request, Closure $next)
{
/*if(Auth::user()->status->is_completed == 0)
{
return redirect()->to('/profile/management/complete');
}*/
return $next($request);
}
I have also included use Auth; in the header of middleware but it always returns null value. And in other controllers Auth::user() returns proper user. Why is this so? And what is missing. Please help thank you.
In your middleware you have to get the user is doing the request, try to do this:
public function handle($request, Closure $next)
{
$request = $next($request);
if($request->user()->status->is_completed == 0){
return redirect()->to('/profile/management/complete');
}
return $request;
}

can not login with laravel attempt return false everytime

Here is my SessionController
public function store()
{
//Attempt to authenticate user
if(! auth()->attempt(request(['email', 'password']))){
return back();
}
return redirect()->home();
}
Password populated with plain text, and am inputting correct email and password, but its not logging me in :(
here is my route
Route::get('/login','SessionController#create');
Route::post('/login','SessionController#store');
Looking forward for your respected answers and comment.
You Should also Need to Pass (Request $request) in store function.
Also bcrypt() Your Password.
Hope this may help you.
public function store(Request $request)
{
//Attempt to authenticate user
if(! auth()->attempt(request(['email', 'password']))){
return back();
}
return redirect()->home();
}
please check with this code:
use Auth;
use Session;
use Redirect;
public function store (Request $request) {
$username = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $username, 'password' => $password])) {
return redirect()->intended('admin_dashboard');
}
else {
Session::flash('message', 'User name or password is incorrect!');
return redirect('/')->with('message', 'User name or password is incorrect!');
}
}
Use the same routes which you used.

how to remember a user who is login

I have created a sign in form with a remember me checkbox. I want to know how can i allow user to keep sign in when the browser is closed or sign out person when they close the browser. A sample code would be nice thank you.
here is my code
class HomeController extends BaseController {
public function getIndex()
{
if(Auth::check())
{
return Redirect::to('profile');
}
return View::make('index');
}
public function postRegister()
{
//gets array of the register form input values
$value = Input::all();
// create a new instance of the User model
$user = new User;
$validate = $user->userValidate($value);
//checks if the validation for the field fails
if($validate->fails())
{
/* $message = $validation->messages();
return $message; */
return Redirect::back()->withInput()->withErrors($validate);
}
//adds the users input to speicific field in the users table
$user->user_name = $value['username'];
$user->email = $value['email'];
$user->password = Hash::make($value['password']);
//save the inputs to the users table
$user->save();
return 'information has been stored';
}
public function getRegister()
{
$title = 'Register';
return View::make('register')->with('title',$title);
}
public function getSignIn()
{
$title = 'Signup';
return View::make('signup')->with('title',$title);
}
public function postSignIn()
{
//user's information
$credentials = array('email' => Input::get('email'),'password'=>Input::get('password'));
//logs this user in and checked if they are registered already in
if(Auth::attempt($credentials,false))
{
return Redirect::to('profile');
}
return Redirect::back()->withInput();
}
}
You just have to turn it on in your login method:
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
// The user will now be logged in and remembered
}
else
{
// Raise a login error
}
This "true" parameter is to remember your user.
Here is the Laravel Auth::attempt() method declaration:
public function attempt(array $credentials = array(), $remember = false, $login = true)
{
...
}
You could set a cookie on the users browser (make sure you tell them if you are) to identify them. But beware that this could be modified by a malicious user.
PHP Cookies Documentation

Categories