Auth not persisting in Laravel 5.2 - php

I have my auth doing this on login.
if (Auth::attempt($userdata)) {
dd(Auth::user()); //this shows the user just fine,
//which proves that the auth driver is working.
return redirect()->intended('dashboard');
}
However, after redirecting to the dashboard. It appears the auth isn't persisted. If I do dd(Auth::user()) or even just Auth::check() it returns null.
Here's the route:
Route::group(['middleware' => ['web']], function () {
Route::get('test',function(){
dd(Auth::user()); //returns null
echo Auth::user()->name; // returns Trying to get property of non-object
});
});
What am I doing wrong?
The weird thing about this is that last night it was working. It kinda just magically stopped working.

The solution to this is not an obvious one, specially coming from older versions of laravel.
Thanks to this link.
Auth Session killed in Laravel 5.2
I was able to solve it, so I'll post the answer to help others who encounter the same issue.
Originally I just had this in my routes.
Route::post('app/login', 'Auth\AuthController#doLogin');
Route::group(['middleware' => ['web','auth']], function () {
Route::get('test',function(){
dd(Auth::user());// was always returning null
});
});
But, to get the login to persist, I had to do this
Route::group(['middleware' =>[ 'web']], function () {
Route::post('app/login', 'Auth\AuthController#doLogin');
});
Route::group(['middleware' => ['web','auth']], function () {
Route::get('test',function(){
echo Auth::user()->name;
});
});
Apparently any route thats going to call or register a session needs to employ the 'web' middleware.

Just add the "auth" middleware to your "test" route and try accessing it while logged in. It shouldn't give you any errors that way. If you try to access it without logging in, it should redirect you to whatever route is defined in the "auth" middleware.
By using "auth" middleware, you are basically ensuring that Auth::user() will always return a proper User instance.
Now, if this works then you can be sure that Laravel Auth is indeed persisting the user and the issue is somewhere else in your code.
I haven't noticed any issues with the Auth class in Laravel.

Related

How to use session data (auth) in the Laravel routes page

We have a large website with many pages. Almost all of them require the user to log in. Instead of specifying "Auth" on every single page, or on every single controller, I would like to set the routes based on if the user is logged in, like this:
// in web.php
if (Auth::isLoggedIn()) {
Route::get('/', function () { return view('pages/dashboard'); });
... lots more
}
The reason I can't do this is because Auth uses sessions, and sessions are not yet initialized in web.php, since it is done as middleware which is not run yet at this point.
I'm using Laravel 8, I believe.
Thanks.
you can group the route that need the user to be logged in, then use auth middleware
for the grouped routes:
Route::middleware(['auth'])->group(function () {
Route::get('/', function () {
//
});
Route::get('/', function () { return view('pages/dashboard'); });
});
Try using Laravel's Route middleware. Route middleware can be used to only allow authenticated users to access a given route.

Laravel How to get web or auth middleware to work

Developing a Laravel packages and in the routes I have this routes
Route::middleware(['web'])->group(function () {
Route::get('/pckOne', 'Frutdev\LaravPck\Controllers\PckController#getIndex');
Route::get('/pckZone', 'Frutdev\LaravPck\Controllers\PckController#getZone');
Route::post('/pckZone', 'Frutdev\LaravPck\Controllers\PckController#postZone');
Route::get('/pckUsers', 'Frutdev\LaravPck\Controllers\PckController#getUsers');
Route::get('/pckUser', 'Frutdev\LaravPck\Controllers\PckController#getCurrentUser');
Route::get('/pckArea', 'Frutdev\LaravPck\Controllers\PckController#getArea');
Route::post('/pckArea', 'Frutdev\LaravPck\Controllers\PckController#postArea');
Route::get('/{Area}/pckZones', 'Frutdev\LaravPck\Controllers\PckController#getAreaZones');
Route::post('/{Area}/pckZone', 'Frutdev\LaravPck\Controllers\PckController#postAreaZone');
});
The routes are not being authenticated.
I tried with the web middleware but can still see/access the routes while not logged in.
I tried with the auth middleware but even after logging in with the default Laravel loggin in system(which wasn't altered) I can't access the routes. It says I'm unauthorized, even after logging in. Any idea?
GET /login whenever I try to go with the auth middleware to /pckOne returns a 302 Found status.
To have the auth middleware functional you need something like the following:
Auth::routes();
Route::group(['middleware' => ['auth']], function () {
// Home Controller After Logging In
Route::get('/', 'HomeController#index')->name('home');
});
This means it will check auth before running the GET route. If you're signed in then great it'll run, if not your middleware will throw the sufficient redirect back to the login page as an example.

Laravel 5.2 session not persisting

Lately I've been working on a project in Laravel 5.2 and now I'm having problems with sessions not persisting. I've read most of the questions already asked regarding this but everyone has the same answer that I have already tried - applying web middleware.
I've read that there was a new L5.2 update where the web middleware group is already applied by default. I checked my routes with php artisan route:list and I can see that every route has only 1 web middleware applied.
I'm creating session with $request->session()->put('key', 'value') but as soon as I comment that line the session is nowhere to be seen anymore.
Edit
I want to set the session inside a controller when I visit a news page, but I tried it on a simple test route as well. Route where I set this is news/{id} and I want to use it on the front page which is in /
I wish to store recently visited pages in session so I can then show it to the user on the front page.
Session config file I left untouched. So it's using file driver
Here is a tested routes to use for your projects
Please use a middleware instead of the function in the routes file
routes.php
// Only as a demo
// Use a middleware instead
function addToSession ($routeName) {
$visited = session()->get('visited', []);
array_push($visited, $routeName);
session()->put('visited', $visited);
}
Route::get('/', function () {
addToSession('/');
return view('welcome');
});
Route::get('/second', function () {
addToSession('/second');
return view('welcome');
});
Route::get('/third', function () {
addToSession('/third');
return view('welcome');
});
Route::get('/history', function() {
return session()->get('visited');
});
The /history route will return a JSON having the history.

laravel 5.2 authentication - Missing Links

I am new to laravel framework and trying to build up authentication for a website. There is something really strange thats happening and I am not able to figure out whats wrong.
I issue php artisan make:auth command and I could see the corresponding files getting generated under controllers and the resources/views. I am able to login and see the homepage (after login). I am able to logout as well and everything works smoothly so far.
now sometimes there seems to be a problem when I am away from the browser for sometime, and come back to the website, it starts acting wierd. the app loses the information about the current logged in user. If I go to the home page (the actual homepage of the website and not the page after the login), then the login page ("/login") does not show up. I have to manually logout (by typing "/logout" in the url) and then try the login url to see the login form.
this is my routes file:
Route::get("/", "PagesController#home")->name("home");
Route::get("/search/{query}","APIController#index")->name("search");
Route::get("/searchBook/{id}","APIController#searchBook")->name("searchBook");
Route::get("/stories","PagesController#stories")->name("stories");
Route::get("/user/{id}/deleteBooks/{book_id}","UserController#deleteBooks")->name('user.delete.books');
Route::get("/user/{id}/showBooks/{book_id}","UserController#showBooks")->name('user.show.books');
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::resource('user', 'UserController');
Route::get('/user/{user}/books',"UserController#books")->name('user.get.books');
Route::post("/user/{user}/createBooks","UserController#createBooks")->name('user.create.books');
Route::get('/home', 'PagesController#dashboard')->name("dashboard");
Route::post("/savemap","UserController#savemap")->name("savemap");
});
Also, It seems the app in itself is not really taking care of the authentication. I manually have to check the authentication (by Auth::check()) at lot of steps and it is painful. For example at many places I have to manually do
if (Auth::check()) {
// some code
}
else{
Auth::logout();
return redirect()->route('home'); //named route
}
This is an update : A route which was giving me issues was not placed under the web middleware in the routes.php file. So when I placed the concerned route under the web middleware, I was actually able to access all the Auth:: parameters and the current logged in user.
Does this mean that I have to place all my "logged-in" routes (available routes after logging in) inside the web middleware? and what about the /login, /logout routes... Should they be places any middleware?
Any route you need sessions (which Auth uses) needs to have the 'web' middleware group applied.
If you want to do auth checks you can use the 'auth' middleware which will do those checks for you.
Example:
Route::group(['middleware' => ['web', 'auth']], function() {
Route::get('mustbeauthed', 'SomeController#someMethod');
});
In this case going to the 'mustbeauthed' will redirect you away if you are not authenticated and let you pass through to it if you are authenticated.

Laravel 5 multiple "dashboard" route for admins and managers

(I have asked this question before, and did find a way around which worked for a while, but soon got out of hand. So now I am looking for a perfect solution to achieve this, the Laravel way.)
The problem is pretty simple, when admin goes to http://example.com/dashboard they should see the admin dashboard and when manager goes to the same link he should see the managers dashboard.
The way around that I used before was to call the pagecontroller and then depending on the user role call the relevant admin's or manager's dashboard controller.
// ROUTES.php
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', 'PagesController#dashboard');
Route::get('users', 'PagesController#manageUsers');
});
// PagesController
public function dashboard(){
if($this->user->isAdmin()){
return $controller = app()->make('App\Http\Controllers\Admin\dashboard')->index();
}
if($this->user->isManager()){
return $controller = app()->make('App\Http\Controllers\Manager\dashboard')->index();
}
}
Now the problem with this approach is that I can no longer call the middleware on the dashboard controller because the process doesn't involve calling the kernel.
I am pretty sure there must be a way to achieve such a basic feature, I would be really grateful if someone can sort this out.
I think the reason this isn't a Laravel default feature because it kinda goes counter to what routes are supposed to represent. In other words, this isn't the Laravel Way. Why not redirect the user depending on their role?
// ROUTES.php
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', function() {
if($this->user->isAdmin())
return redirect('/dashboard/admin');
if($this->user->isManager())
return redirect('/dashboard/manager');
return redirect('/home');
});
Route::get('dashboard/admin', 'Admin\dashboard#index');
Route::get('dashboard/manage', 'Manager\dashboard#index');
Route::get('users', 'PagesController#manageUsers');
});

Categories