Skip to content

Conversation

shankarThiyagaraajan
Copy link

Simple Middleware process were implemented,

ex.
Simple Implementation of Middleware in Route.

$router->post([
    'as' => 'Test',
    'uri' => '/test',
    'middleware' => __NAMESPACE__ . '\Middlewares\Auth',
    'uses' => __NAMESPACE__ . '\Controllers\Test\TestController@test'
]);

Adding additional index for "Middleware" [Route.php],

$this->middleware = $data['middleware'];

Re-Process the Request with Middleware [Router.php],

 protected function processRequest(Route $route)
    {
        // Middleware Implementations
        $route = (new Middleware())->init($route);

        $this->processResponse($route->handle());

    }

New Middleware Module in "Herbert/Framework/Middleware.php",

Creating Folder for Middleware in inside "Plugin/app/Middleware"

Finally Create Custom Middleware to Implement...!

Sample User Rights Handling Middleware :

<?php
namespace Plugin\Middlewares;

use Plugin\Helper;
use Exception;

/**
 * Class Middleware
 * @package Plugin\library
 */
class Auth
{
    /**
     * @var
     */
    protected $request;

    /**
     * @var string
     */
    protected $role = 'administrator';

    /**
     * Auth constructor.
     */
    public function __construct()
    {
        //
    }

    /**
     * Managing Requests
     */
    public function handle($request)
    {
        $user_rights = $this->getUserRights();
        try {
            if (in_array($this->rights, $user_rights)) {
                return $request;
            } else {
                wp_die(__('You do not have sufficient permissions to access this page.'), 403);
            }
        } catch (Exception $e) {
            wp_die(__($e->getMessage()), 403);;
        }
    }


    /**
     * @return mixed
     */
    public function getUserRights()
    {
        return wp_get_current_user()->roles;
    }

}

Route Define ex. 

$router->get([
    'as' => 'URI',
    'uri' => '/name',
    'middleware' => '[your_middlewares]',
    'uses' => __NAMESPACE__ . '\Controllers\Controller_name@function
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant