Laravel 5.2 Auth::login($user) not working - laravel

I am writing a Laravel 5.2 application. I need to manually login the user for which I am using \Auth::login($user). I am doing it in following way.
if ($user = User::where('phone',session('phone'))->first())
{
\Auth::login($user);
// \Auth::loginUsingId($user->id);
// Auth::attempt(['email' => $user->email, 'password' => 'password']);
$data = \Auth::user(); //returning correct results
}
I have tried all the options namely Auth::login($user), Authh:loginUsingId($user->id) and attempt method. These methods are working fine as the $data variable is storing the object of correct user. But the problem is when I move to other route say '/home' the user remain no more authenticated.
What might be the wrong here? How could I do it correctly?

Since Laravel 5.2, you have to attach all your routes that need session with the 'web' middleware. See your app/Http/Kernel.php, the 'web' middleware contains the \Illuminate\Session\Middleware\StartSession.

In routes you have to use web in laravel 5.2
Route::group(['middleware' => ['web', 'auth']], function () {
Route::get('/', 'HomeController#index');
Route::get('/profile', 'HomeController#profile');
});

Related

Register user with Vue.js and Laravel

Created a page of login with vue.js.
Sent the data to a laravel controller to create a new user.
I sent the data to a controller in laravel to create a new user.
After creating the user, I'm trying to redirect to home, with the user authenticated, but when redirecting to home, it goes to login page.
Vue requisition
register(){
axios.post('/api/register', this.form)
.then(response => {
window.location.href = "/home";
});
}
Route API
Route::post('register', 'Api\RegisterController#register');
Controller Laravel
public function register(Request $request){
$data = $request->validated();
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Auth::login($user);
Auth::guard()->login($user);
// Auth::loginUsingId($user->id);
return response()->json(['message' => 'Salvo com sucesso.','user' => $user]);
}
Route WEB, that is accessed after registration:
Route::group(['middleware' => ['auth']], function () {
Route::get('/home', function(){
return view('home')
});
});
I tried with the code,redirect to home, authenticated , but it is going to the login screen, because of the middlware.
Is there any way to go to the home screen automatically authenticated after registration, without having to log in?
When you're registering using Ajax, Laravel is not using sessions to prevent authentication from unsafe origins, so you end up having no authentication for the current user session even after login.
You need to use other auth guard for stateless auth. There are a bunch of variants, but most simple for you will be Sanctum, which store XSRF-TOKEN in cookies and take auth data from there instead of session.
As an alternative, you may consider using JWT, or other token based authentication, but you still will probably experience some troubles with session as I see you not having your front-end as SPA:
window.location.href = "/home";

Laravel passport public api routes

I am trying to code a login function for my api that takes a username and password then give you a password grant token to make api requests. The login route when called gives you
{
"message": "Unauthenticated."
}
I am using passport on laravel to do secure the api. Why am I getting a 401 when the route does not have the auth:api middleware? I tried using a clousure to see if I get could get a response and the closure did not give me an error.
Route::group(['prefix' => '/v1', 'middleware' => ['auth:api'], 'namespace' => 'Api\V1', 'as' => 'api.'], function () {
Route::post('/post/like','PostLikeController#store');
});
Route::group(['prefix' => '/v1', 'namespace' => 'Api\V1', 'as' => 'api.'], function () {
Route::post('login', 'Auth\LoginController#login');
});
Does your login controller have a constructor? sometimes middleware is set in there?
Otherwise I've also had issues with having the middleware routes above the public ones.
Try putting the public routes in the file first and also checking the LoginController.php for a constructor which might be setting a middleware
It possibly due to the same prefixes, as it does not overriding but instead stacking on top of each other.
I suggest for your login route, possibly, you can use this
Route::post('login', 'Auth\LoginController#login')->withoutMiddleware([FooMiddleware::class]);
If it's still does not help try putting your login route above the middlewared route.

Laravel Method [index#index] does not exist

I had Laravel 4.2 application and updating it to Laravel 5.4. for this i have installed fresh Laravel 5.4 and migrated routes,controllers views etc.
I want to protect all pages after /warehouse e.g /warehouse/dashboard,/warehouse/accounts and so on except /warehouse/login page. I have searched and used this route but its not working properly.
Can any one let me know whats the proper way of authentication.
Route::group(['middleware' => ['auth']], function() {
// uses 'auth' middleware
Route::resource('/warehouse','WarehouseController#index');
});
My login and verify routes are
Route::get('/warehouse/login', array('as' => 'WarehouseAdminLogin', 'uses' => 'WarehouseController#login'));
Route::post('/warehouse/verify', array('as' => 'WarehouseAdminVerify', 'uses' => 'WarehouseController#verify'));
For Route:resource there is no need to add function name after controller.
So try this:
Route::resource('/warehouse','WarehouseController');
And for Auth middlware you can do this :
Route::middleware(['auth']->group(function() {
// Auth routes
});
And it's obvious that login route should no be inside auth middleware!
How can a new guest user see login page?
Use Auth routes outside the auth middleware :
Route::get('login', 'Auth\LoginController#showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController#login');
Route::get('logout', 'Auth\LoginController#logout')->name('logout');

Laravel multi auth protecting route multple middleware not working

I have created an extra middleware admin and I want to protect my routes. Adding one single middleware 'auth' or 'auth:admin' is working.
Route::get('/calendar', function () {
return view('app', ['data' => []);
})->middleware('auth');
But I want that as an admin you can also access the user routes but this is not working. If I try the following, and I log in as an admin I get redirected to the login page all the time.
Route::get('/information', ['middleware' => ['auth', 'auth:admin'], function () {
return view('app', ['data' => ['auth' => Auth::check()]]);
}]);
But if I change ['auth', 'auth:admin'] to ['auth:admin','auth'] it is working for admin but not for user. So it seems that only the first element of my middleware in array is being recognized. Does anybody have any idea why my multiple middlewares are working seperate but not together? Any help is appreciated
If you are trying to allow multiple 'guards' to be checked for a route you can pass multiple guards as parameters to the Authenticate middleware, auth.
auth:web,admin (assuming web is your default guard).
This will try to resolve a user (Authenticatable) from each guard passed in. If any guard returns a user (Authenticatable) you pass through authenticated. If not you are a guest.
If you set the middleware auth and auth:admin those are 2 separate 'middleware' in the stack that are unrelated.
Route::get('/information', ['middleware' => ['auth', 'auth:admin'],function () {
return view('app', ['data' => ['auth' => Auth::check()]]);
}]);
in this code. ['auth', 'auth:admin'] that's mean you need to login default guard and admin guard. if you need only login admin guard, ['auth:admin']

auth logout doesn't work laravel

I made the files for authentication using the command
php artisan make:auth
I've read on the internet that register, login, as well as logout should work properly, but localhost:8080/logout doesn't work, and I don't know why.
I also read something about modifying AuthController in app, but I do not have that file.
I tried to do it by hand, which means I created a middleware LogoutRedirect:
public function handle($request, Closure $next)
{
return redirect(pages.logout);
}
In the routes I added
use App\Http\Middleware\LogoutRedirect;
Route::get('logout', function()
{
return view('pages.logout');
})->middleware(LogoutRedirect::class);
And logout.blade.php looks like
{{ Auth::logout() }}
I get the error (when trying to access localhost:8080/logout)
Use of undefined constant pages - assumed 'pages'
What could I do about it?
EDIT
I tried another approach (but with no better results):
renamed the route which redirects to '/' to 'home'
made a LogoutController in app/http/Controllers/Auth
namespace App\Http\Controllers;
use [...]
class LogoutController extends Controller
{
public function logout() {
Auth::logout();
return Redirect::route('home');
}
}
made the route
Route::post('logout', array(
'as' => 'account-sign-out',
'uses' => 'Auth\LogoutController#logout'
));
The error I get is
MethodNotAllowedHttpException in RouteCollection.php line 233:
That's the same error I get when I try to use the default logout defined in auth
You are trying to access the logout page with GET. But this doesn't work because your logout route is a post route.
Change
Route::post('logout', array(
'as' => 'account-sign-out',
'uses' => 'Auth\LogoutController#logout'
));
by
Route::get('logout', [
'as' => 'account-sign-out',
'uses' => 'Auth\LogoutController#logout'
]);
When you go to the /logout route with the method GET(The default when you go to a page) it should work.

Resources