I am using Laravel 5.1 for my project. I am trying to secure Routes and make sure only logged in user can access certain routes. I am aware about middlewares but I am wondering if anyone post an example or a link explaining about middleware and how to protect a page using middleware.
Thanks
To build on the answer given by Joe Rose, you can also specify the middleware in your controller rather than in your routes.php file.
E.g you could have your routes set out like
Route::get('/example', 'ExampleController#index');
Route::post('/example/post', 'ExampleController#post');
Route::resource('blog', 'BlogController');
And then inside your controller reference it like so:
class ExampleController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
//....
If you're looking for more info, check out the link to the docs Joe gave, and also this blog post which explains what middleware is really well and how to create your own if you need to.
You are correct about using middleware. The included Auth middleware is what you should use, as long as you are also using the included Auth controller to authenticate users. You would write your route like this:
Route::get('/page', array(
'uses' => 'Controller#method',
'middleware'=>'auth'
));
(The above example is using a GET request, but it could other request types, like POST for example).
This will use the default behavior of the middleware which checks to see if the user is logged in (authenticated). You can also extend or overwrite the built-in functions to allow you to direct the application on where to send the user if they are or are not logged in, etc. Laravel's official documentation is a good starting point: link
Related
I started creating a REST API using the lumen framework and wanted to set up a particular behaviour for my GET /user route. Behaviour is the following:
If the request come from an authenticated user (using auth middleware), the method getAllFields from UserController is called and return all the data from the user
If it's not the case, the method get from UserController is called and return some of the data from the user
It seems logic to me to just write it like that in my web.php using a simple middleware:
<?php
$router->group(['middleware' => 'auth'], function () use ($router) {
$router->get('/user/{id}', [
'uses' => 'UserController#getAllFields'
]);
});
$router->get('/user/{id}', [
'uses' => 'UserController#get'
]);
But for some reason, even if the middleware is correct, I always get the response of the second route declaration (that call get()). I precise that if I remove the second route declaration, the one in the middleware work as expected.
Have someone an idea how I can achieve something similar that work?
Router will check if your request matches to any declared route. Middleware will run AFTER that match, so You cannot just return to router and try to find another match.
To fallow Laravel and Routes pattern - You should have single route that will point to method inside controller. Then inside that You can check if user is logged or not and execute getAllFields() from that controller. It will be not much to rewrite since You are currently using UserController in both routes anyway.
web.php
$router->get('/user/{id}', 'UserController#get');
UserController.php
public function get()
{
return auth()->check() ? YourMethodForLogged() : YourMethodForNotLogged();
}
Or if there is not much logic You can keep this in single method.
Also it is good idea to fallow Laravels REST standards (so use show instead of get, "users" instead of "user" etc - read more https://laravel.com/docs/7.x/controllers)
web.php
$router->get('/users/{user}', 'UserController#show');
UserController.php
public function show(User $user)
{
if (auth()->check()) {
//
} else {
//
}
}
To summary - for your needs use Auth inside controller instead of middleware.
To check if user is logged You can use Facade Auth::check() or helper auth()->check(), or opposite Auth::guest() or auth()->guest().
If you are actually using Lumen instead of full Laravel then there is not auth helper by default (You can make own or use package like lumen-helpers) or just keep it simple and use just Facades instead (if You have then enabled in Lumen).
Read more https://laravel.com/docs/7.x/authentication and https://lumen.laravel.com/docs/7.x/authentication
This pattern is against the idea of Laravel's routing. Each route should be defined once.
You can define your route without auth middleware enabled and then define your logic in the controller.
I'm building enterprise modular Laravel web application but I'm having a small problem.
I would like to have it so that if someone goes to the /api/*/ route (/api/ is a route group) that it will go to an InputController. the first variable next to /api/ will be the module name that the api is requesting info from. So lets say for example: /api/phonefinder/find
In this case, when someone hit's this route, it will go to InputController, verifiy if the module 'phonefinder' exists, then sends anything after the /api/phonefinder to the correct routes file in that module's folder (In this case the '/find' Route..)
So:
/api/phonefinder/find - Go to input controller and verify if phonefinder module exists (Always go to InputController even if its another module instead of phonefinder)
/find - Then call the /find route inside folder Modules/phonefinder/routes.php
Any idea's on how to achieve this?
Middlewares are designed for this purpose. You can create a middleware by typing
php artisan make:middleware MiddlewareName
It will create a middleware named 'MiddlewareName' under namespace App\Http\Middleware; path.
In this middleware, write your controls in the handle function. It should return $next($request); Dont change this part.
In your Http\Kernel.php file, go to $routeMiddleware variable and add this line:
'middleware_name' => \App\Http\Middleware\MiddlewareName::class,
And finally, go to your web.php file and set the middleware. An example can be given as:
Route::middleware(['middleware_name'])->group(function () {
Route::prefix('api')->group(function () {
Route::get('/phonefinder', 'SomeController#someMethod');
});
});
Whenever you call api/phonefinder endpoint, it will go to the Middleware first.
What you are looking for is HMVC, where you can send internal route requests, but Laravel doesn't support it.
If you want to have one access point for your modular application then you should declare it like this (for example):
Route::any('api/{module}/{action}', 'InputController#moduleAction');
Then in your moduleAction($module, $action) you can process it accordingly, initialize needed module and call it's action with all attached data. Implement your own Module class the way you need and work from there.
Laravel doesn't support HMVC, you can't have one general route using other internal routes. And if those routes (/find in your case) are not internal and can be publicly accessed then also having one general route makes no sense.
Laravel newbie here (obviously :D ). I've set up a new model & controller for a model named Pages.
Every User has many Pages.
Each Page has a single User.
I've created the following functioning controller actions (& views):
PagesController::index
PagesController::create
PagesController::store
PagesController::show
PagesController::edit
PagesController::delete
So you can edit a Page by going to url.dev/pages/{id}/edit.
The problem is, you can access all of these routes regardless of your session status. So random users can edit any given Page. Which, obviously, is terrible.
Can anyone point me in the direction of what I should read up on, to limit the ability to access my model's controller actions based on whether or not the user is logged in (and if it's the correct user, at all)?
To force a specific route to be only accessible by authenticated users you can specify middleware auth in the controller constructor, like so:
public function __construct()
{
$this->middleware('auth');
}
Also you can restrict which methods you want auth to be applied to in the controller, using the only or except parameters. Using only you could do:
public function __construct()
{
$this->middleware('auth', ['only' => ['create', 'store', 'edit', 'delete']]);
}
You´re looking for middleware..
You can read more here
public function __construct()
{
$this->middleware('auth')->only('index');
$this->middleware('admin')->except('store');
}
Other answers are good, but I prefer to use middleware on route groups.
So when I have several routes like this:
Route::get('pages', 'PagesController#index')->name('pages.index');
Route::get('pages/{id}/edit', 'PagesController#edit')->name('pages.edit');
I would add them inside Laravel Route group. Like this:
Route::group(['middleware' => 'auth'], function() {
Route::get('pages', 'PagesController#index')->name('pages.index');
Route::get('pages/{id}/edit', 'PagesController#edit')->name('pages.edit');
});
I have two types of users: "vendors" and "clients". And I'm currently using Laravel's built-in Auth Controllers (from the make:auth command) to do my client user authentication.
And since I have two kinds of users, I have changed the $redirectTo property on the LoginController, RegisterController, and ResetPasswordController to /client/home.
Here is proof:
RegisterController
LoginController
Now, it redirects to /client/home every time I successfully do registration, login, and password reset.
But the problem is when I'm in mysite.com/client/home already, whenever I would try to go to mysite.com/register or mysite.com/login via the address bar, it would redirect to mysite.com/home instead of mysite.com/client/home...
How can I make it redirect to mysite.com/client/home whenever an authenticated user tries to go to /login or /register?
The simplest option is to create separate controllers for both of your login areas. It will be easier to manage later on, and you can customise the behaviour a bit better.
The default folder structure looks like this:
app
|__Http
|__Controllers
|__Auth
|__ForgotPasswordController.php
|__LoginController.php
|__RegisterController.php
|__ResetPasswordController.php
You could create an additional folder for your client controllers, like so:
app
|__Http
|__Controllers
|__Auth
| |__ForgotPasswordController.php
| |__LoginController.php
| |__RegisterController.php
| |__ResetPasswordController.php
|__Client
|__Auth
|__ForgotPasswordController.php
|__LoginController.php
|__RegisterController.php
|__ResetPasswordController.php
This way you can customise the $redirectTo properties of each controllers individually.
As an alternative solution, you could overwrite the redirectPath of the RedirectsUsers trait, by creating a redirectPath method in your respective controllers, and return the URL you'd like:
public function redirectPath()
{
if (\Request::is('client/*'))
{
return url('client/home');
}
return url('home');
}
The advantage of this second solution is that you can return controller actions and named routes as well. I personally don't like routing to URLs, as if I ever decide to change them, then I'll have to change them everywhere. Using controller actions seems like a better idea, but you could run into the same problem if you refactor your code later on. I prefer using named routes, as I can give them a sensible name, and never change them again, yet still keep all my redirects in a working order.
I would like to create an administrator interface for my Laravel project, which is completely separated from the user side.
For example, in Yii framework I can make a module and this will ensure full separation from the user side. Inside a module I can use separate folder structure etc.
This is really a broad question and one answer can't cover everything about best practice for admin controllers or back end management but there are some basic concepts for building an Admin Panel:
// Keep all of your admin routes inside something like this
Route::group(array('prefix'=> 'admin', 'before' => 'auth.admin'), function() {
// Show Dashboard (url: http://yoursite.com/admin)
Route::get('/', array('uses' => 'Admin\\DashBoardController#index', 'as' => 'admin.home'));
// Resource Controller for user management, nested so it needs to be relative
Route::resource('users', 'Admin\\UserController');
});
// Other routes (Non-Admin)
Route::get('login', array('uses' => 'AuthController#showLogin' 'as' => 'login'));
By using a prefix you may separate all admin routes whose url will be prefixed with admin so, if you have a users controller for user management in back end then it's url will be prefixed with admin, i.e. site.com/admin/users. Also using a before filter you may add an authentication for all admin controllers in one place, that means, to access all of your admin controllers user must be logged in and the filter could be something like this:
Route::filter('auth.admin', function($route, $request, $args){
// Check if the user is logged in, if not redirect to login url
if (Auth::guest()) return Redirect::guest('login');
// Check user type admin/general etc
if (Auth::user()->type != 'admin') return Redirect::to('/'); // home
});
For, CRUD (Create, Read, Update, Delete) use a resourceful controller, for example, the UserController in an example of resourceful route declaration.
Use repository classes (Repository Pattern) for decoupling of dependencies, read this article.
Always use a named route, i.e. array('as' => 'routename', 'uses' => 'SomeController#method'), this is an example of naming a route. Named routes are easy to refer, i.e. return Redirect::route('admin.home') will redirect to site.com/admin because we have used admin.home in as to assign the name for that route.
Keep admin controllers in a separate folder and use a namespace for example, Admin\\DashBoardController#index controller should be in app/controllers/admin and your DashBoardController controller should look like this:
<?php namespace Admin;
class DashBoardController extends \BaseController {
public function index()
{
//...
}
}
There are more but it's enough to start with, read articles online and must read the documentation.
If you are familiar with composer you can import in packages (aka modules)
There is a widely available module with multi level interface already called Sentry 2.0:
https://github.com/cartalyst/sentry
You could also make your own if needed if the one I propose is too complex.
There is even a "laravel-ready" version of sentry.
I use the same directory structure that you would like to use on most (if not all) my Laravel projects. Basically, I keep admin views and admin controllers separate from the front-end ones.
Examples:
Controllers:
app/controllers/admin/Admin*Name*Controller.php
app/controllers/site/*Name*Controller.php
Views:
app/views/admin/some_folder/index.blade.php
app/views/site/some_folder/index.blade.php
I would also suggest that you install this laravel project https://github.com/andrewelkins/Laravel-4-Bootstrap-Starter-Site which will give a very good starting on how to organise things in your laravel project. It also has the same folder structure you would like to use.
Good luck.