how to create middleware in octobercms - php

I'm new to OctoberCMS but I have moderate knowledge about Laravel.
In Laravel it is easy to create middleware and group more than one middleware.
In OctoberCMS I can't find proper guidelines or a satisfactory answer yet.
Does anyone know how to create middleware and group more then one middleware in OctoberCMS ?

In your plugin folder, use the file Plugin.php to set up your middleware
You must declare in boot function like this :
public function boot()
{
// Register middleware
$this->app['Illuminate\Contracts\Http\Kernel']
->pushMiddleware('Experty\Experts\Middleware\ExpertsMiddleware');
}
and in ExpertsMiddleware.php
<?php namespace Experty\Experts\Middleware;
use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Http\Response;
use October\Rain\Exception\AjaxException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExpertsMiddleware implements Middleware
{
/**
* The Laravel Application
*
* #var Application
*/
protected $app;
/**
* Create a new middleware instance.
*
* #param Application $app
* #return void
*/
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
//youre code
}
}

Related

Query Parameters not working when default api prefix is changed to something else

I am using Laravel 7.0.
I have created a new module and in the new modules RouteServiceProvider.php file changed the prefix of the API routes to cp.
I am now trying to send some query parameters but nothing is received in the controller action method.
Here you can see the Laravel Telescope also not showing any query parameters. I checked the Nginx logs and query parameters are present there.
php artisan route:list is showing the route correctly.
Here is the code of the controller.
<?php
namespace Modules\SomeModule\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class PartnerController extends Controller
{
/**
* List all Partners
*
* #param Illuminate\Http\Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function index(Request $request)
{
$page = $request->query('page'); // it is always null
$pageSize = $request->query('page_size'); // it is always null
return response()->json(['page' => $page, 'page_size' => $pageSize]);
}
}
Here is the code of RouteServiceProvider. I am using nWidart/laravel-modules package to generate modules in my app.
<?php
namespace Modules\SomeModule\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* The module namespace to assume when generating URLs to actions.
*
* #var string
*/
protected $moduleNamespace = 'Modules\SomeModule\Http\Controllers';
/**
* Called before routes are registered.
*
* Register any model bindings or pattern based filters.
*
* #return void
*/
public function boot()
{
parent::boot();
}
/**
* Define the routes for the application.
*
* #return void
*/
public function map()
{
$this->mapApiRoutes();
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* #return void
*/
protected function mapApiRoutes()
{
Route::middleware('api')
->prefix('cp')
->namespace($this->moduleNamespace)
->group(module_path('SomeModule', '/Routes/api.php'));
}
}
When I changed the API prefix back to api it works absolutely fine.
Can someone please guide what is going on here? Thanks!

Laravel route middleware outputting my log

I'm trying to run some middleware on my routes via my package's service provider before the routes run in my Laravel project but I'm not seeing my var_dump despite running php artisan route:list showing that the BeforeMiddleware is applied. Am I using the wrong middleware?
My service provider:
<?php
namespace Company\FudgeInboundManagementBridge;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Company\FudgeInboundManagementBridge\Http\Middleware\BeforeMiddleware;
class FudgeInboundManagementBridgeServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
$this->registerFiles();
}
/**
* Register files
*/
protected function registerFiles(): void
{
Route::middleware(BeforeMiddleware::class)->group(function () {
$this->loadRoutesFrom(__DIR__.'/routes/fudge-routes.php');
});
$this->publishes([
__DIR__ . '/config/FudgeInboundManagementBridge.php' => config_path('FudgeInboundManagementBridge.php'),
], 'config');
}
}
My middleware:
<?php
namespace Company\FudgeInboundManagementBridge\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class BeforeMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
var_dump('hello from before middleware - bridge');
die;
// return $next($request);
}
}
Seems like it's not triggering?

Trying to get property of non-object on Laravel Middleware Role

I'm trying to make middleware role for my authentication in my project, this is my middleware called sales.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Sales
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->user()->role == "sales"){
return $next($request);
}
return redirect()->route('login')->with('error',"You don't have an access");
}
}
and this is the route i protect from middleware
Route::get('dashboard','DashboardController#index')->middleware('sales')->name('dashboard');
and when i try to access dashboard to make sure my route is protected by middleware, it shows error like this
Trying to get property of non-object
i appreciate if you answer this !
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Sales
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::User()->role=='sales'){
return $next($request);
}
return redirect()->route('login')->with('error',"You don't have an access");
}
}

Creating Multiple Auth Providers in Lumen

I am trying to create multiple Auth Guards and services for my API. I want specific group to be available to specific users (more like RBAC without sessions).
If a user tries to access a group that has admin:auth as middleware its privileges will be checked. If it has api:auth then no privilege check.
I can't understand how to do this. I have added the following lines in the bootstrap/app.php
$app->routeMiddleware([
'admin' => App\Http\Middleware\Admin::class,
'api' => App\Http\Middleware\Api::class,
]);
And:
$app->register(App\Providers\AdminServiceProvider::class);
$app->register(App\Providers\ApiServiceProvider::class);
and created the Files Admin.php and APi.php in Middleware folder with the following content (basically same as Authenticate.php with name changes)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class Admin
{
/**
* The authentication guard factory instance.
*
* #var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* #param \Illuminate\Contracts\Auth\Factory $auth
* #return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
return response('Unauthorized.', 401);
}
return $next($request);
}
}
And the AdminServiceProvider and ApiServiceProvider in the App\Providers folder with just this in function boot():
var_dump($this->app['api']);exit;
And this on top:
namespace App\Providers;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class ApiServiceProvider extends ServiceProvider
But I get the Following Error:
What am I missing? I have already done composer dump-autoload, no difference.
Regards
Well what I ended up using is more like a work around, but I think this might be how it is supposed to be used.
So what I did was that I created two groups (a parent and a child) with the middlewares I needed as follows:
$app->group(["middleware" => "middleware1"], function() use ($app){
$app->group(["middleware" => "middleware1"], function() use ($app){
$app->post("/signin", "AppController#signin");
}
}
This way, the signin route is reached after going through 2 middlewares.
Regards

Laravel: How to access session value in AppServiceProvider?

Is there any way available to access Session values in AppServiceProvider? I would like to share session value globally in all views.
You can't read session directly from a service provider: in Laravel the session is handled by StartSession middleware that executes after all the service providers boot phase
If you want to share a session variable with all view, you can use a view composer from your service provider:
public function boot()
{
view()->composer('*', function ($view)
{
$view->with('your_var', \Session::get('var') );
});
}
The callback passed as the second argument to the composer will be called when the view will be rendered, so the StartSession will be already executed at that point
Add new web middleware ShareDataForView
in \app\Http\Kernel.php:
protected $middlewareGroups = [
'web' => [
// ...
\Illuminate\Session\Middleware\StartSession::class,
// I will always ShareDataForView after StartSession
\App\Http\Middleware\ShareDataForView::class,
...
and write your code in method "handle" of app\Http\Middleware\ShareDataForView.php, for example:
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Closure;
use Log, Exception, View;
class ShareDataForView
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = Auth::user();
$bank = NULL;
if ( $user ){
$bank = $user->bank;
}
View::share('user', $user);
session()->put(['bank' => $bank]);
return $next($request);
}
}
The following works for me on Laravel 5.2, is it causing errors on your app?
AppServiceProvider.php
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
\Session::put('lang', 'en_US');
view()->share('lang', \Session::get('lang', 'de_DE'));
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
home.blade.php
<h1>{{$lang}}</h1>
Shows "en_US" in the browser.

Categories