Jump to content

Sebi

Members
  • Posts

    56
  • Joined

  • Last visited

  • Days Won

    1

Everything posted by Sebi

  1. Hey @csaggo.com, thank you very much for your input! This should not be a big problem, I will have a look at it in the next few days. I'll get back to you soon :-)
  2. 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
  3. 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 :-)]
  4. 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!
  5. 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?
  6. 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?
  7. 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.
  8. @thomasaullThank you! You are right - AppApiModule->checkIfApiRequest() compares with the full path of $_SERVER['REQUEST_URI']. Because of that, we must give the full path to the module-config, even if the ProcessWire root is in a subfolder. @Bacos: If you have only api instead of testeapi/api in your configuration, that would result in an 404 error!
  9. Hi @Bacos, You're right: If the AppApi module had received the Api request correctly, even an incorrect request would be answered with an exception and a JSON response. You get a HTML-response, so the request is not received by the module. Let's see... You send your request to https://localhost/testeapi/api/test - so your processwire root is https://localhost/testeapi/, am I right? Can you please double-check if your module's config looks like this: Another reason for a 404 error could be that you have already created a page in the ProcessWire page tree that is accessible under the /api route. Since the module uses a hook on ProcessPageView::pageNotFound to intercept requests, there must not be a page serving the api route. I think that's all the approaches I can think of for now. Was there perhaps already something suitable 🙃?
  10. Absolutely! But I'm glad, that I could fix the old handler, so it will work regardless which ProcessWire version is used. I think it would make sense to additionally add the new hook functionality. It should grab the request before it triggers 404. But that is something that must be tested very carefully.
  11. I do not use the pagination function, but I had similar issues with my AppApi module, that resulted in a 404 error in ProcessWire versions >= 1.0.173. So maybe it is related to it? The short version is: wire('input')->url no longer returns the requested url in the hook function I use, but only "/http404/" in the new ProcessWire versions. So in my module I now use $_SERVER['REQUEST_URI'], which works. I couldn't find anything yet with a quick look in the MarkupPagerNav class, but maybe it will help you or @ryan to find a solution...
  12. It is done. I have found the error. Version 1.1.5, which I just released, fixes the bug and makes AppApi fully compatible with ProcessWire versions >= 1.0.173 again. For those interested in the details: It was just a tiny little thing that caused the module to no longer be able to find out if an api url was requested. This is what the code for it looked like: protected function checkIfApiRequest() { $url = $this->sanitizer->url($this->input->url); // support / in endpoint url: $endpoint = str_replace('/', "\/", $this->endpoint); $regex = '/^\/' . $endpoint . '\/?.*/m'; preg_match($regex, $url, $matches); return !!$matches; } However, in ProcessWire versions >= 1.0.173, $this->input->url (or wire('input')->url) now no longer contains the requested URL (e.g. "/api/page/"), but already the URL of the 404 error page "/http404/". Thus, the module could no longer determine whether it should handle the request or not. But the solution to the problem was easier than I thought. $_SERVER['REQUEST_URI'] still contains the correct value. So we use that now for this check. And because this would have worked before, we don't need to worry about AppApi not working with older ProcessWire versions now. The fixed version simply looks like this: protected function checkIfApiRequest() { $url = $this->sanitizer->url($_SERVER['REQUEST_URI']); // support / in endpoint url: $endpoint = str_replace('/', "\/", $this->endpoint); $regex = '/^\/' . $endpoint . '\/?.*/m'; preg_match($regex, $url, $matches); return !!$matches; } Finally, thank you again for your reports. And I hope that you can now run your apis with the latest ProcessWire versions again. Thank you for using AppApi! 🤩
  13. Hi everyone! I did not have the time to look deep into it, but looks like version 3.0.173 has made some changes into the handling of hooks. Especially hooks for custom urls, like we do in AppApi. Previously we had to use a little workaround to get it done - we hook into 404 (site not found) exceptions and generate our own response, if the request was made for /api/... The new update seems to add a functionality, where our module can use an url, without doing the 404-hack. But the new functionality seems also to break some of the old functionality. 🤨 So, please wait with the 3.0.173 upgrade! Thank you @csaggo.com and @psy for mentioning it. I will have time to look into it on the weekend - pull requests or hints are very welcome!
  14. I released v1.1.4 of AppApi. The update fixes a critical bug that occurred when routes were called with GET parameters. (reported by @David Lumm, thanks for PR 🤗) Because I was already at it, I outsourced the reading of the current route (which is then further used by FastRoute) to its own hookable function `___getCurrentUrl()`. This allows you in special use cases to subsequently influence the URL with your own hook function.
  15. @psy So, just to make sure, that everything works well on the PHP side: You can make a request via Postman to the same url that you are trying to access via Javascript? And you get back the expected JSON-data? Unfortunately, I don't know much about NextJS and React. I am actually an Angular or Vanilla Javascript developer. In an Angular environment I would use Angular's httpClient to make an api-call: const params = new HttpHeaders({ 'x-api-key': environment.api_key }); this.httpClient.get('https://my-test-domain.com/api/page/1042').subscribe( response => console.log("Api-Response: ", response) ); I assume that React has a similar helper class as well. This makes a call to the page-route in my router-definition, which you can see here: https://github.com/Sebiworld/musical-fabrik.de/blob/master/site/api/Routes.php . It will return the ajax-results for the ProcessWire page with id 1042 in this case. I prefer to use the httpClient (if available) instead of the fetch function, which you are using in your code-example above. Mainly because I found the fetch function very cumbersome to use when dealing with more complex parameter data. But for a vanilla-js project I needed to use it, so I wrote a helper class that is way more usable: https://github.com/Sebiworld/musical-fabrik.de/blob/master/site/templates/src/js/classes/AjaxCall.js Here is how you can make an api-call: const ajaxCall = new AjaxCall({ method: 'GET', path: '/api/page/1042', headers: { 'X-API-KEY': 'oiasnduz3498gfsubasd' } }); ajaxCall.fetch().then(function(response){ console.log('Api-response: ', response); }).catch(function(response){ console.log('Api-error: ', response); }); I hope that helps you out 😊
  16. Hi @psy, At first glance, I can't find any obvious error in your code. Can you please show me the server response you get for the "Invalid Json" errors? (You can see each request/response in your browser's developer-console in the network-tab. Feel free to DM me if you need support for that.) I would try to take out some complexity first and leave Twack out of the queries for now. It's best to set up a test route that only returns a simple response. Insert this to your Routes.php: 'v1' => [ 'test' => [ ['OPTIONS', '', ['GET']], ['GET', '', AppApiTest::class, 'test'] ] ], ] And create the AppApiTest-class: <?php namespace ProcessWire; class AppApiTest { public static function test($data) { return [ 'test' => true, 'success' => 'YEAH!' ]; } } No token-authentication needed. If you get this response back in Javascript, we can be sure that the basic api connection works.
  17. I just released version 1.1.3 which resolves three issues that were reported recently: Fixes an issue with the constructor signature of the modules AppApiException class (by @David Lumm, thanks for PR 🤗) Fixes an issue with the error-handler, which made it mistakenly catch errors that should have been ignored via @ operator (Thanks to @eelkenet) Switched from `wire('input')->url` to `$_SERVER['REQUEST_URI']` for reading the base-url, because ProcessWire's internal function transferred everything to lowercase. (Thanks to Github-user @pauldro) Thank you all for your contributions!
  18. Hi @thibaultvdb, thank you for reporting this issue! I'll be honest: In my Apis I actually always use arrays as return values, so I didn't notice this bug. With version 1.1.2, which I just released, you can use a stdclass again instead of an array as return value. I hope everything is running smoothly again with your Api? I would be very happy about a short feedback!
  19. @David Lumm: v1.1.1 is out. It changes the datatype to int(1). Works for me - can you please check if that fixes the error on your configuration, too? @derixithy: You mentioned the same error - I hope that v1.1.1 fixes it!
  20. Hi @David Lumm, I'm workung on an emergency fix. Still cannot reproduce the problem, but I will try to change the datatype of the default_application-column from boolean to int. Hopefully that fixes it.
  21. Hey @David Lumm, thanks! Short answer: Yes, I'm pretty sure that upgrading to 1.1.0 will not break anything. Longer answer: Every previous functionality will work as before - there are only additional features, but no breaking changes. During the update the module will add a new column "default_application" to the appapi_applications table. Everything else stays the same. To be on the safe side, I tested upgrading to 1.1.0 and new installing in multiple different configurations. Besides @derixithy 's comment above I did not hear any problems. But if against all expectations you notice something, feel free to contact me 🤗
  22. Hey @derixithy, I've just set up a new ProcessWire-instance (current stable 3.0.165) and installed the module. Everything seems normal and I can add applications without getting an error. Maybe it is a problem with your individual configuration, can you give me additional details (e.g. ProcessWire-version, was AppApi installed before and updated to v1.1.0, or is it a fresh install? What PHP-version do you run?) The following is the INSERT-statement I use to create a new application in db: $createStatement = 'INSERT INTO `' . AppApi::tableApplications . '` (`id`, `created_user_id`, `created`,`modified_user_id`, `modified`, `title`, `description`, `default_application`, `token_secret`, `accesstoken_secret`, `authtype`, `expires_in`) VALUES (NULL, :created_user_id, :created, :modified_user_id, :modified, :title, :description, :default_application, :token_secret, :accesstoken_secret, :authtype, :expires_in);'; So let me try to interpret the error message... "Invalid datetime format: 1366" - 1366 looks like a user-id, that should be used as variable :created_user_id. But it tries to insert that value to a datetime-column, which could be the 'created'-column that follow right after that in the insert-statement. So it looks like that something went wrong with the variable-values for the PHP-prepared statement I use. You find the create-statement here in the code: https://github.com/Sebiworld/AppApi/blob/65911a3f13c6420ffad0e68b34d8c51a8b1eb99c/classes/Application.php#L614 Have any of you ever seen anything like this?
  23. Sebi

    Twack

    Just released version 2.1.4 with an improved documentation. I moved most of the contents from README.md to the repository-wiki. Everything is better structured and more readable 🤗
  24. Thank you @3fingers ! Your coffees will help me to stay motivated ☺️
  25. @thomasaull is right. I have added an example in the Wiki, in which I demonstrate the output of a RepeaterMatrix-field "contents" that I use in most of my projects: https://github.com/Sebiworld/AppApi/wiki/3.1:-Output-Formatting#complex-data I hope, that helps. Generally speaking, you can output anything you want via api. You only have to transform complex structures like ProcessWire-Pages, Repeatermatrix-fields, ... into something that is JSON-encodable.
×
×
  • Create New...