Handle every request in laravel 5 - laravel

I have laravel project and I want to create access log table. in route file is it possible handle every request and its parameters to store in database.

You can create middleware and handle all request with it. Then put all your routes in a group to apply your middleware.
Route::group(['middleware' => 'yourMiddleware'], function () {
// All your routes
});

Yes, it is possible. Create your own service provider and register it, then in boot method create script that logs requests to database.
Example:
public function boot()
{
if (! app()->runningInConsole()) {
App\Request::create(['payload'=>serialize(app('request')->all())]);
}
}

Related

Verify access token with Database in laravel

In my laravel project, I am allowing user to generate a token which will be stored in tenants Database. Now when an API is called ,at that time I want to verify this token with the token stored in DB. How to do that ?? How can I achieve this using middleware ?? Please advise
You could verify it in middleware as follows:
create a middleware file with command php artisan make:middleware EnsureTokenIsValid
Now go to app/Http/Middleware and find EnsureTokenIsValid middleware. Then, on handle method you should implement your logic with something like:
public function handle($request, Closure $next)
{
// you have to get token from database below line is just an example
$tokenInDatabase = TenanentModel::find(1);
if ($request->input('token') !== $tokenInDatabase) {
// if token not match redirect to home page
// or implement your logic
return redirect('home');
}
return $next($request);
}
Next, you need to register your middleware on app/Http/Kernel.php as mentioned in https://laravel.com/docs/9.x/middleware#assigning-middleware-to-routes. Example:
'ensureTokenIsValid' => \App\Http\Middleware\EnsureTokenIsValid::class,
Next, add to the route. Example:
Route::get('/profile', function () {
//
})->middleware('ensureTokenIsValid');
You could find more details about this on: https://laravel.com/docs/9.x/middleware#defining-middleware

LImit Access on pages. to prevent access pages without login

as we know when we code on localhost we can go directly to dashboard admin on our website without login first by typing the link. so how we can stop that? so if we want to access the admin dashboard we really have to log in first
use laravel middleware to limit accesses ... you can use auth middleware like:
Route::get('/profile', function () {
//
})->middleware('auth');
for more info visit laravel docs
use laravel middleware in your web.php if you are using a simple function for your route
Route::get('/admin/dashboard',function () {
return view....``
})->middleware('auth');
Or you can use a constructor in your Controller to limit access for all function in this controller
public function __construct()
{
$this->middleware('auth');
}

How to create single endpoint for authenticated or non-authenticated User in laravel?

I need a single endpoint where I can check if User authenticated then can return some user-related data else(if not-authenticated) some basic information that I want.
I tried by checking user having a token or not in the api.php file. but it is not working.
The example below is basically generated by following the official documentation.
//file: ./routes/web.php
use Illuminate\Support\Facades\Auth;
Route::get('profile', function () {
if (Auth::check()) {
return Auth::user();
} else {
return ['foo' => 'bar'];
}
});
Have in mind that this is extremely simplified example.
In a real world case use probably you would have a route pointing to a controller method where you can auto-inject the Illuminate\Auth\AuthManager.
Also you wouldn't be returning the whole user object, but rather transforming the response to your needs.

Use Policies with apiResource Routes

Currently I'm writing a Laravel 5.6 REST api. Now I want to secure my endpoints:
Each user in my application has a role. Based on that the user should be able to access some endpoints and otherwise should get a 403 error. For this I would like to use Policies because, when used as middleware, they can authorize actions before the incoming request even reaches my route or controller.
I declare my endpoints like this:
Route::apiResource('me', 'UserController');
My problem now is that if I want to use Policies as middleware I have to specify the (HTTP) method like this middleware('can:update,post'). How should I do this when I use apiResource in my route declaration?
BTW: Currently I have written a FormRequest for each method (which is a pain) and do the authorization there. Can I simply return true in the authorize method after switching to Policies middleware?
Since you are using FormRequest::class to validate the request data, it is best practice to first check is the user is authorized to make the request. For Laravel 5.6 the cleanest solution would be to specify each policy manually in the __construct() method of your resource controller.
public function __construct()
{
$this->middleware('can:viewAny,App\Post')->only('index');
$this->middleware('can:create,App\Post')->only('store');
$this->middleware('can:view,post')->only('show');
$this->middleware('can:update,post')->only('update');
$this->middleware('can:delete,post')->only('delete');
}
If your were validating form data inside your controller instead of using FormRequest::class, a cleaner solution would be to also authorize the user inside the controller.
public function store(Request $request)
{
$this->authorize('create', Post::class);
// The user is authorized to make this request...
$request->validate([
//Validation Rules
});
// The form data has been successfully validated...
// Controller logic...
}
Since Laravel 5.7 you can do all of this using one line of code on your controller's __construct() method.
public function __construct()
{
$this->authorizeResource(Post::class, 'post');
}
You can define route groups, routes that have a common behaviour (middleware, prefix etc. ).
The following should work:
Route::middleware('can:update,post')->group(function () {
Route::apiResource('me', 'UserController');
//more routes
});
You can prefix routes as well:
Route::middleware('can:update,post')->group(function () {
Route::prefix('users')->group(function () {
Route::apiResource('me', 'UserController'); //Translated to ex: /users/me
Route::prefix('books')->group(function () {
Route::apiResource('{book}', 'UserController'); //Translated to ex: /users/me/book_1
});
});
});
P.S: I haven't used resources before but it should do the job

How to log all routes acess?

I build api service using laravel.
I want to log all acess to the api routes
I though somewhere in the routes.php put some code that get the requested route? any help? thanks
laravel 4
You can define a route filter first
Route::filter('log', function($route, $request, $response)
{
// log work
});
then apply the filter to your route
Route::get('api', array('before' => 'log', function()
{
return 'logged!';
}));
I think you can also get the log from the access log of your web server.

Resources