EmailThis Premium lets you save unlimited bookmarks, PDF, DOCX files, PPTs and images. It also gives you a PDF copy of every page that you save. Upgrade to Premium →
Heads up: this article is over a year old. Some information might be out of date, as I don't always update older articles.
Introduction
Impersonate is quite a handy feature in some applications. It allows you to choose from a list of users and to impersonate them, in order to see the application from their point of view, without having to log out and log in again. For example, as an administrator you want to recreate a bug encountered by one of your users, without having them to share their password with you.
It's a functionality that it's really powerful, but at the same time it's easy to implement in Laravel. You just need to make sure that a normal user cannot impersonate an administrator.
Meet the impersonate Middleware
"HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application."
Middleware are additional layers that enclose the application logic, allowing modifications on the requests and responses of the application.
For example, Laravel uses a middleware that verifies if the user of your application is authenticated. If not, the middleware will redirect the user to the login screen.
We can use the same logic to login as a different user for each request. Laravel provides the Auth::once() method to log a user into the application without sessions or cookies, however it requires an array of credentials, which we don't have. The solution is to use the Auth::onceUsingId(mixed $id) method, which serves the same purpose, but it requires only the user ID.
As you can see, if the session has an impersonate value, which contains the ID of the user that we want to impersonate, our middleware starts working, logging a different user for the request.
Next we have to register our new middleware to be available for our routes. You can add it into the $routeMiddleware array inside your App\Http\Kernel.php file.
or, if you prefer, you can use POST requests to avoid accidental calls to those routes. In every case make sure that the first route is accessible only to an authenticated user which has to be an administrator.
Now we have to add a couple of additional functions to the User model. As you can see, these are only descriptive methods that interact with the Session object.
This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post تحويل الى pdf
1 comment:
This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post تحويل الى pdf
Post a Comment