Jump to content
thomasaull

Module: RestApi

Recommended Posts

@pmichaelis If the error is thrown in line 131 it's likeley there is an error with the JWT Authorization. Maybe the Token you're submitting is not valid, maybe something else. Hard to tell with the little information you provided.

Oh, just noticed you already mentioned the JWT Auth… 🙂 Probably the error is produced in those 4 lines:

$secret = wire('modules')->RestApi->jwtSecret;
$token = str_replace('Bearer', '', $authHeader);
$token = trim($token);
$decoded = JWT::decode($token, wire('modules')->RestApi->jwtSecret, array('HS256'));

if the secret is in your config and you didn't change it, I'd check if the token gets transmitted properly with the request.

Share this post


Link to post
Share on other sites
5 hours ago, thomasaull said:

@pmichaelis If the error is thrown in line 131 it's likeley there is an error with the JWT Authorization. Maybe the Token you're submitting is not valid, maybe something else. Hard to tell with the little information you provided.

@thomasaull It seems that the authorisation headers are not present.

Added the following line to the htaccess:

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

auth headers are stored in following variable

$_SERVER['REDIRECT_HTTP_AUTHORIZATION'];

Please don't ask why.

Share this post


Link to post
Share on other sites

@pmichaelis I'm gonna ask anyway: Why? 😉

Seems like a weird server config, but I could add this to the variables the module checks by default.

  • Like 1
  • Haha 1

Share this post


Link to post
Share on other sites
On 2/28/2019 at 3:17 PM, eelkenet said:

Here is the final cleaned-up and more secure 'api' template that I am using in between the RestApi router and ProCache, perhaps it can be of some help:

 

I ran into issues with a slow server using this method, where wireHttp would already resolve a result while RestApi was still running.
So with help from my co-worker @harmvandeven we came up with a more stable version, with some more redundancy: 
 

<?php

/*

    api.php, a simple PW template to fill the gap between the RestApi and ProCache modules
    v2

    @author: @eelkenet, with help from @harmvandeven & @ryan

    1. Create a template called 'api' and set it up using the following settings:
    - Allow URL segments
    - Allow guests to view the page
    - Set the Content-Type to application/json
    - Make sure to NOT Prepend or Append any files

    2. Add a page using this template and allow ProCache to run its magic

*/

$timeout = 600;
$maxAttempts = 10;

// Pre-check for unwanted symbols
if (strpos($input->urlSegmentStr(), '.') !== false) {
    throw new Wire404Exception();
}

// Build request URL
$endpoint = $modules->get("RestApi")->endpoint;
$url = $input->scheme() . "://" . $config->httpHost . "/" . $endpoint ."/" . $input->urlSegmentStr();

$http = new WireHttp();

// Set a high timeout, to deal with a slow server
$http->setTimeout($timeout);

// Get the HTTP status of the page, to make sure it exists in the first place
$status = $http->status($url);

// If the page exists, or possibly redirects to valid content
if ($status >= 200 && $status < 400) {

    $result = false;
    $attempt = 0;

    // If the result isn't a string, something went wrong
    while(gettype($result) !== "string" && $attempt++ < $maxAttempts) {

        $result = $http->get($url);
        if ($attempt > 1) wire()->log->message("Loading content at $url, attempt $attempt: " . gettype($result));
    }

    // Double check if the data is a string..
    if (gettype($result) === "string"){

        // .. And check if it can be decoded, if so: return the data and thus cache it
        if (json_decode($result) !== NULL) return $result;

        // If it cannot be decoded: throw exception (don't cache it)
        throw new WireException("Found the data at $url, but it could not be decoded. Please check your API output!");
    }

    // Throw exception if data could not be loaded in time (don't cache it)
    throw new WireException("Found the data at $url, but could not load it in time, after $attempt attempts. Result has type: " . gettype($result));

}

// Throw generic exception if the requested page was not found or there was another error
throw new WireException("Failed to load the content at: $url, with HTTP status: " . $status);

 

 

 

  • Like 4

Share this post


Link to post
Share on other sites

Hi

I've just installed this module (processwire version 3.0.123) but I can't get anything off a connection. I tried a clean install without any modules activated and have the some problem. Is there anything that has to be installed to be able to get a response? I'm developing on a local environment of xampp and tried it on a mac os environment with mamp aswell.

I tested it on a production environment (online hosting) and there it is working. I'm guessing it has something to do with the local servers. Anybody has an idea what should be activated?

Thanks in advance

Share this post


Link to post
Share on other sites

@thibaultvdb It's a bit difficult to help from here. One thing you could try is to go through the code in Router.php and return or exit early to find out until where the code runs. The main functions are "go()" and "handle()". Another idea is to compare php settings between your hosted and local environment with "phpinfo()". If you can isolate the issue it's much easier to help.

  • Like 1

Share this post


Link to post
Share on other sites
13 hours ago, thomasaull said:

@thibaultvdb It's a bit difficult to help from here. One thing you could try is to go through the code in Router.php and return or exit early to find out until where the code runs. The main functions are "go()" and "handle()". Another idea is to compare php settings between your hosted and local environment with "phpinfo()". If you can isolate the issue it's much easier to help.

The main functions are all going like they should. I tried comparing the php info like you said but those files are huge so hard to compare them and find out what is missing/wrong. Is there a localhost software you recommend that is working? Friends that have mamp pro don't have the issue but using mamp/xampp does give me the 404. It's strange that I don't get errors, only a 404 page.

If I can provide you anything please let me know since serverside issue's aren't my best area of working.

Share this post


Link to post
Share on other sites

@thibaultvdb 

I think that by default on XAMPP your ProcessWire installation is in a subdir, and I bet that the module is giving you as api endpoint something like : /subdir/api instead of the /api endpoint. 

You should ask your friends to help you to setup your localhost environment to use a domain like  http://mylocalwebsite.local

To get started, you can follow the second answer here https://stackoverflow.com/questions/16229126/using-domain-name-instead-of-localhost-in-with-https-in-xampp

or follow this tutorial to use AcrylicDNS (the best solution IMO, do not be afraid, it's really easy to setup) https://www.ottorask.com/blog/automated-apache-virtual-hosts-on-windows/

 

Good luck.

  • Like 3

Share this post


Link to post
Share on other sites

@thibaultvdb If what @flydev says is the case and you're trying to access your website inside a subdirectory you could also try to adjust the path for the api in the module settings. Maybe it'll work 🙂

Share this post


Link to post
Share on other sites

@flydev I must say you are the savior of the day. The reason was indeed that xampp is putting "localhost" in front of the site url.
In my case this was "localhost/sitename" the RestApi module probably didn't understand this sitename url what gave me 404-pages all the time.

@thomasaull You mentioned that maybe this could be fixed through the settings of the module. Could you give an example of a path?
Maybe it's usefull to add a option to the module or something that notifies the user if it is using localhost or to automatically prefix this with localhost? I don't think I will be the only one that uses the localhost prefix 😛 

Thanks for the help already! Hopefully there is a possibility to handle this in the settings so I don't have to use these virtual hosts. Or maybe look at the processwire config? The processwire handles this localhost prefix perfectly.

Share this post


Link to post
Share on other sites

@thibaultvdb In the module settings there is an input for "API Endpoint" — can you try to change the value there to "localhost/api" and report back if this works for you?

  • Like 1

Share this post


Link to post
Share on other sites

@thomasaull changing the api endpoint didn't solve it (I tried a few things already). I solved it by using the virtual host for this project but for the future and others a localhost sollution would be lovely!
If I can provide anything more, please tell me!

Share this post


Link to post
Share on other sites

@thibaultvdb I need to check this, since I think (when I remember it properly) I put this option in specifically for this use-case. If you want to fiddle around try making it work or you know/want to figure out how ProcessWire does this automatically feel free 🙂 Otherwise I can't really make any promise when I'm going to be able to look into this

Share this post


Link to post
Share on other sites

Hello,
I have a clean blank install of latest dev version of Processwire. When I install your module, the backend stops working.

Share this post


Link to post
Share on other sites

@Hurme

Did you check your server error logs for hints? Or site/assets/logs/ ?

First of all, you could try to delete everything in site/assets/cache/modules/. 

If that doesn't work, rename the REST API module: prepend a dot (.modulename).

Share this post


Link to post
Share on other sites

@dragan Hi, I've left the office and wont be back until next week, but I'll see if deleting the cache has any effect. There were no errors in the log files, just your usual "Saved module X". Of course deleting the module itself resolves the crashing issue, but then you can't really use the module.

Share this post


Link to post
Share on other sites

Recently a user of this module had the problem that some multi-language fields weren't working correctly.kno After some investigation I discovered, that the hook this module uses (it's a "before ProcessPageView::execute") kicks in to early for the multi-language plugins to be ready. Does anyone knows of a hook, which can do something similar (basically take over the default routing of ProcessWire) while still have the other modules loaded?

One alternative approach for this specific problem would be to not trigger the module via a hook but with an own template and page like the old RestApiProfile did. A couple of benefits would come for free aswell (these are my assumptions, not tested yet):

  • ProCache should work without any workarounds
  • Multi-Language works
  • Websites in subdirectories (if working in ProcessWire in general) should work
  • site profile export would work if the /api folder lives in /templates by default

Any potential downsides I'm not seeing yet? Thoughts?

Share this post


Link to post
Share on other sites

I wrote an api-module a few years ago, where the module generated a custom template (e.g. "api-page"), which could be used to create one or more endpoint-pages. To handle calls to these pages I used ProcessPageView::pageNotFound like @bernhard did:

$this->addHookBefore('ProcessPageView::pageNotFound', $this, 'handleApiRequest');
public function handleApiRequest(HookEvent $e) {
	$page = $e->arguments[0];

	if ($page->template === 'api-page') {
		// handle request here...
		$otherEvent = $e->arguments(0); // grab event provided to PageRender::renderPage
		$e->replace = true; // prevent PageRender::renderPage from being called
	}
}

It worked nice for me, but I cannot say if caching or multi-language works better in this hook. pageNotFound should be called later than execute, so there is a chance that it helps 🤷‍♂️

 
  • Like 4

Share this post


Link to post
Share on other sites

Hello everyone,
while building an app-interface for a page, I developed some changes and improvements to this module, which I made available as a pull request
But @thomasaull and I are not quite sure if it makes sense to transfer these basic changes into the main module as well. Therefore we would like to hear your opinion: What do you think of the new module version? Which features would be useful for you? 

I have developed several new features that allow the administration of Api accesses via the ProcessWire backend. I also revised the authentication and added a new Double-JWT option that works with long-lasting refresh and short-lived access-tokens.

New Features:

  • New menu item "Restapi" in the ProcessWire menu under "setup
  • Management of Api accesses (applications) outsourced to the new menu item
  • Apikeys now authorize api-access
  • Creation of multiple applications with different auth types possible
  • Double-JWT Authentication, renewable tokens
  • token-sessions can be viewed and deleted in the backend
  • Improved exception handling: Each endpoint can throw exceptions, which are then output with the appropriate HTTP status header and message.
  • Like 8

Share this post


Link to post
Share on other sites

I am using this module in all my install now (it's a modified version with Basic Auth implemented) and all these additions look super !  Looking into it this afternoon, I will give my opinion. Thanks guys for the hard work 👍

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Mike Rockett
      Jumplinks for ProcessWire
      Release: 1.5.56
      Composer: rockett/jumplinks
      Jumplinks is an enhanced version of the original ProcessRedirects by Antti Peisa.
      The Process module manages your permanent and temporary redirects (we'll call these "jumplinks" from now on, unless in reference to redirects from another module), useful for when you're migrating over to ProcessWire from another system/platform. Each jumplink supports wildcards, shortening the time needed to create them.
      Unlike similar modules for other platforms, wildcards in Jumplinks are much easier to work with, as Regular Expressions are not fully exposed. Instead, parameters wrapped in curly braces are used - these are described in the documentation.
      Under Development: 2.0, to be powered by FastRoute
      As of version 1.5.0, Jumplinks requires at least ProcessWire 2.6.1 to run.
      View on GitLab
      Download via the Modules Directory
      Read the docs
      Features
      The most prominent features include:
      Basic jumplinks (from one fixed route to another) Parameter-based wildcards with "Smart" equivalents Mapping Collections (for converting ID-based routes to their named-equivalents without the need to create multiple jumplinks) Destination Selectors (for finding and redirecting to pages containing legacy location information) Timed Activation (activate and/or deactivate jumplinks at specific times) 404-Monitor (for creating jumplinks based on 404 hits) Additionally, the following features may come in handy:
      Stale jumplink management Legacy domain support for slow migrations An importer (from CSV or ProcessRedirects) Feedback & Feature Requests
      I’d love to know what you think of this module. Please provide some feedback on the module as a whole, or even regarding smaller things that make it whole. Also, please feel free to submit feature requests and their use-cases.
      Note: Features requested so far have been added to the to-do list, and will be added to 2.0, and not the current dev/master branches.
      Open Source

      Jumplinks is an open-source project, and is free to use. In fact, Jumplinks will always be open-source, and will always remain free to use. Forever. If you would like to support the development of Jumplinks, please consider making a small donation via PayPal.
      Enjoy! :)
    • By BitPoet
      As threatened in Ryan's announcement for 3.0.139, I built a little module for sliding toggles as a replacement for checkboxes. Styling of the input is CSS3 only (with all the usual caveats about older browsers), no JS necessary, and may still be a bit "rough around the edges", so to speak, since I didn't have much time for testing on different devices or brushing things up enough so I'd feel comfortable pushing it to the module directory. But here's the link to the GitHub repo for now:
      InputfieldSlideToggle
      Fieldtype and Inputfield that implements smartphone-style toggles as replacement for checkbox inputs. The visualization is CSS-only, no additional JS necessary.
      Status
      Still very alpha, use with caution!
      Features / Field Settings
      Size
      You can render the toggles in four different sizes: small, medium, large and extra large.
      Off Color
      Currently, "unchecked" toggles can be displayed either in grey (default) or red.
      On Color
      "Checked" toggles can be rendered in one of these colors: blue (default), black, green, grey, orange or red.
      Screenshots

      Some examples with checkbox label


      View all Size and Color Combinations
      Small toggles Medium toggles Big toggles Extra big toggles  









    • By Orkun
      Hi Guys
      I needed to add extended functionalities for the InputfieldDatetime Module (module is from processwire version 2.7.3) because of a Request of Customer.
      So I duplicated the module and placed it under /site/modules/.
      I have added 3 new Settings to the InputfieldDatetime Module.
      1. Day Restriction - Restrict different days based on weekdays selection (e.g. saturday, sunday) - WORKING

       
      2. Time Slots - Define Time slots based on custom Integer Value (max is 60 for 1 hour) - WORKING

       
      3. Time Range Rules per Weekday - Define a minTime and MaxTime per Weekday (e.g. Opening Hours of a Restaurant) - NOT WORKING PROPERLY

       
      The Problem
      Time Slots and Day Restriction working fine so far. But the Time Range Rules per Weekday doesn't work right.
      What should happen is, that when you click on a date, it should update the minTime and maxTime of the Time Select.
      But the change on the select only happens if you select a date 2 times or when you select a date 1 time and then close the datepicker and reopen it again.
      The time select doesn't get change when you select a date 1 time and don't close the picker.
      Here is the whole extended InputfieldDatetime Module.
      The Files that I have changed:
      InputfieldDatetime.module InputfieldDatetime.js jquery-ui-timepicker-addon.js (https://trentrichardson.com/examples/timepicker/) - updated it to the newest version, because minTime and maxTime Option was only available in the new version  
      Thats the Part of the JS that is not working correctly:
      if(datetimerules && datetimerules.length){ options.onSelect = function(date, inst) { var day = $(this).datetimepicker("getDate").getDay(); day = day.toString(); var mintime = $(this).attr('data-weekday'+day+'-mintime'); var maxtime = $(this).attr('data-weekday'+day+'-maxtime'); console.log("weekday: "+day); console.log("minTime: "+mintime); console.log("maxTime: "+maxtime); var optionsAll = $(this).datetimepicker( "option", "all" ); optionsAll.minTime = mintime; optionsAll.maxTime = maxtime; $(this).datetimepicker('destroy'); $(this).datetimepicker(optionsAll); $(this).datetimepicker('refresh'); //$.datepicker._selectDate($(this).attr("id"),date); //$.datepicker._base_getDateDatepicker(); // var inst = $.datepicker._getInst($(this)); // $.datepicker._updateDatepicker(inst); /*$(this).datetimepicker('destroy'); InputfieldDatetimeDatepicker($(this), mintime, maxtime); $(this).datetimepicker('refresh'); */ // $(this).datetimepicker('option', {minTime: mintime, maxTime: maxtime}); } } Can you have a look and find out what the Problem is?
      InputfieldDatetime.zip
       
      Kind Regards
      Orkun
    • By teppo
      This module tracks changes, additions, removals etc. of public (as in "not under admin") pages of your site. Like it's name says, it doesn't attempt to be a version control system or anything like that - just a log of what's happened.
      At the moment it's still a work in progress and will most likely be a victim of many ruthless this-won't-work-let's-try-that-instead cycles, but I believe I've nailed basic functionality well enough to post it here.. so, once again, I'll be happy to hear any comments you folks can provide
      https://modules.processwire.com/modules/process-changelog/
      https://github.com/teppokoivula/ProcessChangelog
      How does it work?
      Exactly like it's (sort of) predecessor, Process Changelog actually consists of two modules: Process Changelog and Process Changelog Hooks. Hooks module exists only to serve main module by hooking into various functions within Pages class, collecting data of performed operations, refining it and keeping up a log of events in it's own custom database table (process_changelog.) Visible part is managed by Process Changelog, which provides users a (relatively) pretty view of the contents of said log table.
      How do you use it?
      When installed this module adds new page called Changelog under Admin > Setup which provides you with a table view of collected data and basic filtering tools See attached screenshots to get a general idea about what that page should look like after a while.
      For detailed installation instructions etc. see README.md.
       


    • By Gadgetto
      Status update links (inside this thread) for SnipWire development will be always posted here:
      2019-08-08
      2019-06-15
      2019-06-02
      2019-05-25
      If you are interested, you can test the current state of development:
      https://github.com/gadgetto/SnipWire
      Please note that the software is not yet intended for use in a production system (alpha version).
      If you like, you can also submit feature requests and suggestions for improvement. I also accept pull requests.
      ---- INITIAL POST FROM 2019-05-25 ----
      I wanted to let you know that I am currently working on a new ProcessWire module that fully integrates the Snipcart Shopping Cart System into ProcessWire. (this is a customer project, so I had to postpone the development of my other module GroupMailer).
      The new module SnipWire offers full integration of the Snipcart Shopping Cart System into ProcessWire.
      Here are some highlights:
      simple setup with (optional) pre-installed templates, product fields, sample products (quasi a complete shop system to get started immediately) store dashboard with all data from the snipcart system (no change to the snipcart dashboard itself required) Integrated REST API for controlling and querying snipcart data webhooks to trigger events from Snipcart (new order, new customer, etc.) multi currency support self-defined/configurable tax rates etc. Development is already well advanced and I plan to release the module in the next 2-3 months.
      I'm not sure yet if this will be a "Pro" module or if it will be made available for free.
      I would be grateful for suggestions and hints!
      (please have a look at the screenshots to get an idea what I'm talking about)
       




×
×
  • Create New...