Cakephp3 Tiny Auth Allow Auth fail - authentication

I am using the TinyAuth plugin with my Cakephp3. I have a controller with the following namespace:
namespace App\Controller\Api\Datatables;
The controller is Listings and my function is Filter
I have the following route setup:
Router::scope('/datatables', ['prefix' => 'api/datatables'], function (RouteBuilder $routes) {
$routes->extensions(['json', 'xml', 'ajax']);
$routes->fallbacks(DashedRoute::class);
});
This allows me to call the following url:
/datatables/listings/filter.json
I want to allow the filter function:
datatables/Listings = filter
When I call my URL I am re-directed to login. If I login the url works, so the allow_auth works.
I have also tried the following:
api/datatables/Listings = filter
api/Datatables/Listings = filter
Api/Datatables/Listings = filter
api/datatables/Listings = filter
datatables/Listings = filter
Datatables/Listings = filter
api/Listings = filter
No matter what the path is not allowed. If I move the controller to the default location then in allow_auth:
Listings = filter
the filter function is accessible without authorisation. This suggests that there is a problem with the plugin when using a router scope.
Here is the plugin's composer.json
{
"name": "ypnos-web/cakephp-datatables",
"description": "jQuery DataTables for CakePHP 3",
"homepage": "https://github.com/ypnos-web/cakephp-datatables",
"type": "cakephp-plugin",
"keywords": ["cakephp", "datatables"],
"license": "MIT",
"authors": [
{
"name": "Frank Heider",
"homepage": "https://github.com/fheider",
"role": "Author"
},
{
"name": "Johannes Jordan",
"homepage": "https://github.com/ypnos-web",
"role": "Author"
}
],
"require": {
"php": ">=7.0",
"cakephp/cakephp": "^3.6"
},
"autoload": {
"psr-4": {
"DataTables\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"DataTables\\Test\\": "tests",
"Cake\\Test\\": "./vendor/cakephp/cakephp/tests"
}
}
}
Am I correct in stating that the slashed routes do work for the acl.ini - they seem to as far as I can see.
I am using the slashed routes to better organise my functions.
My request params are as follows when I call /datatables/listings/filter.json?
'controller' => 'Listings',
'action' => 'filter',
'pass' => [],
'prefix' => 'api/datatables',
'plugin' => null,
'_ext' => 'json',
'_matchedRoute' => '/datatables/:controller/:action/*',
'?' => [
'string' => 'seat'
]
If I call /api/datatables/listings/filter.json:
Controller class Datatables could not be found.

I'm not overly familiar with the plugin, but api/datatables/Listings seems to be the correct format, however looking at the plugin's source, it seems that nested prefixes aren't supported:
if (strpos($key, '/') !== false) {
list($res['prefix'], $key) = explode('/', $key);
}
https://github.com/dereuromark/cakephp-tinyauth/blob/1.11.0/src/Utility/Utility.php#L23-L25
That code would parse api as the prefix, and datatables as the controller.
You may want to open an issue, or add support for it yourself if you can.

Related

Mimic the ( Show All ) link in datatables.net

I have a situation where I want to get the full (data) from the backend as a CSV file. I have already prepared the backend for that, but normally the front-end state => (filters) is not in contact with the backend unless I send a request, so I managed to solve the problem by mimicking the process of showing all data but by a custom button and a GET request ( not an ajax request ). knowing that I am using serverSide: true in datatables.
I prepared the backend to receive a request like ( Show All ) but I want that link to be sent by custom button ( Export All ) not by the show process itself as by the picture down because showing all data is not practical at all.
This is the code for the custom button
{
text: "Export All",
action: function (e, dt, node, config) {
// get the backend file here
},
},
So, How could I send a request like the same request sent by ( Show All ) by a custom button, I prepared the server to respond by the CSV file. but I need a way to get the same link to send a get request ( not by ajax ) by the same link that Show All sends?
If you are using serverSide: true that should mean you have too much data to use the default (serverSide: false) - because the browser/DataTables cannot handle the volume. For this reason I would say you should also not try to use the browser to generate a full export - it's going to be too much data (otherwise, why did you choose to use serverSide: true?).
Instead, use a server-side export utility - not DataTables.
But if you still want to pursuse this approach, you can build a custom button which downloads the entire data set to the DataTables (in your browser) and then exports that complete data to Excel.
Full Disclosure:
The following approach is inspired by the following DataTables forum post:
Customizing the data from export buttons
The following approach requires you to have a separate REST endpoint which delivers the entire data set as a JSON response (by contrast, the standard response should only be one page of data for the actual table data display and pagination.)
How you set up this endpoint is up to you (in Laravel, in your case).
Step 1: Create a custom button:
I tested with Excel, but you can do CSV, if you prefer.
buttons: [
{
extend: 'excelHtml5', // or 'csvHtml5'
text: 'All Data to Excel', // or CSV if you prefer
exportOptions: {
customizeData: function (d) {
var exportBody = getDataToExport();
d.body.length = 0;
d.body.push.apply(d.body, exportBody);
}
}
}
],
Step 2: The export function, used by the above button:
function GetDataToExport() {
var jsonResult = $.ajax({
url: '[your_GET_EVERYTHING_url_goes_here]',
success: function (result) {},
async: false
});
var exportBody = jsonResult.responseJSON.data;
return exportBody.map(function (el) {
return Object.keys(el).map(function (key) {
return el[key]
});
});
}
In the above code, my assumption is that the JSON response has the standard DataTables object structure - so, something like:
{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "8422"
},
{
"id": "3",
"name": "Ashton Cox",
"position": "Junior Technical Author",
"salary": "$86,000",
"start_date": "2009/01/12",
"office": "San Francisco",
"extn": "1562"
}
]
}
So, it's an object, containing a data array.
The DataTables customizeData function is what controls writing this complete JSON to the Excel file.
Overall, your DataTables code will look something like this:
$(document).ready(function() {
$('#example').DataTable( {
serverSide: true,
dom: 'Brftip',
buttons: [
{
extend: 'excelHtml5',
text: 'All Data to Excel',
exportOptions: {
customizeData: function (d) {
var exportBody = GetDataToExport();
d.body.length = 0;
d.body.push.apply(d.body, exportBody);
}
}
}
],
ajax: {
url: "[your_SINGLE_PAGE_url_goes_here]"
},
"columns": [
{ "title": "ID", "data": "id" },
{ "title": "Name", "data": "name" },
{ "title": "Position", "data": "position" },
{ "title": "Salary", "data": "salary" },
{ "title": "Start Date", "data": "start_date" },
{ "title": "Office", "data": "office" },
{ "title": "Extn.", "data": "extn" }
]
} );
} );
function GetDataToExport() {
var jsonResult = $.ajax({
url: '[your_GET_EVERYTHING_url_goes_here]',
success: function (result) {},
async: false
});
var exportBody = jsonResult.responseJSON.data;
return exportBody.map(function (el) {
return Object.keys(el).map(function (key) {
return el[key]
});
});
}
Just to repeat my initial warning: This is probably a bad idea, if you really needed to use serverSide: true because of the volume of data you have.
Use a server-side export tool instead - I'm sure Laravel/PHP has good support for generating Excel files.

Removing join table data in sequelize returned value

I am currently trying to remove a joint table data added when retrieving an association data.
The query is done by sequelize using a method added to the model through specifying model relationships(sequelize magic methods), for some reason, I'm not able to do that.
I have currently tried passing in attributes: {exclude: ['...']} to the method but the field still persists.
Current association
// Class sequelize model
Class.belongsToMany(models.Subject, {
through: 'ClassSubject',
foreignKey: 'class_id',
otherKey: 'subject_id',
as: 'subjects'
})
// Subject sequelize model
Subject.belongsToMany(models.Class, {
through: 'ClassSubject',
foreignKey: 'subject_id',
otherKey: 'class_id',
as: 'classes'
});
Query and Response
const subjects = await dbClass.getSubjects(); // dbClass is a Class model instance
// Response
[
{
"id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
"name": "Mathematics",
"code": "MATHS",
"summary": "Mathematics for class 1",
"ClassSubject": {
"class_id": "637afc7b-40f6-478e-b35e-859ca462e2e7",
"subject_id": "1b89d44c-2caa-452d-a1f8-7faa11970917"
}
}
]
Desired output
// Response
[
{
"id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
"name": "Mathematics",
"code": "MATHS",
"summary": "Mathematics for class 1"
}
]
I have tried passing options to the method as specified below but to no avail
const subjects = await dbClass.getSubjects({
attributes: { exclude: ['ClassSubject'] }
});
But it still doesn't work.
Try using the joinTableAttributes option and pass empty array to exclude everything in joint table.
const subjects = await dbClass.getSubjects({ joinTableAttributes: [] });

How to update the Strapi GraphQL cache, after creating new data?

How to update the cache, after creating new data?
Error message from Apollo
Store error: the application attempted to write an object with no provided id but the store already contains an id of UsersPermissionsUser:1 for this object. The selectionSet that was trying to be written is:
{
"kind": "Field",
"name": { "kind": "Name", "value": "user" },
"arguments": [],
"directives": [],
"selectionSet": {
"kind": "SelectionSet",
"selections": [
{ "kind": "Field", "name": { "kind": "Name", "value": "username" }, "arguments": [], "directives": [] },
{ "kind": "Field", "name": { "kind": "Name", "value": "__typename" } }
]
}
}
Nativescript-vue Front-end Details
1- Watch Book Mobile app in action on YouTube: https://youtu.be/sBM-ErjXWuw
2- Watch Question video for details on YouTube: https://youtu.be/wqvrcBRQpZg
{N}-vue AddBook.vue file
apolloClient
.mutate({
// Query
mutation: mutations.CREATE_BOOK,
// Parameters
variables: {
name: this.book.name,
year: this.book.year,
},
// HOW TO UPDATE
update: (store, { data }) => {
console.log("data ::::>> ", data.createBook.book);
const bookQuery = {
query: queries.ALL_BOOKS,
};
// TypeScript detail: instead of creating an interface
// I used any type access books property without compile errors.
const bookData:any = store.readQuery(bookQuery);
console.log('bookData :>> ', bookData);
// I pin-pointed data objects
// Instead of push(createBook) I've pushed data.createBook.book
bookData.books.push(data.createBook.book);
store.writeQuery({ ...bookQuery, data: bookData })
},
})
.then((data) => {
// I can even see ID in Result
console.log("new data.data id ::::: :>> ", data.data.createBook.book.id);
this.$navigateTo(App);
})
.catch((error) => {
// Error
console.error(error);
});
What are these "Book:9": { lines in the cache?
console.log store turns out:
"Book:9": {
"id": "9",
"name": "Hadi",
"year": "255",
"__typename": "Book"
},
"$ROOT_MUTATION.createBook({\"input\":{\"data\":{\"name\":\"Hadi\",\"year\":\"255\"}}})": {
You can see all front-end GitHub repo here
Download Android apk file
Our goal is to update the cache. Add Book Method is in here:
https://github.com/kaanguru/mutate-question/blob/c199f8dcc8e80e83abdbcde4811770b766befcb5/nativescript-vue/app/components/AddBook.vue#L39
Back-end details
However, this is a frontend question a running Strapi GraphQL Server is here: https://polar-badlands-01357.herokuapp.com/admin/
GraphQL Playground
USER: admin
PASSWORD: passw123
You can see GraphQL documentation
I have so much simple Strapi GrapQL Scheme:
If you want to test it using postman or insomnia you can use;
POST GraphQL Query URL: https://polar-badlands-01357.herokuapp.com/graphql
Bearer Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTkwODI3MzE0LCJleHAiOjE1OTM0MTkzMTR9.WIK-f4dkwVAyIlP20v1PFoflpwGmRYgRrsQiRFgGdqg
NOTE: Don't get confused with $navigateTo() it's just a custom method of nativescript-vue.
It turns out;
all code was correct accept bookData.push(createBook);
// HOW TO UPDATE
update: (store, { data }) => {
console.log("data ::::>> ", data.createBook.book);
const bookQuery = {
query: queries.ALL_BOOKS,
};
// TypeScript detail: instead of creating an interface
// I used any type access books property without compile errors.
const bookData:any = store.readQuery(bookQuery);
console.log('bookData :>> ', bookData);
// I pin-pointed data objects
// Instead of push(createBook) I've pushed data.createBook.book
bookData.books.push(data.createBook.book);
store.writeQuery({ ...bookQuery, data: bookData })
},
})
Typescipt was helping
The point is; I shouldn't trust TypeScript errors, or at least I should read more about what it really says.
Typescript just asked me to be more specific while saying: Property 'push' does not exist on type 'unknown'
TypeScript was trying to tell me I need to be more specific while calling ROOT_MUTATION data. It said: Cannot find name 'createBook' But again I ignored it.
Solution Github Branch
https://github.com/kaanguru/mutate-question/tree/solution
Sources
how to update cache
Create interface for object Typescript

Aurelia I18N: Scan html sources for new keys and update translation.json files

Is there any tool to scan aurelia project sources (html, js) files and create (update) keys in translation.json files?
Especially I want to collect keys from HTML files that use TBindingBehavior and TValueConverter translation style.
Disclaimer: The packages suggested, are developed by my employer company.
Following are main steps involved in this process.
Generating i18n keys for the html templates, using gulp-i18n-update-localization-ids
Extract keys and values to an external resource, using gulp-i18n-extract
Manually translate the values for different languages
Compile the translations to generate locale files for different language, using gulp-i18n-compile2
Following are the minimalistic gulp tasks
const gulp = require("gulp");
const path = require("path");
const updateLocalizationIds = require('gulp-i18n-update-localization-ids');
const i18nExtract = require('gulp-i18n-extract');
const i18nCompile = require('gulp-i18n-compile2');
const src = path.resolve(__dirname, "src"),
json = path.resolve(src, "*.r.json"),
html = path.resolve(src, "*.html"),
translations = path.resolve(__dirname, "translations/i18n.json"),
locales = path.resolve(__dirname, "locales"),
i18nGlobalPrefixes = new Map();
const generateI18nKeys = function () {
return gulp.src(html)
.pipe(updateLocalizationIds({
emit: 'onChangeOnly',
ignore: [{ content: v => v.startsWith('${') && v.endsWith('}') }],
idTemplate: updateLocalizationIds.prefixFilename(i18nGlobalPrefixes),
whitelist: [
{ tagName: 'h2' },
{
tagName: 'another-custom-el',
attrs: ['some-other-value1', 'some-other-value2']
}
]
}))
.pipe(gulp.dest(src));
}
const i18nExtractOptions = {
plugIns: [
new i18nExtract.html(),
new i18nExtract.json()
],
markUpdates: true,
defaultLanguages: ['de', "fr"] // add more language here as per your need
};
const extractI18n = function () {
return gulp.src([html, json])
.pipe(i18nExtract.extract(translations, i18nExtractOptions))
.pipe(gulp.dest("."));
}
const compileOptions = {
fileName: "translation.json",
defaultLanguage: "en"
};
const compileI18n = function () {
return gulp.src(translations)
.pipe(i18nCompile(compileOptions))
.pipe(gulp.dest(locales));
}
gulp.task("i18n", gulp.series(generateI18nKeys, extractI18n, compileI18n));
What's happening here?
Let us assume that you have all the html files under src directory. You can also have some plain json files under src that act as external resources. Though it is not really needed, in this example, I have used the extension *.r.json for that (r indicates resource).
The first task generateI18nKeys generates i18n keys for the html templates. For example, it transforms the following edit.html
...
<!--edit.html-->
<h2>some text</h2>
<another-custom-el some-other-value1="value1" some-other-value2="value2"></another-custom-el>
... to the following
<!--edit.html-->
<h2 t="edit.t0">some text</h2>
<another-custom-el some-other-value1="value1" some-other-value2="value2"
t="[some-other-value1]edit.t1;[some-other-value2]edit.t2"></another-custom-el>
Use the whitelist property in the config option for this task, to mark elements and attributes for the key generation target.
In the next step, the keys and the corresponding values are extracted to a json file which looks like as follows.
{
"edit": {
"content": {
"edit.t0": {
"content": "some text",
"lastModified": "2019-05-26T16:23:42.306Z",
"needsUpdate": true,
"translations": {
"de": {
"content": "",
"lastModified": ""
},
"fr": {
"content": "",
"lastModified": ""
}
}
},
"edit.t1": {
"content": "value1",
"lastModified": "2019-05-26T16:23:42.306Z",
"needsUpdate": true,
"translations": {
"de": {
"content": "",
"lastModified": ""
},
"fr": {
"content": "",
"lastModified": ""
}
}
},
"edit.t2": {
"content": "value2",
"lastModified": "2019-05-26T16:23:42.306Z",
"needsUpdate": true,
"translations": {
"de": {
"content": "",
"lastModified": ""
},
"fr": {
"content": "",
"lastModified": ""
}
}
}
},
"src": "src\\edit.html"
}
}
Note that empty contents are generated for the localeIds, specified in the task. You can manually change this file to add translations for every language, configured.
Lastly, the compileI18n task generates files for every language from the last json, that looks something like below.
{
"edit": {
"t0": "some text",
"t1": "value1",
"t2": "value2"
}
}
Note that this file can directly be consumed by the aurelia-i18n plugin. For more details check the package specific documentation.
Hope this helps.

oauth2orize redirect_uri issue

I'm attempting to customize the oauth2orize all-grants example for my use. I can run the all-grants as-is and everything works (as you would expect), but when I run my customized version, I always end up with this error:
Error: Unable to issue redirect for OAuth 2.0 transaction
at Object.response [as handle] (C:\Dev\Expy\api\node_modules\oauth2orize\lib\grant\code.js:122:41)
I've been digging into this a bit and it seems there is a property of the txn variable within that function that should be named redirectURI and should be populated with the redirect_uri from the query string of the initial request to the /dialog/authorize page. For some reason this doesn't happen on my example app. Is this caused by an express version difference? That is the biggest difference that I see between the example code and my customizations. The all-grants uses express 2.* and my app will use express 4.*.
If it isn't an express version issue, where should I start looking in my code for the issue?
For reference, this is what I see in my app for the txn object:
txn: {
"transactionID": "evlUd2q4",
"client": { ... },
"req": {
"type": "code",
"clientID": "5C3B4438-433F-11E5-A532-74653C701F13"
},
"user": { ... },
"res": {
"allow": true
}
}
and this is what I see in that same object with the example (note the presence of the redirectURI in req and in the txn itself):
txn: {
"transactionID": "EEcYp3Uj",
"client": { ... },
"redirectURI": "http://localhost:3000/api/userinfo",
"req": {
"type": "code",
"clientID": "abc123",
"redirectURI": "http://localhost:3000/api/userinfo"
},
"user": { ... },
"res": {
"allow": true
}
}