Modify parameters and arguments with Middleware

#1

Hello,

I need to transform everything that comes from GET, POST, PUT, DELETE and the arguments of the url in base64.

I have the following example script, I can not understand how it should be done.

   <?php
    namespace Api\Src\Middleware;

    use Psr\Http\Message\ServerRequestInterface as Request;
    use Psr\Http\Message\ResponseInterface as Response;

    class Base64Middleware
    {
        public function __construct()
        {
        }
        public function __invoke(Request $request, Response $response, $next)
        {
            // 1. TODO: All parameters sent by GET, POST, PUT or DELETE must be encoded in base64
            $arrParams = $objRequest->getParams();

            $arrEncodeParams = $this->encodeBase64($arrParams);

            // How should I send it?
            $request = $objRequest->withParams($arrEncodeParams);

            // 2. TODO: Every argument sent by the url must be encoded in base64
            // $app->get('/foo/{code}', ...)
            $arrAttributes = $request->getAttributes();

            $arrEncodeAttributes = $this->encodeBase64($arrAttributes);

            // How should I send it?
            $request = $request->withAttributes($arrEncodeAttributes);

            $response = $next($request, $response);
            return $response;
        }

        private function encodeBase64($arrParams)
        {
            foreach ($arrParams as $key => $itemParam) {
                if (empty($itemParam) || !is_string($itemParam)) {
                    continue;
                }
                $strEncodeParam = base64_encode($itemParam);
                $arrParams[$key] = $strEncodeParam;
            }

            return $arrParams;
        }
    }
0 Likes

#2

What you need is a method that changes the request , something like this:

protected function getRequestWithEncodedAttributes(Request $request)
{
      $attributes = $request->getAttributes();
       foreach($attributes as $name => $value) {
           $request = $request->withAttribute($name, base64_encode($value)); 
       }
       return $request;
}

You should do the same for the $request->getParams();

0 Likes

#3

The problem is that I don’t know how.

0 Likes

#4

For posted values you can use : $request = $request->withParsedBody($encodededParsedBody);
And for get values: $request = $request->withQueryParams($encodededQueryParams);

1 Like