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.
Related
I am building my first Laravel app with the Metronic 8 Laravel theme. It uses Breeze for authentication. I changed a couple of things around - created a welcome page for non-logged-in users, and moved the main template that was the index to an auth protected "/dashboard". The problem is that it still tries to load the dashboard Blade template, regardless of authentication, resulting in an error.
Route
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
Here's Authenticate, where it should redirect non-authenticated users to the login page.
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
When I'm not logged in and navigate to the dashboard URL, it attempts to load the dashboard Blade template, which calls a menu function that checks the user permissions for menu items. Unfortunately, since there is no user, the application blows up from passing a null value to a method expecting a user array/object.
Any ideas on where to look for the problem? It seems to me that the auth middleware should redirect to the login page before trying to load the Blade template when not logged in.
I would put the middleware at the beginning of the route like this, though I'm sure it's not causing the problem-
Route::middleware(['auth'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Aside from that, please provide some information on the error itself like what the error is about/what is says..etc...
First of all, make sure you have a login named route defined in your routes/web.php file. It should look something like:
Route::get('/login', '<controller>#<method>')->name('login');
The important bit is ->name('login') so that the Authenticate middleware can correctly identify the route to redirect to. Change <controller>#<method> appropriately to route to the login method of your app.
Wakil's answer is irrelevant and actually opposite of the documentation. Your syntax is correct.
I figured out the issue. Keen Themes put a call to a method to build an array of menu items in the web routes file. That was making the call to the offending code. After I wrapped that in an auth check the error was fixed, and everything works as expected.
Question
How can I set up Laravel routing so that:
navigating to mysite.com/login uses the LoginController
navigating to somecompany.mysite.com/login uses the TenantLoginController
What I'm doing
I'd have a Laravel 5.7 app that has a typical login page at say, mystite.com/login
I'd like to set up a subdomain for this app like somecompany.mysite.com that will have it's own authentication.
I'd like the somecompany users to log in at somecompany.mysite.com/login
What I've tried
The route definition for the main site login
Route::group(['namespace' => 'App\Http\Controllers\Auth', 'middleware' => ['web']], function () {
Route::get('login', 'LoginController#showLoginForm')->name('login');
});
The rout definition for the subsomain login
Route::domain('somecompany.mysite.com')->group(function ($router) {
$router->group(['namespace' => 'App\Http\Controllers\Tenant\Auth', 'middleware' => ['web']], function($router) {
$router->get('login', 'TenantLoginController#showLoginForm')->name('somecompany.login');
});
});
What Happened
I can navigate to somecompany.mysite.com/login and the URL bar says somecompany.mysite.com/login but when I do, the request is actually routed to the 'LoginController#showLoginForm' controller not the expected 'TenantLoginController#showLoginForm' and the typical login form is desplayed, not the subdomain's login form.
If I change the path to $router->get('tenant-login' and navigate to somecompany.mysite.com/tenant-login the subdomain login form is shown, and somecompany.mysite.com/login shows the main login form.
Since you did not specify a domain in the first route (handled by LoginController), it should also be valid for the somecompany.mysite.com subdomain.
To work around that, I would suggest trying to add more specificity to that first route, enclosing it with Route::domain('mysite.com').
The Laravel router always takes the first matching route, and that first one matches just fine in the end.
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.
In my laravel project when i click on logout and if the session is timed out it shows and error for token miss match.But i want like it goes to the login page.how to solve this.
In other pages when session timedout it goes to the login page i want same for the logout.
in my web all other pages are under the following auth middleware thats may be the reason other pages works fine.
Route::group(['middleware' => ['auth', 'changepassword']], function ()
{ }
You could add the logout route to the VerifyCsrfToken exceptions list:
protected $except = [
'your/logout/route'
];
You can find the class in App/Http/Middleware. If you have any code doing stuff in the logout function that you only want logged in users to be able to, then you would have to add checks to see if the user session has timed out and act accordingly.
I am New in Laravel, and using Laravel 5
I am storing some values in Session like this
This is in a Controller with function say ABC
Session::put('check_in', $check_in);
Session::put('check_out', $check_out);
Session::put('no_of_rooms', $no_of_rooms);
Session::put('adult', $adult);
Session::put('child', $child);
return view('room');
I am getting the values of all these Sessions in rooms view, but now the problem is when I am going to some other link or on other page from this room view and using the Session as
echo Session::get('check_in')."<br>";
echo Session::get('check_out')."<br>";
echo Session::get('no_of_rooms')."<br><br>";
echo Session::get('adult')."<br>";
echo Session::get('child')."<br>";
I am not able to get any of these Sessions value.
I am using Sessions so it has to be on all the pages till the Session flashed or browser gets closed, but its not retrieving any of the Session values..
I have seen may topics like this on Stack Overflow, but I am not able to understand those answers, Please Explain me thoroughly and solve this Problem, I am stucked at this part from last 4 to 5 days clueless.......
If your using Laravel 5.*, then you should use 'web' middleware in all routes to use session.
This looks like this: in routes.php in app/http directory
Route::group(['middleware' => 'web'], function () {
Route::Auth();
Route::get('/', 'HomeController#index');
Route::get('/login', 'UserController#userLoginView');
Route::post('/login', 'UserController#userLogin');
}
You can use session in all those routes by declaring it under 'web' middleware.
I suggest you read more about 'web' middleware in Laravel 5.
Check this out:
My Laravel 5.2.10 Sessions wont persist
NOTE: As of Laravel 5.2.27 the web middleware is now in place by default, Try removing the Route::group and see if that helps. https://github.com/laravel/laravel/blob/v5.2.27/app/Providers/RouteServiceProvider.php#L56
Create a construction __construct() in your controllers that required the user to be connected:
public function __construct()
{
$this->middleware('auth');
}
and this automatically will check if the user is authenticated if not it will redirect them to login page