Laravel - Auth, route is not logged - php

I've a problem when route call a method of Controller after login successfull.
In the new method user seems to be not logged.
I can't understand why.
Steps are: Log-in with
Route::post('login', 'UserController#login')->name('login');
and than check if user is logged with:
Route::get('check-login', 'UserController#checklogged');
Controller is this one:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Faker\Generator as Faker;
class UserController extends Controller
{
// regole per FormValidator
protected $rulesLogin = [
'email' => 'bail|required|email',
'password' => 'required',
];
// Effettuo il login
/**
* Method: POST
* #Parameters: email, password
* return: Authenticated User.
*/
public function login(Request $request)
{
//dd($request->all());
$validator = Validator::make($request->all(),$this->rulesLogin);
// login fallito
if ($validator->failed()) {
return response([
'status' => 'ko',
'message' => $validator->errors()->first(),
], 422);
}
// login errato
if (!Auth::attempt([
'email' => $request->email,
'password' => $request->password,
'status' => ['active'],
])) {
return response(
[
'status' => 'ko',
'message' => 'Invalid email or password',
], 422);
}
return (Auth::user());
}
public function checklogged()
{
return dd(Auth::id());
}
checklogged() return always false. I expect it return a user logged Id

I think the problem is u havent used web midlleware in route.If you are following HMVC pattern make sure to use web middleware like this.
Route::group([
'middleware' => ['web'],
], function () {
});
or please check your RouteServiceProvider.php file weather it has web middleware in mapWebRoutes() function
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}

problem was middleware as guest.
Route::post('login', 'UserController#login')->name('login')->middleware('guest');

Try this sintaxe:
public function checklogged()
{
return dd(Auth::user()->id);
}

Related

Auth::attempt always return false even with proper input

Here are the facades I used
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
I've successfully created user signup page with hashed password using bcrypt.
//Get singnup view
public function getSignup()
{
return view('user.signup');
}
//Process signup
public function postSignup(Request $request)
{
$this->validate($request, [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
$user = new User([
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
$user->save();
return redirect()->route('product.index');
}
And now I'm stuck at the signin page. The Auth::attempt always return false. I even tried to store a plain password in my database and signin without bcrypt but it still returned false. I have no idea where I'm wrong right now.
//Get signin view
public function getSignin()
{
return view('user.signin');
}
//Process signin
public function postSignin(Request $request)
{
$this->validate($request, [
'email' => 'email|required',
'password' => 'required|min:4'
]);
$credentials = array(
'email' => $request->input('email'),
'password' => bcrypt($request->input('password'))
);
if(Auth::attempt($credentials))
{
return redirect()->route('user.profile');
}
return redirect()->route('product.index');
}
You don't need bcrypt() in Auth::attempt(). Remove it and try again.
In config\auth, change guard driver setting is set to api.
'defaults' => [
'guards' => 'api',
'passwords' => 'users'
]
But Laravel doesn't support attempt() function with guard api. Thus, you should use some packages like Passport (You can reference here)
Or simplier, just configure you guard driver with Auth::guard('api')->attempt($credentials)
Hope this solve your problem.

Why laravel 6 auth returns false after redirecting by using custom guard?

I am trying to make auth through laravel package using admins table. In the project directory I added admin guard into config/auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
And in the guard array
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
Following is my login controller inside pacakge
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/admin/dashboard';
protected function redirectTo()
{
return '/admin/dashboard';
}
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
if(Auth::guard('admin')->attempt($request->only('email','password'), true)){
return redirect()
->intended(route('dashboard'))
->with('status','You are Logged in as Admin!');
}
}
}
and following is my dashboard controller
class DashboardController extends Controller
{
public function __construct()
{
/* dd(Auth::check()); */ //return false : just want to show you
$this->middleware('auth:admin');
}
public function index()
{
return view('xyz::dashboard');
}
}
And in my Admin.php Model following script is there
namespace App;
class Admin extends \ABC\xyz\App\Models\Admin
{
}
Which is extending package model
namespace ABC\xyz\App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
protected $table = 'admins';
}
And below are the routes from my package
$namespace = 'ABC\Xyz\App\Http\Controllers';
Route::group([
'namespace' => $namespace,
'middleware' => ['web'],
'prefix' => 'admin'
], function () {
Route::get('login', function(){
return view('xyz::auth.login');
})->name('login');
Route::post('/login', 'Auth\LoginController#login')->name('customLogin');
});
Route::group(['namespace' => $namespace,'prefix' => 'admin', 'middleware' => ['auth'] ], function () {
Route::get('dashboard', 'DashboardController#index')->name('dashboard');
});
When I try to login, after submitting valid details it does not redirecting me to dashboard, nothing happening. Also when I try for open forcefully /dashboard it take me to login page.
Also right after login attempt when I try Auth::check() it's returns true but same thing returning false in dashboardController.php construct function. In the same way Auth::guard('admin')->user() returns user's info while on dashboardController.php it's returns null.
Strange Result of php artisan route:list
As you can see in DashboardController.php construct I added $this->middleware('auth:admin');
So when I try to add dd(Auth::guard('admin')->user()) and then check in terminal php artisan route:list it returns null and sometime false, any idea why it is happening?
I don't know what and where I am missing something.
I would like to request you kindly guide me about it. I would appreciate.
Thank you
The problem is in your routes file:
Route::group(['namespace' => $namespace,'prefix' => 'admin', 'middleware' => ['auth'] ], function () {
Route::get('dashboard', 'DashboardController#index')->name('dashboard');
});
You are using the default guard with auth middleware. After you are logged in with admin guard you may not be logged in by your default web guard. That is why it fails and tries to redirect you to login page:
When I try to login, after submitting valid details it does not redirecting me to dashboard, nothing happening. Also when I try for open forcefully /dashboard it take me to login page.
Instead, you should specify in your group that you are using the admin guard:
Route::group(['namespace' => $namespace,'prefix' => 'admin', 'middleware' => ['auth:admin']], function () {
Route::get('dashboard', 'DashboardController#index')->name('dashboard');
});
However, you already specified in your DashboardController to use $this->middleware('auth:admin');, so there is no need to specifiy it in the route group again. The following is enough and reduces the likelihood to create an error:
Route::group(['namespace' => $namespace,'prefix' => 'admin'], function () {
Route::get('dashboard', 'DashboardController#index')->name('dashboard');
});
An extraction sample of the how you should define your admin model:
// app/Admin.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use Notifiable;
protected $guard = 'admin';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
For more on multiple authentications guards see: How to use multiple authentication guards
Auth::guard('admin')->attempt($request->only('email','password') its returning true or false? If returning false then maybe toy didnt hashed your password
Try add this in your Model
public function setPasswordAttribute($password)
{
$this->attributes['password'] = Hash::make($password);
}
Please note that the Auth::check doesn't work on construct. this is because the middleware hasn't run yet, so Auth::check() should return false or null when you try to check in construct.
In your login controller, why are you using two redirectto?
protected $redirectTo = '/admin/dashboard';
protected function redirectTo()
{
return '/admin/dashboard';
}
it is better to stick with one :-)
inside your Admin.php , add this:
protected $guard = 'admin';
for your web.php routes, replace
Route::group(['namespace' => $namespace,'prefix' => 'admin', 'middleware' => ['auth'] ], function () {
Route::get('dashboard', 'DashboardController#index')->name('dashboard');
});
with
Route::group(['namespace' => $namespace,'prefix' => 'admin', 'middleware' => ['auth:admin'] ], function () {
Route::get('dashboard', 'DashboardController#index')->name('dashboard');
});
finally, in DashboardController.php
replace the
/* dd(Auth::check()); */ //return false : just want to show you
With:
$this->middleware(function ($request, $next) {
dd(Auth::check()); //return false : just want to show you
die;
});
Auth::check() should return true!

test if user is logged in laravel 5.7

I am making a test but it fails when it tries to check if a user is logged in:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use App\User;
class RegisterTest extends TestCase
{
use RefreshDatabase;
/*.....
more test about registering
....*/
/** #test */
function redirect_to_home_page_and_logged_in_after_login()
{
$user = factory(User::class)->create([
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
$response = $this->post('login', [
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
}
And this is my controller HomeController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class HomeController extends Controller
{
public function index()
{
if (Auth::check()){
return view('home');
}
return view('welcome');
}
}
And this is my routes/web.php
Route::get('/', 'HomeController#index');
Auth::routes();
I am not sure what I am doing wrong. What can I do?. I am using laravel 5.7 and phpunit 5.7.1
Also in my app/Htpp/Auth/LoginController.php I did this:
protected $redirectTo = '/';
Thank you.
In addition to hashing your password you could also just post to the register route and create a new account.
/** #test */
function redirect_to_home_page_and_logged_in_after_register()
{
$response = $this->post('register', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
I guess you may also have a requirement to do it both ways:
/** #test */
function redirect_to_home_page_and_logged_in_after_login()
{
$user = factory(User::class)->create([
'name' => 'Test',
'email' => 'test#hotmail.com',
// note you need to use the bcrypt function here to hash your password
'password' => bcrypt('123456')
]);
$response = $this->post('login', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
Creating a user requires you to take care of the hashing of the password.
You can simply do it by using php's password_hash function. And use Auth::login($user); to login.
Like so:
$user = User::create(['email' => 'r#o.b', 'password' => password_hash('123456', 1)]);
Auth::login($user); //You should be logged in :)

Login Fail in laravel 5.2 using AuthenticatesUsers trait

I'm using the AuthenticatesUsers trait to handle logins in my web site.
When I register a new user on the site it can login and logout successfully, but when I login through the login form it fails every time even though I'm providing the right data. I don't understand why this is happening. What did I do wrong? Here is my auth controller.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/home';
protected $guard = 'user';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'first_name' => $data['firstName'],
'last_name' => $data['lastName'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Route.php
<?php
Route::group(['middleware' => ['web']], function () {
// Your route here
// // Authentication routes...
Route::get('customer/login', 'Customer\Auth\AuthController#getLogin');
Route::post('customer/login', 'Customer\Auth\AuthController#postLogin');
Route::get('customer/logout', 'Customer\Auth\AuthController#getLogout');
//
// // Registration routes...
Route::get('customer/register', 'Customer\Auth\AuthController#getRegister');
Route::post('customer/register', 'Customer\Auth\AuthController#postRegister');
Route::auth();
Route::get('/home', function (){
return view('welcome');
});
});
Route::get('/home', 'HomeController#index');

laravel 5.2 - Auth::user()->username is empty

If I use Auth::user()->username in a Blade file laravel returns me an empty String but Auth::user()->email is filled. I use my own AuthController and my Login,Register and Logout work perfectly but I can't get the username.
Routes.php
<?php
Route::group(['middleware' => ['web']] , function () {
Route::get('/', function () {
return view('welcome');
})->name('home');
});
Route::group(['middleware' => ['web','guest']], function () {
Route::auth();
#Sign up Routes
Route::get('/signup', function () {
return view('auth.signup');
})->name('auth.signup');
Route::post('/signup', 'AuthController#signup');
#Sign in Routes
Route::get('/signin', function () {
return view('auth.signin');
})->name('auth.signin');
Route::post('/signin', 'AuthController#signin');
});
Route::group(['middleware' => ['web','auth']], function () {
Route::auth();
#Sign out Routes
Route::get('/signout', 'AuthController#signout')->name('auth.signout');
});
And my custom Auth Controller is:
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AuthController extends Controller
{
public function signup(Request $request) {
$this->validate($request, [
'email' => 'required|unique:users|email|max:255',
'username' => 'required|unique:users|alpha_dash|min:2|max:20',
'password' => 'required|min:6'
]);
User::create([
'email' => $request->input('email'),
'username' => $request->input('username'),
'password' => bcrypt($request->input('password')),
]);
return redirect()->route('home');
}
public function signin(Request $request) {
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('flash-message','We can not sign you in with this data!');
}
return redirect()->route('home');
}
public function signout() {
Auth::logout();
return redirect()->route('home');
}
}
Maybe someone can help me
.
Note:
I added the username into User.php under the filled array.
Most likely you are missing username in $fillable of your User model.
The create method only accept fields coming from $fillable.
Please edit your User model like this:
protected $fillable = [
'email', 'username', 'password',
];
Only $fillable fields insert by Create method.

Categories