What is the proper way to set up API endpoints for usage with Keystone? - keystonejs

It's not clear in the docs how one would use existing Keystone models to expose API endpoints that return json within a Keystone.js app. I would simply like to be able expose REST API endpoints with Keystone and be able to use the Keystone CMS capabilities to manage content via interacting with those endpoints. Thanks!

Now that they've standardized the admin API I found that it's pretty trivial to use the same methods. For my read only APIs that are powering my react app I've done put something like this in my routes/index.js
router.get('/api/:list/:format(export.csv|export.json)',middleware.initList,require('keystone/admin/server/api/list/download'));
And I've made my own version of the admin initList middleware:
exports.initList = function(req, res, next) {
console.log('req.keystone', req.keystone);
req.keystone = keystone;
req.list = keystone.list(req.params.list);
if (!req.list) {
if (req.headers.accept === 'application/json') {
return res.status(404).json({ error: 'invalid list path' });
}
req.flash('error', 'List ' + req.params.list + ' could not be found.');
}
next();
};

You may consider using:
restful-keystone by #creynders, or
keystone-rest by #danielpquinn
I've never actually used either of these because I have my own implementation, which I will open source once Keystone implements it plugin architecture (see Keystone Issue #912: Proposed Keystone Package Architecture).
I suspect many other similar modules will start surfacing once Keystone is more "plugin friendly".

Related

Twitter API OAuth 403 Error - Authentication with unknown is forbidden

I signed up for the Twitter API yesterday and I've been trying to get it working using node.js and the twitter-api-v2 npm package. I am pretty sure I've used the correct configuration (0Auth 1), I've looked through the twitter developer portal and my read-write permissions are correct. Checked my keys about a dozen times. Checked the twitter-api-v2 documentation too. Anybody know what I might be missing here? and writing something like this:
const {TwitterApi} = require('twitter-api-v2');
const config = {
appKey: 'XXXXXXXXX',appSecret: 'XXXXXXXXX', accessToken: 'XXXXXXXXX',accessTokenSecret: 'XXXXXXXXX', }
// OAuth 1.0a (User context)
const userClient = new TwitterApi( config );
const rwClient = userClient.readWrite;
const tweet = async () => {
try { await rwClient.currentUserV2(); await rwClient.tweet('Testing the Twitter API') } catch (err){ console.error(err) } }
tweet()
Unfortunately, each time I try run this I get the following error:
*
'Authenticating with Unknown is forbidden for this endpoint.
Supported authentication types are [OAuth 1.0a User Context, OAuth 2.0
User Context].'
I am pretty sure I've used the correct configuration (0Auth 1), I've looked through the twitter developer portal and my read-write permissions are correct. Checked my keys about a dozen times. Checked the twitter-api-v2 documentation too. Anybody know what I might be missing here?

Enabling binary media types breaks Option POST call (CORS) in AWS Lambda

New to AWS..
We have a .NET Core Microservice running on a serverless aws instance as lambda functions.
Our Controller looks like this
[Route("api/[controller]")]
[ApiController]
public class SomeController : ControllerBase
{
[HttpGet()]
[Route("getsomedoc")]
public async Task<IActionResult> GetSomeDoc()
{
byte[] content;
//UI needs this to process the document
var contentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
contentDisposition.FileName = "File Name";
Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
return File(content, "application/octet-stream");
}
[HttpPost()]
[Route("somepost")]
public async Task<IActionResult> SomePost()
{
return null;
}
}
URL's
{{URL}}/getsomedoc
{{URL}}/somepost
We have enabled 'Binary Media Types' in AWS package settings to / for the getsomedoc to work otherwise it was returning the byte array back instead of the file.
But this is breaking our 'somepost' call when UI is accessing the API using
Method: OPTIONS & Access-Control-Request-Method as POST
When we remove the binary media type the 'somepost' starts working.
Looking for suggestions as why this might be happening? and what can we add/remove from gateway to get this fixed.
Well we ended up resolving this in a strange way.
Added two gateways for the lambda
- on one of them have binary enabled
- Disabled on the other one.
For
getsomedoc - Using the one where binary media types are enabled
postsomedoc - Using the other one
Wish there was a better way!!
I have found this same behavior with my API. While looking everywhere for some help, I found a few things that address the issue:
Basically, this bug report says the problem is having CORS enabled while also using the generic Binary Media Type "*/*". Apparently the OPTIONS method gets confused by this. They discuss this in terms of using Serverless, but it should apply to using the console or other ways of interacting with AWS.
They link to a possible solution: you can modify the Integration Response of the OPTIONS method - change the Mapping Template's Content-Type to an actual binary media type, like image/jpeg. They say this allows you to leave the binary media type in Settings as "*/*". This is a little hacky, but at least it is something.
There also was this alternate suggestion in the issues section of this GitHub repo that is a little less hacky. You can set the content handling parameter of the OPTIONS Integration Request to "CONVERT_TO_TEXT"... but you can only do this via CloudFormation or the CLI (not via the console). This is also the recommended solution by some AWS Technicians.
Another possible workaround is to setup a custom Lambda function to handle the OPTIONS request, this way the API gateway may have the "*/*" Binary Media Type.
Create a new lambda function for handling OPTIONS requests:
exports.handler = async (event) => {
const response = {
statusCode: 200,
headers:{
'access-control-allow-origin':'*',
'Access-Control-Allow-Headers': 'access-control-allow-origin, content-type, access-control-allow-methods',
'Access-Control-Allow-Methods':"GET,POST,PUT,DELETE,OPTIONS"
},
body: JSON.stringify("OK")
};
return response;
};
In your API Gateway OPTION method, change the integration type from Mock to Lambda Function.
Make sure to check 'Use Lambda proxy integration'
Select the correct region and point to the created Lambda Function
This way any OPTIONS request made from the browser will trigger the Lambda function and return the custom response.
Be aware this solution might involve costs.

Angularfire2 custom authentication

I creating a website which has register link multiple auth providers and custom token as well. I also using AngularFire2 to communicate between Angular2 and Firebase but seem it doesn't have method similar with Firebase, e.g:
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
ref.authWithCustomToken(AUTH_TOKEN, function(error, authData) {
Anyone can show up to me how can deal with issue?
To authenticate using a custom token, you can call AngularFire2's login method with the following configuration options:
angularFire.auth.login(AUTH_TOKEN, {
provider: AuthProviders.Custom,
method: AuthMethods.CustomToken
});
Internally, this will call Firebase's signInWithCustomToken method.

JWT authentication with gundb

Can i use JWT authentication with gundb? And if so, would it dramatically slow down my sync speed? I was going to try and implement a test using the tutorial here but wanted to see if there were any 'gotchas' I should be aware of.
The API has changed to use a middleware system. The SEA (Security, Encryption, Authorization) framework will be published to handle stuff like this. However, you can roll your own by doing something like this on the server:
Gun.on('opt', function(ctx){
if(ctx.once){ return }
ctx.on('in', function(msg){
var to = this.to;
// process message.
to.next(msg); // pass to next middleware
});
});
Registering the in listener via the opt hook lets this middleware become 1st in line (before even gun core), that way you can filter all inputs and reject them if necessary (by not calling to.next(msg)).
Likewise to add headers on the client you would want to register an out listener (similarly to how we did for the in) and modify the outgoing message to have msg.headers = {token: data} and then pass it forward to the next middleware layers (which will probably be websocket/transport hooks) by doing to.next(msg) as well. More docs to come on this as it stabilizes.
Old Answer:
A very late answer, sorry this was not addressed sooner:
The default websocket/ajax adapter allows you to update a headers property that gets passed on every networked message:
gun.opt({
headers: { token: JWT },
});
On the server you can then intercept and reject/authorize requests based on the token:
gun.wsp(server, function(req, res, next){
if('get' === req.method){
return next(req, res);
}
if('put' === req.method){
return res({body: {err: "Permission denied!"}});
}
});
The above example rejects all writes and authorizes all reads, but you would replace this logic with your own rules.

How to configure Stormpath as middleware in Sails.js

What is the best way to implement the following code in sails.js v0.10.5? Should I be handling this with a policy, and if so, how? The init() function required by Stormpath requires Express (app) as an argument. Currently, I am using the following code in sails.config.http.js as custom middleware.
customMiddleware: function(app) {
var stormpathMiddleware = require('express-stormpath').init(app, {
apiKeyFile: '',
application: '',
secretKey: ''
});
app.use(stormpathMiddleware);
}
Yes, this is the preferred way of enabling custom Express middleware with Sails if it does more than just handling a request (as in your case, where .init requires app). For simpler cases where you want to implement custom middleware that just handles requests, you can add the handler to sails.config.http.middleware and also add the handler name to the sails.config.http.middleware.order array. See the commented out defaults in config/http.js for an example using myRequestLogger.
Also note that the $custom key in the sails.config.http.middleware.order array indicates where the customMiddleware code will be executed, so you can change the order if necessary.