phplaravel-5encryptiondomain-masking

How to create url signature on the place of parameters in laravel 5.4


It just my thought i just want to do like the same, I haven't try this because of i haven't any idea about this means how it will be done.

For Example:

I have - mysite.com/view?user_id=12 , I don't want to show url's parameters (?user_id=12) on url, On the place of this, I want to show like

mysite.com/view?_signature=encryptedparameter 

(like : mysite.com/view?_signature=853ef7a0ff5aea6f24152b1d1ed4d771)

853ef7a0ff5aea6f24152b1d1ed4d771 will denotes user_id=12.

If i have multiple parameters it would be like the same and i will have a single encrypted string and i will get all parameters with that string.


Solution

  • Yes, but I am using in Laravel 5.1

    Assume if I have "mysite.com/view?user_id=12"

    And I want "mysite.com/view?_signature=encryptedparameter"

    Please follow some steps

    laravel>packages>myfolder>core
    
    
    +=>folder
    -=>file     
    
    +packages
        +Folder
            +core
                +src
                    +Faundation
                        -Application.php
                    +Routing
                        -RoutingServiceProvider.php
                        -UriGenerator.php   
                    +Support
                        +Middleware
                            -UrlParamRevealerMiddleware.php
                        +ServiceProvider
                            -CoreServiceProvider.php
                        -UriParamProtector.php
    
                        
    
    <<IN APPLICATION.PHP>>
    
    <?php
    
    namespace Folder\Core\Foundation;
    
    use Illuminate\Events\EventServiceProvider;
    use Folder\Core\Routing\RoutingServiceProvider;
    use Illuminate\Foundation\Application as BaseApplication;
    use Folder\Core\Support\ServiceProvider\CoreServiceProvider;
    
    class Application extends BaseApplication
    {
        /**
         * Register all of the base service providers.
         *
         * @return void
         */
        protected function registerBaseServiceProviders()
        {
            $this->register(new EventServiceProvider($this));
    
            $this->register(new CoreServiceProvider($this));
    
            $this->register(new RoutingServiceProvider($this));
        }
    }
    <<//IN APPLICATION.PHP>>
    
    
    <<-RoutingServiceProvider>>
    
    <?php
    
    namespace Folder\Core\Routing;
    
    use Folder\Core\Routing\UrlGenerator;
    use Illuminate\Routing\RoutingServiceProvider as BaseServiceProvider;
    
    class RoutingServiceProvider extends BaseServiceProvider
    {
    
        /**
         * Register the URL generator service.
         *
         * @return void
         */
        protected function registerUrlGenerator()
        {
            $this->app['url'] = $this->app->share(function ($app) {
                $routes = $app['router']->getRoutes();
    
                // The URL generator needs the route collection that exists on the router.
                // Keep in mind this is an object, so we're passing by references here
                // and all the registered routes will be available to the generator.
                $app->instance('routes', $routes);
    
                $url = $this->getUrlGenerator($routes);
    
                $url->setSessionResolver(function () {
                    return $this->app['session'];
                });
    
                // If the route collection is "rebound", for example, when the routes stay
                // cached for the application, we will need to rebind the routes on the
                // URL generator instance so it has the latest version of the routes.
                $app->rebinding('routes', function ($app, $routes) {
                    $app['url']->setRoutes($routes);
                });
    
                return $url;
            });
        }
    
        /**
         * Get the url generator instance.
         *
         * @param \Illuminate\Routing\RouteCollection $routes
         * @return \Folder\Core\Routing\UrlGenerator
         */
        protected function getUrlGenerator($routes)
        {
            $url = new UrlGenerator(
                $routes,
                $this->app->rebinding(
                    'request',
                    $this->requestRebinder()
                )
            );
    
            return $url;
        }
    }
    <</-RoutingServiceProvider>>
    
    <<UriGenerator.php>>
    <?php
    
    namespace Folder\Core\Routing;
    
    use ErrorException;
    use Illuminate\Support\Facades\App;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Routing\UrlGenerator as BaseUrlGenerator;
    
    class UrlGenerator extends BaseUrlGenerator
    {
    
        /**
         * Get the URL to a named route.
         *
         * @param  string  $name
         * @param  mixed   $parameters
         * @param  bool  $absolute
         * @return string
         *
         * @throws \InvalidArgumentException
         */
        public function route($name, $parameters = [], $absolute = true)
        {
            $encryptedParameters = $parameters;
    
            if (Auth::guest() === false) {
                $encryptedParameters = $this->encrypt($name, $parameters);
            }
    
            return parent::route($name, $encryptedParameters, $absolute);
        }
    
        /**
         * Get the cryptic engine.
         *
         * @return \Folder\Core\Support\UrlParamEncrypter
         *
         * @throws \ErrorException
         */
        protected function getCrypt()
        {
            $app = App::getInstance();
    
            if (isset($app['urlencryptor'])) {
                return $app['urlencryptor'];
            }
    
            throw new ErrorException('URL Encryptor was not found.');
        }
    
        /**
         * Get the protector engine.
         *
         * @return @return \Folder\Core\Support\UrlParamProtector
         *
         * @throws \ErrorException
         */
        protected function getProtector()
        {
            $app = App::getInstance();
    
            if (isset($app['urlprotector'])) {
                return $app['urlprotector'];
            }
    
            throw new ErrorException('URL Protector was not found.');
        }
    
        /**
         * Encrypts the parameter passed as querystring in URL.
         *
         * @param array $parameters
         * @return array
         */
        protected function encrypt($routeName, $parameters = [])
        {
    
            if (! is_array($parameters)) {
                return $parameters;
            }
            
            if (count($parameters) === 0) {
                return [];
            }
    
            if (Auth::guest() === true) {
                return $parameters;
            }
    
            $protected = $this->getProtector()->protect($routeName, $parameters);
    
            return ['__signature' => $protected];
        }
    }
    
    <<//UriGenerator.php>>
    
    <<UrlParamRevealerMiddleware.php>>
    <?php
    
    namespace Folder\Core\Support\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\App;
    use Illuminate\Support\Facades\Auth;
    use Folder\Core\Support\UrlParamProtector;
    
    class UrlParamRevealerMiddleware
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            (! Auth::guest()) && App::make(UrlParamProtector::class)->reveal($request);
            
            return $next($request);
        }
    }
    
    <<//UrlParamRevealerMiddleware.php>>
    
    <<CoreServiceProvider.php>>
    <?php
    
    namespace Folder\Core\Support\ServiceProvider;
    
    use Illuminate\Support\ServiceProvider;
    use Folder\Core\Support\UrlParamProtector;
    
    class CoreServiceProvider extends ServiceProvider
    {
    
        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot()
        {
            $this->app->make('Illuminate\Contracts\Http\Kernel')
                ->pushMiddleware('Folder\Core\Support\Middleware\UrlParamRevealerMiddleware');
        }
    
        /**
         * Register the service provider.
         *
         * @return void
         */
        public function register()
        {
            $this->registerUrlProtector();
        }
    
        /**
         * Register UrlProtector class.
         */
        protected function registerUrlProtector()
        {
            $this->app->singleton('urlprotector', function () {
                return new UrlParamProtector();
            });
        }
    }
    
    <<//CoreServiceProvider.php>>
    
    <<-UriParamProtector.php>>
    <?php
    
    namespace Folder\Core\Support;
    
    use Illuminate\Support\Str;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\App;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Session;
    
    class UrlParamProtector
    {
    
        /**
         * Session key.
         *
         * @var string
         */
        protected $sessionKey = '__url_protector__';
    
        /**
         * Request class.
         *
         * @var \Illuminate\Http\Request
         */
        protected $request;
    
        /**
         * Values those needs to be merged in request object.
         *
         * @var array
         */
        protected $valuesToBeMerged;
    
        /**
         * Create and returns VALID RFC 4211 COMPLIANT
         * Universally Unique IDentifiers (UUID) version 4.
         *
         * @return string
         */
        protected function getNewGuid()
        {
            if (function_exists('com_create_guid') === true) {
                return trim(com_create_guid(), '{}');
            }
    
            return sprintf(
                '%04X%04X-%04X-%04X-%04X-%04X%04X%04X',
                mt_rand(0, 65535),
                mt_rand(0, 65535),
                mt_rand(0, 65535),
                mt_rand(16384, 20479),
                mt_rand(32768, 49151),
                mt_rand(0, 65535),
                mt_rand(0, 65535),
                mt_rand(0, 65535)
            );
        }
    
        /**
         * Create the route key.
         *
         * @param string $routeName
         * @param array $parameters
         * @return string
         */
        protected function getRouteKey($routeName, array $parameters = [])
        {
            if (count($parameters) <= 0) {
                $paramToString = '';
            } else {
                $paramToString = implode('-', array_map(
                    function ($k, $v) {
                            return $k . '-' . $v;
                    },
                    array_keys($parameters),
                    array_values($parameters)
                ));
            }
    
            $routeKey = 'route__' . $routeName . (empty($paramToString) ? '' : '-' . $paramToString);
    
            return $routeKey;
        }
    
        /**
         * Returns a GUID for a URL parameter.
         *
         * @param string $routeName
         * @param array $parameters
         * @return string
         */
        public function protect($routeName, array $parameters)
        {
            $routeKey = $this->getRouteKey($routeName, $parameters);
    
            if (Session::has($this->sessionKey . '.' . $routeKey) === false) {
                $guid = Str::lower($this->getNewGuid());
    
                Session::set($this->sessionKey . '.' . $routeKey, [
                    'guid' => $guid,
                    'loggedin_user_id' => (Auth::guest() ? 0 : Auth::user()->id),
                    'params' => $parameters,
                ]);
            } else {
                $guid = Session::get($this->sessionKey . '.' . $routeKey . '.guid');
            }
    
            return $guid;
        }
    
        /**
         * Check whether guid passed is a valid one or not.
         *
         * @param string $guid
         * @return boolean
         */
        protected function isValidGuid($guid)
        {
            foreach (Session::get($this->sessionKey) as $key => $value) {
                if (!isset($value['guid'])) {
                    list($innerKey, $val) = each($value);
                } else {
                    $val = $value;
                }
                if ($val['guid'] === $guid) {
                    $this->valuesToBeMerged = $val['params'];
                    return true;
                }
            }
    
            return false;
        }
    
        /**
         * Check whether guid passed is a valid one or not.
         *
         * @param string $guid
         * @return boolean
         */
        public function isValidGuidForPost($guid)
        {
            foreach (Session::get($this->sessionKey) as $key => $value) {
                if ($value['guid'] === $guid && Auth::user()->id === $value['loggedin_user_id']) {
                    $this->valuesToBeMerged = $value['params'];
                    return true;
                }
            }
    
            return false;
        }
    
        /**
         * Merge the request with our revealed values.
         */
        protected function mergeRequest()
        {
            $this->request->merge($this->valuesToBeMerged);
        }
    
        /**
         * Check whether a "__signature" is correct or not.
         *
         * @param \Illuminate\Http\Request $request
         * @return boolean
         */
        public function reveal(Request &$request)
        {
            $this->request = $request;
    
            $guid = ($this->request->query('__signature') ? : false);
    
            if ($guid === false) {
                return false;
            }
    
            if ($this->isValidGuid($guid) === false) {
                App::abort(400);
            }
    
            $this->mergeRequest();
        }
    }
    
    
    <<//-UriParamProtector.php>>
    

    ============================================== after that, in "bootstrap>App.php" use this:

    $app = new Folder\Core\Foundation\Application(
        realpath(__DIR__.'/../')
    );
    

    instead of:

    $app = new Illuminate\Foundation\Application(
       realpath(__DIR__.'/../')
    );
    

    In any link use "data-href":

    <a data-href="route('modify_lead_status',['user_id' => $users->id])" href="javascript:void(0)"><i class=\"fa fa-random\"></i></a>"
                    
    

    and after that any controller,Routing,middleware will be same...

    composer auto-dump
    

    <<Please check spelling, be sure use same>>