Jump to content
thomasaull

Module: RestApi

Recommended Posts

When using RestAPI, I found the following error in the debug page. (RestApi 0.0.7 ProcessWire 3.0.148)

restapierr.png

Share this post


Link to post
Share on other sites

This module is very useful unconditionally.
Could you add an example of uploading a file to the server in the README.md.

I just can’t understand how this is implemented in your module.

 

Share this post


Link to post
Share on other sites

@Andy Uh, the first time I'm seeing this page. Where can I access it in the ProcessWire Backend? Is the module otherwise working for you? Regarding your question about file uploads: The module itself does not has an implementation for this case, basically it provides just a wrapper for your own functions. So in theory you should be able to create a route for a file upload and have your own function to accept the file and store it on the server. If you google "Processwire file upload" you should find some examples to get you started. I'm writing "in theory" because I haven't done it myself yet. If this approach fails, we can figure out what needs be changed in the module itself.

Share this post


Link to post
Share on other sites
17 minutes ago, thomasaull said:

Uh, the first time I'm seeing this page. Where can I access it in the ProcessWire Backend?

1375638912_Capturedecran2020-03-04a09_59_15.png.0023e39bed10241446b2c74add0391a0.png

  • Like 1

Share this post


Link to post
Share on other sites

@thomasaull

3 hours ago, thomasaull said:

Where can I access it in the ProcessWire Backend?

When you set up the site configuration. In file /site/config.php change the row to true and you will see backend debugging capabilities.

/*** SITE CONFIG *************************************************************************/

/**
 * Enable debug mode?
 *
 * Debug mode causes additional info to appear for use during dev and debugging.
 * This is almost always recommended for sites in development. However, you should
 * always have this disabled for live/production sites.
 *
 * @var bool
 *
 */
$config->debug = true;

 

Thanks for the answer on downloading the file in the Processwire. I don’t understand very well how API communication works. But your module perfectly illustrates this feature. I managed to transfer any information from the site through the API. But I can’t transfer a file through your module to site.
When we submit a file from the form, we have identifiers

<input type="file" name="uploadedFile[]" id="uploadedFile" multiple>

And we can find it in global wire('input') or  $_GET, $_POST. But in our case this is empty wire('input')->post->upload

Share this post


Link to post
Share on other sites

@thomasaull It seems I found what was the mistake. It was necessary to transfer the dispatch from Insomnia to the multipart format and set the file name. After that, in the $_FILES variable you can find all the data to get the file.

$_FILES Array(
[upfile]=>Array(
	[name]=>hot-pizza.jpeg
	[type]=>image/jpeg
	[tmp_name]=>/localhost/tmp/phptAUnX5
	[error]=>0
	[size]=>65639
	)
)

 

  • Like 2

Share this post


Link to post
Share on other sites

@thomasaull I continue to test this module which is very suitable for me.

JWT token. Problem with authorization.

Apache2 server and PHP 7.3.10. Can't auth and gives a message: No Authorization Header found' and code 400.

This is a problem in Router.php function private static function getAuthorizationHeader()

    $headers = array();
    foreach($_SERVER as $key => $value) {
      $headers[strtolower($key)] = $value;
    }

Where variable $_SERVER have no authorization variable. If you change this to a function, it will work.

    foreach(getallheaders() as $key => $value) {
		$headers[strtolower($key)] = $value;
    }

The following error occurs if you enter an invalid token.

{
  "error": "Error: Exception: Signature verification failed (in \/localhost\/site\/modules\/RestApi\/Router.php line 131)\n\n#0 \/localhost\/site\/modules\/RestApi\/Router.php(91): ProcessWire\\Router::handle('ProcessWire\\\\Exa...', 'getUser', Object(stdClass), Array)\n#1 \/localhost\/site\/modules\/RestApi\/RestApi.module(50): ProcessWire\\Router::go()\n#2 \/localhost\/wire\/core\/WireHooks.php(924): ProcessWire\\RestApi->checkIfApiRequest(Object(ProcessWire\\HookEvent))\n#3 \/localhost\/wire\/core\/Wire.php(450): ProcessWire\\WireHooks->runHooks(Object(ProcessWire\\ProcessPageView), 'execute', Array)\n#4 \/localhost\/index.php(61): ProcessWire\\Wire->__call('execute', Array)\n#5 {main}. File: \/localhost\/index.php:70"
}

It seems to me that it would be right to replace Router.php line 131 with code 500

      catch (\Throwable $e)
      {
        throw new \Exception($e->getMessage());
      }

Can be replaced by

      catch (\Throwable $e)
      {
        self::displayError('Signature verification failed', 400);
      }       

This will be more correct, as the token error is a request syntax error and this is code 400.

Share this post


Link to post
Share on other sites

@thomasaull I will try, although I do not have such experience with github. And I'm not sure that all my suggestions are useful. Maybe I'm wrong somewhere.

Share this post


Link to post
Share on other sites

@Andy I think for the getallheaders() function it'd make sense to keep the old way aswell and just search in both for the Authorization Header (If I remember correctly, the getallheaders() function wasn't available in all environments. In case you create a PR we can discuss the details there 🙂 Basically you need to fork the repository, push your changes and then create a PR on the github website

Share this post


Link to post
Share on other sites

@thomasaull Array merging may help

	$headers = array();
    $header_variables = array_merge($_SERVER, getallheaders());
    foreach($header_variables as $key => $value) {
      $headers[strtolower($key)] = $value;
    }

Since you require in your module PHP>=7.2.0, ProcessWire>=3.0.98
The getallheaders() function is definitely present.

  • Like 1

Share this post


Link to post
Share on other sites

Another problem with RestAPI. When loading large files, an error occurs.
In the backend everything is fine, a 300 MB file is loaded normally.
The problem only occurs when testing through Insomnia or Postman with files larger than 15 mb.
We managed to solve the problem. It is necessary to include AJAX in the file properties.

        $ul = wire(new WireUpload($formName));
        $ul->setValidExtensions(['mp4', 'avi', '3gp']);
        $ul->setMaxFiles(1);
        $ul->setMaxFileSize(100 * 1000000); // 100 MB
        $ul->setOverwrite(true);
        $ul->setDestinationPath($p_path);
        $ul->setLowercase(true);
        $ul->setAllowAjax(true);
        $files = $ul->execute();

 

  • Like 2

Share this post


Link to post
Share on other sites

Hi @thomasaull

Do you know what the best way is to restrict the API Requests for specific IP Adresses?

KR
Orkun

Share this post


Link to post
Share on other sites

Hi @Orkun, at the moment there is not built-in way for such a use case. However I guess it's really easy to do with a ProcessWire Hook which can be independet of the API, you'd just need to run the hook on the endpoint-url and check the IP with PHP there. If you want to restrict access to specific routes of the API only, I'd probably run the same checks in the endpoint function.

  • Like 2

Share this post


Link to post
Share on other sites
On 3/20/2020 at 10:21 AM, thomasaull said:

Hi @Orkun, at the moment there is not built-in way for such a use case. However I guess it's really easy to do with a ProcessWire Hook which can be independet of the API, you'd just need to run the hook on the endpoint-url and check the IP with PHP there. If you want to restrict access to specific routes of the API only, I'd probably run the same checks in the endpoint function.

I tried this by creating a init.php file insdie /site/ with this content in it, but the go method of the router class from your RestApi.module is still executed.

<?php 

require_once wire('config')->paths->RestApi . "/Router.php";

$this->addHookBefore('ProcessPageView::execute', function(HookEvent $event) {
    
    $url = wire('sanitizer')->url(wire('input')->url);
    
    // support / in endpoint url:
    $endpoint = str_replace("/", "\/", wire('modules')->RestApi->endpoint);

    $regex = '/^\/'.$endpoint.'\/?.*/m';
    preg_match($regex, $url, $matches);

    $hasAccess = array(
        '178.192.77.1'
    );

    if($matches) {
        $event->replace = true;
        if(in_array($_SERVER['REMOTE_ADDR'], $hasAccess)){
            wire('log')->save("sso-debug", "Access granted for ".$_SERVER['REMOTE_ADDR']);
            Router::go();
        } else {
            wire('log')->save("sso-debug", "Access denied for ".$_SERVER['REMOTE_ADDR']);
            throw new \Exception("Access denied!", 400);
        }  
    }
});

What can I do?

KR
Orkun

Share this post


Link to post
Share on other sites
1 hour ago, Orkun said:

I tried this by creating a init.php file insdie /site/ with this content in it, but the go method of the router class from your RestApi.module is still executed.


<?php 

require_once wire('config')->paths->RestApi . "/Router.php";

$this->addHookBefore('ProcessPageView::execute', function(HookEvent $event) {
    
    $url = wire('sanitizer')->url(wire('input')->url);
    
    // support / in endpoint url:
    $endpoint = str_replace("/", "\/", wire('modules')->RestApi->endpoint);

    $regex = '/^\/'.$endpoint.'\/?.*/m';
    preg_match($regex, $url, $matches);

    $hasAccess = array(
        '178.192.77.1'
    );

    if($matches) {
        $event->replace = true;
        if(in_array($_SERVER['REMOTE_ADDR'], $hasAccess)){
            wire('log')->save("sso-debug", "Access granted for ".$_SERVER['REMOTE_ADDR']);
            Router::go();
        } else {
            wire('log')->save("sso-debug", "Access denied for ".$_SERVER['REMOTE_ADDR']);
            throw new \Exception("Access denied!", 400);
        }  
    }
});

What can I do?

KR
Orkun

Ok this works for me now:

require_once wire('config')->paths->RestApi . "Router.php";

$this->addHookBefore('ProcessPageView::execute', function(HookEvent $event) {

    $url = wire('sanitizer')->url(wire('input')->url);
    
    // support / in endpoint url:
    $endpoint = str_replace("/", "\/", wire('modules')->RestApi->endpoint);

    $regex = '/^\/'.$endpoint.'\/?.*/m';
    preg_match($regex, $url, $matches);

    $hasAccess = array(
      '178.192.77.1'
    );

    if($matches) {
        if(!in_array($_SERVER['REMOTE_ADDR'], $hasAccess)){
            wire('log')->save("sso-debug", "Access denied for ".$_SERVER['REMOTE_ADDR']);
            http_response_code(403);
            exit;
        }
        $event->replace = true;
    }

}, [ 'priority' => 99 ]);

I have added the priority option and set it to 99 so that it gets executed before your hook in RestApi Module.

KR
Orkun

  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By MoritzLost
      This module allows you to integrate hCaptcha bot / spam protection into ProcessWire forms. hCaptcha is a great alternative to Google ReCaptcha, especially if you are in the EU and need to comply with privacy regulations.

      The development of this module is sponsored by schwarzdesign.
      The module is built as an Inputfield, allowing you to integrate it into any ProcessWire form you want. It's primarily intended for frontend forms and can be added to Form Builder forms for automatic spam protection. There's a step-by-step guide for adding the hCaptcha widget to Form Builder forms in the README, as well as instructions for API usage.
      Features
      Inputfield that displays an hCaptcha widget in ProcessWire forms. The inputfield verifies the hCaptcha response upon submission, and adds a field error if it is invalid. All hCaptcha configuration options for the widget (theme, display size etc) can be changed through the inputfield configuration, as well as programmatically. hCaptcha script options can be changed through a hook. Error messages can be translated through ProcessWire's site translations. hCaptcha secret keys and site-keys can be set for each individual inputfield or globally in your config.php. Error codes and failures are logged to help you find configuration errors. Please check the README for setup instructions.
      Links
      Github Repository and documentation InputfieldHCaptcha in the module directory (pending approval) Screenshots (configuration)

      Screenshots (hCaptcha widget)

       
       

       
    • By joshua
      This module is (yet another) way for implementing a cookie management solution.
      Of course there are several other possibilities:
      - https://processwire.com/talk/topic/22920-klaro-cookie-consent-manager/
      - https://github.com/webmanufaktur/CookieManagementBanner
      - https://github.com/johannesdachsel/cookiemonster
      - https://www.oiljs.org/
      - ... and so on ...
      In this module you can configure which kind of cookie categories you want to manage:

      You can also enable the support for respecting the Do-Not-Track (DNT) header to don't annoy users, who already decided for all their browsing experience.
      Currently there are four possible cookie groups:
      - Necessary (always enabled)
      - Statistics
      - Marketing
      - External Media
      All groups can be renamed, so feel free to use other cookie group names. I just haven't found a way to implement a "repeater like" field as configurable module field ...
      When you want to load specific scripts ( like Google Analytics, Google Maps, ...) only after the user's content to this specific category of cookies, just use the following script syntax:
      <script type="text/plain" data-type="text/javascript" data-category="statistics" data-src="/path/to/your/statistic/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="marketing" data-src="/path/to/your/mareketing/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="external_media" data-src="/path/to/your/external-media/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="marketing">console.log("Inline scripts are also working!");</script> The type has to be "optin" to get recognized by PrivacyWire, the data-attributes are giving hints, how the script shall be loaded, if the data-category is within the cookie consents of the user. These scripts are loaded asynchronously after the user made the decision.
      If you want to give the users the possibility to change their consent, you can use the following Textformatter:
      [[privacywire-choose-cookies]] It's planned to add also other Textformatters to opt-out of specific cookie groups or delete the whole consent cookie.
      You can also add a custom link to output the banner again with a link / button with following class:
      <a href="#" class="privacywire-show-options">Show Cookie Options</a> <button class="privacywire-show-options">Show Cookie Options</button> This module is still in development, but we already use it on several production websites.
      You find it here: PrivacyWire Git Repo
      Download as .zip
      I would love to hear your feedback 🙂
      CHANGELOG
      0.1.1 Debugging: fixed error during uninstall 0.1.0 Added new detection of async scripts for W3C Validation 0.0.6 CSS-Debugging for hiding unused buttons, added ProCache support for the JavaScript tag 0.0.5 Multi-language support included completely (also in TextFormatter). Added possibility to async load other assets (e.g. <img type="optin" data-category="marketing" data-src="https://via.placeholder.com/300x300">) 0.0.4 Added possibility to add an imprint link to the banner 0.0.3 Multi-language support for module config (still in development) 0.0.2 First release 0.0.1 Early development
    • By bernhard
      --- Please use RockFinder3 ---
    • By MoritzLost
      Cacheable Placeholders
      This module allows you to have pieces of dynamic content inside cached output. This aims to solve the common problem of having a mostly cacheable site, but with pieces of dynamic output here and there.  Consider this simple example, where you want to output a custom greeting to the current user:
      <h1>Good morning, <?= ucfirst($user->name) ?></h1> This snippet means you can't use the template cache (at least for logged-in users), because each user has a different name. Even if 99% of your output is static, you can only cache the pieces that you know won't include this personal greeting. A more common example would be CSRF tokens for HTML forms - those need to be unique by definition, so you can't cache the form wholesale.
      This module solves this problem by introducing cacheable placeholders - small placeholder tokens that get replaced during every request. The replacement is done inside a Page::render hook so it runs during every request, even if the response is served from the template cache. So you can use something like this:
      <h1>Good morning, {{{greeting}}}</h1> Replacement tokens are defined with a callback function that produces the appropriate output and added to the module through a simple hook:
      // site/ready.php wire()->addHookAfter('CachePlaceholders::getTokens', function (HookEvent $e) { $tokens = $e->return; $tokens['greeting'] = [ 'callback' => function (array $tokenData) { return ucfirst(wire('user')->name); } ]; $e->return = $tokens; }); Tokens can also include parameters that are parsed and passed to the callback function. There are more fully annotated examples and step-by-step instructions in the README on Github!
      Features
      A simple and fast token parser that calls the appropriate callback and runs automatically. Tokens may include multiple named or positional parameters, as well as multi-value parameters. A manual mode that allows you to replace tokens in custom pieces of cached content (useful if you're using the $cache API). Some built-in tokens for common use-cases: CSRF-Tokens, replacing values from superglobals and producing random hexadecimal strings. The token format is completely customizable, all delimiters can be changed to avoid collisions with existing tag parsers or template languages. Links
      Github Repository & documentation Module directory (pending approval) If you are interested in learning more, the README is very extensive, with more usage examples, code samples and usage instructions!
    • By Craig
      I've been using Fathom Analytics for a while now and on a growing number of sites, so thought it was about time there was a PW module for it.
      WayFathomAnalytics
      WayFathomAnalytics is a group of modules which will allow you to view your Fathom Analytics dashboard in the PW admin panel and (optionally) automatically add and configure the tracking code on front-end pages.
      Links
      GitHub Readme & documentation Download Zip Modules directory Module settings screenshot What is Fathom Analytics?
      Fathom Analytics is a simple, privacy-focused website analytics tool for bloggers and businesses.

      Stop scrolling through pages of reports and collecting gobs of personal data about your visitors, both of which you probably don't need. Fathom is a simple and private website analytics platform that lets you focus on what's important: your business.
      Privacy focused Fast-loading dashboards, all data is on a single screen Easy to get what you need, no training required Unlimited email reports Private or public dashboard sharing Cookie notices not required (it doesn't use cookies or collect personal data) Displays: top content, top referrers, top goals and more
×
×
  • Create New...