Jump to content

New Module: AppApi


Sebi

Recommended Posts

On 5/11/2021 at 4:00 PM, fliwire said:

hi need to add custom variable to every request .
Token has an_id value and need to fetch user data from another database. Tried bottom code but $tokenString is empty.

Simply need to add $token->an_id value to request $data object.

Hi @fliwire! Auth::getBearerToken() is a protected function. I do not exactly know how PHP handles that, but maybe that results into an empty string? You could copy the logic from Auth::getBearerToken() and Auth::getAuthorizationHeader() to try out if that is the issue. 

Additionally, hooking into Router::params could be a better place to add the logic since it is called later - after all auth-checks and just before Router::handle calls the targetted function.

Link to comment
Share on other sites

hi @Sebi found that that was server fault.  AUTHORIZATION headers not set.
cant find what apache module should enable but .htaccess solve my issue. 

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1


 

Link to comment
Share on other sites

Hi all. I've got something that I'm not 100% sure is a problem with AppApi or elsewhere, so I'm hoping someone can just help me cross the AppApi module off my list of the things I'm looking into.

I'm currently trying get my API to send an email when a certain POST is made. Locally this works fine, but on our test server I'm getting an unexpected error:

{
    "error": "Internal Server Error",
    "devmessage": {
        "message": "set_time_limit() has been disabled for security reasons",
        "location": "/home/runcloud/webapps/D2U-API/site/assets/cache/FileCompiler/site/modules/WireMailSmtp/WireMailSmtp.module",
        "line": 750
    }
}

Now a quick look through this forum suggests that this should be generating a PHP warning, that I should just be able to ignore, but for some reason it's stopping execution and generating the API error.

I'm wondering whether AppApi is handling this as a hard error and stopping execution, but really it would carry on fine if left, or whether the situation I'm seeing is more serious than the examples in that other forum post?

@Sebi or @thomasaull do you have any comments about how a PHP runtime warning would be handled?

Link to comment
Share on other sites

10 minutes ago, David Lumm said:

I'm wondering whether AppApi is handling this as a hard error and stopping execution, but really it would carry on fine if left, or whether the situation I'm seeing is more serious than the examples in that other forum post?

Yeah, that's exactly what's happening. In Router.php:

public static function handleError($errNo, $errStr, $errFile, $errLine) {
        if (error_reporting()) {
            $return = new \StdClass();
            $return->error = 'Internal Server Error';
            $return->devmessage = [
                'message' => $errStr,
                'location' => $errFile,
                'line' => $errLine
            ];
            self::displayOrLogError($return, 500);
        }
    }

So if any error logging is enabled this will be fired, regardless of whether we actually care about that type of error. I've made some modifications, so I'll do a PR and you can see what you think @Sebi

  • Like 1
Link to comment
Share on other sites

Hi friends, I'm here again with another newbie question, but...
I'm getting "failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized" when I try to access API using file_get_contents from PHP page.

I'm passing ApiKey (PHP Session) and logged in as superuser.

If I remove ["auth"=>true] from routes.php it works.

In my mind, if I'm logged in as superuser it should work with authorization enabled or am I wrong? 

Here is my code...

Thank you all!

$apiKey = $config->apikey;

$getdata = http_build_query(
    [
        'nome' => 'sample name',
        'endereco' => 'sample address'
    ]
);

$context = stream_context_create(
    [
        'http' => [
            'method' => 'GET',
            'header' => ["X-Api-Key: $apiKey", "Content-Type: application/x-www-form-urlencoded"],
        ],
        'ssl' => [
            'verify_peer'      => false,
            'verify_peer_name' => false
        ]
    ]
);

$url_returns = file_get_contents("$url" . $getdata, false, $context);

 

Link to comment
Share on other sites

Additional informations:

I believe the AppApi has a bug with PHP Session.

I've changed the line 187 in router.php to show the user name logged in and it shows "guest".

if (isset($routeParams['auth']) && $routeParams['auth'] === true && !$this->wire('user')->isLoggedIn()) {
            throw new AppApiException('User does not have authorization ' .$this->wire('user')->name, 401);

But running the same command inside a page it shows the real name of logged user.

Inside Page user name = 2069008

From API :
{"error":"User does not have authorization guest","devmessage":{"class":"ProcessWire\\AppApiException","code":401,"message":"User does not have authorization guest","location":"C:\\xampp\\htdocs\\cinemed\\site\\modules\\AppApi\\classes\\Router.php","line":187}

Any help please?

Thank you all!

Link to comment
Share on other sites

  • 2 weeks later...
On 5/24/2021 at 2:38 PM, David Lumm said:

Yeah, that's exactly what's happening. In Router.php:


public static function handleError($errNo, $errStr, $errFile, $errLine) {
        if (error_reporting()) {
            $return = new \StdClass();
            $return->error = 'Internal Server Error';
            $return->devmessage = [
                'message' => $errStr,
                'location' => $errFile,
                'line' => $errLine
            ];
            self::displayOrLogError($return, 500);
        }
    }

So if any error logging is enabled this will be fired, regardless of whether we actually care about that type of error. I've made some modifications, so I'll do a PR and you can see what you think @Sebi

Hey @David Lumm, thank you for your pull request! 

I'm still testing out a few things at the moment, but I wanted to report back briefly at least. I catch all exceptions and errors at the top of Router.php to handle them myself:

    set_error_handler("ProcessWire\Router::handleError");
    set_exception_handler('ProcessWire\Router::handleException');
    register_shutdown_function('ProcessWire\Router::handleFatalError');

My main goal was to prevent a plaintext or HTML error message from being displayed when an API function was requested. Instead, the message should be output as JSON. @David LummDo I understand your commit correctly, that you disable this behaviour for warnings and only log the warning additionally? My goal is actually only that no PHP echo is made with the warning. A PHP echo before a JSON response would render the whole response useless.

Do any of you know how I can prevent this echo, but the warning is still treatable in the non-module code?

Link to comment
Share on other sites

On 5/27/2021 at 8:59 AM, Bacos said:

Additional informations:

I believe the AppApi has a bug with PHP Session.

I've changed the line 187 in router.php to show the user name logged in and it shows "guest".


if (isset($routeParams['auth']) && $routeParams['auth'] === true && !$this->wire('user')->isLoggedIn()) {
            throw new AppApiException('User does not have authorization ' .$this->wire('user')->name, 401);

But running the same command inside a page it shows the real name of logged user.

Inside Page user name = 2069008

From API :
{"error":"User does not have authorization guest","devmessage":{"class":"ProcessWire\\AppApiException","code":401,"message":"User does not have authorization guest","location":"C:\\xampp\\htdocs\\cinemed\\site\\modules\\AppApi\\classes\\Router.php","line":187}

Any help please?

Thank you all!

 

Hi @Bacos,  I have just tested it once through. At least it doesn't seem to be a general problem with AppApi's auth. In my Processwire test installation (running local with MAMP) I can protect a route with ['auth' => true]. It is then only accessible if I have logged in beforehand. In fact, there still seems to be a discrepancy, as I was also able to authenticate via the session with an apikey of type "Double JWT". But I will fix that soon.

Unfortunately, I'm not really familiar with stream_context_create. My API requests are mostly made from a Javascript context. Is it possible that the session is not passed on correctly? Does the session or the cookies perhaps have to be specified as a parameter in stream_context_create?

Link to comment
Share on other sites

Hi Sebi,

I guess I'm a little confused about phpSession feature. 

Calling API with curl getting the same problem.

Do you have some sample calling API inside a processwire template with route authenticated ?

Calling from Postman with JWT works fine. 

Thank you again!

Link to comment
Share on other sites

Hey @Bacos,
unfortunately I really don't have much experience with api requests from PHP. 

In my beautiful, carefree javascript world, the browser handles the session cookies, so I can log in normally via the ProcessWire backend, and then get the logged in user back in the frontend via a simple call to the /api/auth/ interface:

fetch(
	'/api/auth/', {
	headers: {
		'X-API-KEY': 'SHBaob3siaud8A'
	}
})
	.then(response => response.json())
	.then(response => console.log("RESPONSE", response));

Postman also handles session cookies for you automatically, so you don't have to worry about it manually.

I did a bit of research. If you want to make your API request in PHP, it seems you have to take care of the session cookies yourself. The answer under this stackoverflow post seems to be a usable example, but with a CURL request instead of stream_context_create, which is what you're using:https://stackoverflow.com/a/10307956/5477836
In short, you have to log in via a PHP request, and the session cookies are written to the specified file path. The next time you make a request, you can then reuse those cookies to authenticate yourself. (If anyone here knows better about this, please correct me). 

If I were in your place, I would probably try the Auth-Type Single JWT instead of the Auth-Type PHP-Session. The advantage here would be that you get back a login token (string) on the /api/auth/ request, which you could then send along as a header on the next requests. This seems easier to me than having to mess with a cookie file. But that's up to you to decide...

I hope you get somewhere with this? Also feel free to let me know if you have something executable. Maybe this would be a good example for documentation!

Link to comment
Share on other sites

I have setup the module and all work fine: my api send data to a client axios, but i have a problem with a file 

My api send this data json

 

{
    "data": [
        {
            "url": "http://p1.test/site/assets/files/1017/gpx.gpx",
            "title": "prova"
        }
    ]
}

and in the quasar app i need to use the file gpx for show a leaflet map.

I get this error

Access to fetch at 'http://p1.test/site/assets/files/1017/gpx.gpx' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

in the .htaccess file i have set this lines at the bottom 

 

RewriteEngine on
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

but the file is not fetched....

What i broken? Thank you (excuse me for the poor english language)

Link to comment
Share on other sites

Hey@abmcr,

I think that it is not a good idea to release all pages for cross-origin requests. But I have an alternative for you. You could also request the file via the api interface. Then the module would automatically set the CORS headers and the request would be a bit more secured by the apikey.

You can take the following class: https://github.com/Sebiworld/musical-fabrik.de/blob/f172a9ef4674e09cabce1fdcf4e55ddeea150d1b/site/api/FileAccess.class.php
It is in productive use in one of my projects. Copy the class into the directory where your Routes.php file is located (default is site/api/).

Now you can add the following endpoints to your Routes-definition:

<?php

namespace ProcessWire;

require_once wire('config')->paths->AppApi . 'vendor/autoload.php';
require_once wire('config')->paths->AppApi . 'classes/AppApiHelper.php';

require_once __DIR__ . '/FileAccess.class.php';

$routes = [
	'file' => [
		['OPTIONS', '{id:\d+}', ['GET']],
		['OPTIONS', '{path:.+}', ['GET']],
		['OPTIONS', '', ['GET']],
		['GET', '{id:\d+}', FileAccess::class, 'pageIDFileRequest'],
		['GET', '{path:.+}', FileAccess::class, 'pagePathFileRequest'],
		['GET', '', FileAccess::class, 'dashboardFileRequest']
	]
];

Full Routes.php for reference: https://github.com/Sebiworld/musical-fabrik.de/blob/f172a9ef4674e09cabce1fdcf4e55ddeea150d1b/site/api/Routes.php

After these routes are integrated, you can call the new /api/file/ endpoint:

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  headers: {
    'X-API-KEY': 'ThisIsYourCustomApiKey',
    'Authorization': 'Bearer ...' // optional if authentication needed
  }
});

instance.get('/file/1017', {
  file: 'gpx.gpx'
}).then(function (response) {
  console.log(response); // This should be your file
}).catch(function (error) {
  console.log(error.toJSON());
});

(Code not tested, only taken from Axios docs and changed to the correct parameters) 

I hope that I could help you with this!
[And please don't worry about your English. Everything is understandable, and there are many non-native speakers here. You don't have to apologize for anything :-)]

Link to comment
Share on other sites

Version 1.1.6 is out! 🥳

Changelog:

  • Adds Router->registerErrorHandlers() Hook, that should allow you to overwrite the general error- and warning handlers of the module. That should fix the problem that @David Lumm mentioned above without breaking things for other users.
  • Allows Apikey & Auth-token to be set as GET-params. That can be useful when it comes to loading images via api.
  • Fixes a bug that made it possible to authenticate with the PHP session (cookie) even though token-auth was enabled.
  • Adds Router->setCorsHeaders() Hook
  • Updated Composer & Firebase dependencies
  • Like 3
Link to comment
Share on other sites

  • 2 months later...

Hi @Sebi

your module is of great help, we are using it in quite a view projects allready.

i just build a mobile app with a processwire backend using Double JWT. While implenting it i noticed the following:

In the docs the /auth route is described to be used like this (in addition to basic auth):

 

// Alternatively you can send username/pass in the request-body:
this.httpClient.post(
  'https://my-website.dev/api/auth',
  JSON.stringify({
    username: username,
    password: pass,
  }),
  {
    'x-api-key': 'ytaaYCMkUmouZawYMvJN9',
  }
);

but this does not work for me. It actually works with basic out and also when sending username and password as form-data. But not as JSON. Its no big deal with two working alternatives, but it would be actually nice to have the JSON option also (specially since form-data can be challenging to set up with some http-clients.

I allways get the following error with the above call:

 

{
  "username": null,
  "pass": null,
  "post": [],
  "test": "{\n\t\"username\": \"REMOVED\",\n\t\"password\": \"REMOVED\"\n}",
  "errorcode": "general_auth_exception",
  "error": "Login not successful"
}

Best,
Michael

  • Like 1
Link to comment
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 Robin S
      This module lets you add some custom menu items to the main admin menu, and you can set the dropdown links dynamically in a hook if needed.
      Sidenote: the module config uses some repeatable/sortable rows for the child link settings, similar to the ProFields Table interface. The data gets saved as JSON in a hidden textarea field. Might be interesting to other module developers?
      Custom Admin Menus
      Adds up to three custom menu items with optional dropdowns to the main admin menu.
      The menu items can link to admin pages, front-end pages, or pages on external websites.
      The links can be set to open in a new browser tab, and child links in the dropdown can be given an icon.
      Requires ProcessWire v3.0.178 or newer.
      Screenshots
      Example of menu items

      Module config for the menus

      Link list shown when parent menu item is not given a URL

      Advanced
      Setting child menu items dynamically
      If needed you can set the child menu items dynamically using a hook.
      Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); if($menu_number === 1) { $colours = $event->wire()->pages->findRaw('template=colour', ['title', 'url', 'page_icon']); $children = []; foreach($colours as $colour) { // Each child item should be an array with the following keys $children[] = [ 'icon' => $colour['page_icon'], 'label' => $colour['title'], 'url' => $colour['url'], 'newtab' => false, ]; } $event->return = $children; } }); Create multiple levels of flyout menus
      It's also possible to create multiple levels of flyout submenus using a hook.

      For each level a submenu can be defined in a "children" item. Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); if($menu_number === 1) { $children = [ [ 'icon' => 'adjust', 'label' => 'One', 'url' => '/one/', 'newtab' => false, ], [ 'icon' => 'anchor', 'label' => 'Two', 'url' => '/two/', 'newtab' => false, 'children' => [ [ 'icon' => 'child', 'label' => 'Red', 'url' => '/red/', 'newtab' => false, ], [ 'icon' => 'bullhorn', 'label' => 'Green', 'url' => '/green/', 'newtab' => false, 'children' => [ [ 'icon' => 'wifi', 'label' => 'Small', 'url' => '/small/', 'newtab' => true, ], [ 'icon' => 'codepen', 'label' => 'Medium', 'url' => '/medium/', 'newtab' => false, ], [ 'icon' => 'cogs', 'label' => 'Large', 'url' => '/large/', 'newtab' => false, ], ] ], [ 'icon' => 'futbol-o', 'label' => 'Blue', 'url' => '/blue/', 'newtab' => true, ], ] ], [ 'icon' => 'hand-o-left', 'label' => 'Three', 'url' => '/three/', 'newtab' => false, ], ]; $event->return = $children; } }); Showing/hiding menus according to user role
      You can determine which menu items can be seen by a role by checking the user's role in the hook.
      For example, if a user has or lacks a role you could include different child menu items in the hook return value. Or if you want to conditionally hide a custom menu altogether you can set the return value to false. Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); $user = $event->wire()->user; // For custom menu number 1... if($menu_number === 1) { // ...if user does not have some particular role... if(!$user->hasRole('foo')) { // ...do not show the menu $event->return = false; } } });  
      https://github.com/Toutouwai/CustomAdminMenus
      https://processwire.com/modules/custom-admin-menus/
    • By tcnet
      This module for ProcessWire sends a notification email for each failed login attempt. Similar modules exists already in the module directory of ProcessWire. However, this module is designed to notify, even if specified user doesn't exist.
      Settings
      The settings for this module are located in the menu Modules=>Configure=>LoginFailNotifier.
      Notification email
      Specifies the email address to which the notification emails should be sent.
        Email subject
      Specifies the subject line for the notification email.
        Post variables
      Specifies the $_POST variables to be included in the notification email. Each variable must be separated by a comma. For example: login_name,login_pass
        Server variables
      Specifies the $_SERVER variables to be included in the notification email. Each variable must be separated by a comma. For example: REMOTE_ADDR,HTTP_USER_AGENT
      Link to ProcessWire module directory:
      https://processwire.com/modules/login-fail-notifier/
      Link to github.com:
      https://github.com/techcnet/LoginFailNotifier
    • By Fokke
      ProcessWire 3.x markup module for rendering meta tags in HTML document head section. Note that this module is not a full-blown SEO solution, but rather a simple tool for rendering meta tags based on module configuration. Adding custom meta tags is also supported.
      Built-in meta tags
      The following meta tags are supported out-of-the-box:
      Document title consisting of page title and site name Character set Canonical Viewport Description Keywords Hreflang tags Open Graph og:title og:site_name og:type og:url og:description og:image og:image:width og:image:height Twitter meta tags twitter:card twitter:site twitter:creator twitter:title twitter:description twitter:image Facebook meta tags fb:app_id The full documentation with configurable options can be found here: https://github.com/Fokke-/MarkupMetadata
       
      Requirements:
      ProcessWire>=3.0.0 PHP >=7.1 Installation using Composer
      composer require fokke/markup-metadata Manual installation
      Download latest version from https://github.com/Fokke-/MarkupMetadata/archive/master.zip Extract module files to site/modules/MarkupMetadata directory.
    • By m.sieber
      ITRK-Service for ProcessWire
      Module for the automated transfer of imprint, data protection declaration and terms and conditions from IT-Recht Kanzlei to your ProcessWire installation
      What is ITRK Service for ProcessWire?
      ITRK-Service for ProcessWire is a free module for ProcessWire CMS. It provides an interface to the update service of IT-Recht Kanzlei, via which the legal texts of your online presence are automatically updated. In this way, the texts remain legally secure and warning-proof in the long term. Imprint, data protection declaration, revocation and general terms and conditions are currently supported.
      You can find our documentation (in german language) here: https://www.pupit.de/itrk-service-for-processwire/dokumentation/

      Download: https://www.pupit.de/itrk-service-for-processwire/
      Github: https://github.com/pupit-de/pwItrkServiceConnector
    • By LuisM
      Symprowire is a PHP MVC Framework based and built on Symfony using ProcessWire 3.x as DBAL and Service-Provider
      It acts as a Drop-In Replacement Module to handle the Request/Response outside the ProcessWire Admin. Even tough Symfony or any other mature MVC Framework could be intimidating at first, Symprowire tries to abstract Configuration and Symfony Internals away as much as possible to give you a quick start and lift the heavy work for you.
      The main Goal is to give an easy path to follow an MVC Approach during development with ProcessWire and open up the available eco-system.
      You can find the GitHub Repo and more Information here: https://github.com/Luis85/symprowire
      Documentation
      The Symprowire Wiki https://github.com/Luis85/symprowire/wiki How to create a simple Blog with Symprowire https://github.com/Luis85/symprowire/wiki/Symprowire-Blog-Tutorial Last Update
      16.07.2021 // RC 1 v0.6.0 centralized ProcessWire access trough out the Application by wrapping to a Service https://github.com/Luis85/symprowire/releases/tag/v0.6.0-rc-1 Requirements
      PHP ^7.4 Fresh ProcessWire ^3.0.181 with a Blank Profile Composer 2 (v1 should work, not recommended) The usual Symfony Requirements Features
      Twig Dependency Injection Monolog for Symprowire Support for .env YAML Configuration Symfony Console and Console Commands Symfony Webprofiler Full ProcessWire access inside your Controller and Services Webpack Encore support Caveats
      Symfony is no small Framework and will come with a price in terms of Memory Usage and added Overhead. To give you a taste I installed Tracy Debugger alongside to compare ProcessWire profiling with the included Symfony Webprofiler

      So in a fresh install Symprowire would atleast add another 2MB of Memory usage and around 40ms in response time, should be less in production due to the added overhead of the Webprofiler in dev env
       
×
×
  • Create New...