express-stormpath request.uri is undefined - stormpath

I'm trying to run express-stormpath on an aws linux instance that is successfully serving. I've double and tripled checked my keys and app hrefs and assured they were connected to applications. I've gone to a fresh vm and used the simplest service to ensure something wasn't awry in the VM where I am successfully serving a sailsjs app.
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
var stormpathInit = function(req,res,next) {
stormpath.init(app, {
apiKey: {
id:'##########',
secret: '############',
},
secretKey: 'theLongRoadToNowhere',
application: 'https://api.stormpath.com/v1/applications/###',
website: true,
api: true
});
next();
};
app.use(stormpathInit);
app.get('/', function (req, res) {
res.send('Login');
});
/* and this failed as well with the same output only on server startup
app.use(stormpath.init(app, {
apiKey: {
id:'4SL89BZ47ALZX6T9W7S4NPUXS',
secret: 's0dA33RPTAqcDAcdbwj6q9i0qDDEr0XyHhsBmjF34SY',
},
secretKey: 'theLongRoadToFreedomWillPayDividends',
application: 'https://api.stormpath.com/v1/applications/1wShCspJ1NFnT1N1UM1laJ',
website: true,
api: true
}));
*/
app.listen(1337);
///////////////////////
The error output:
req.uri = undefined
/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/RequestExecutor.js:70
throw new Error('request.uri field is required.');
^
Error: request.uri field is required.
at RequestExecutor.executeRequest [as execute] (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/RequestExecutor.js:70:13)
at doRequest (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/DataStore.js:277:27)
at onCacheResult (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/DataStore.js:301:5)
at Array.<anonymous> (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/cache/Cache.js:54:14)
at DisabledCache.get.DisabledCache.set.DisabledCache.delete.DisabledCache.clear.DisabledCache.size (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/cache/DisabledCache.js:11:62)
at Cache.get (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/cache/Cache.js:52:14)
at CacheHandler.getCachedResource [as get] (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/cache/CacheHandler.js:91:51)
at Object.executeRequest [as exec] (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/DataStore.js:294:22)
at DataStore.getResource (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/ds/DataStore.js:122:16)
at Client.getResource (/var/www/stormpath/node_modules/express-stormpath/node_modules/stormpath/lib/Client.js:313:38)
Any guidance is appreciated...

Unfortunately the answer from photon did not work for me, but after communicating with Stormpath support (which was very helpful) the following fixed my problem:
Set environment variable STORMPATH_APPLICATION_HREF by running this in the shell:
export STORMPATH_APPLICATION_HREF=<YourAppsHREF>
Hopefully this will work for others as well.
The problem seems to be a small typo in the stormpath documentation. They currently instruct you to set an environment variable called STORMPATH_CLIENT_APPLICATION_HREF. This is incorrect, it should be STORMPATH_APPLICATION_HREF as shown above.

I had the same problem and after looking at the current default options for the Stormpath middleware, changing the following line resolved my issue.
Before
application: 'https://api.stormpath.com/v1/applications/1wShCspJ1NFnT1N1UM1laJ'
After
application: {
href: 'https://api.stormpath.com/v1/applications/1wShCspJ1NFnT1N1UM1laJ'
}

Related

Missing jwtSecret. Please, set configuration variable "jwtSecret" in Strapi

Strapi Error
I am trying to deploy a Strapi app to Heroku. I have set APP_KEYS and JWT_SECRET config vars in Heroku. I have also added this code to plugins.js as stated in this question. But I am still getting this error (see image). Can anyone help with this?
const crypto = require("crypto");
module.exports = ({ env }) => ({
"users-permissions": {
config: {
jwtSecret: env("JWT_SECRET") || crypto.randomBytes(16).toString("base64"),
},
},
});

Svelte Proxy with rollup?

I'm trying to proxy requests from a Svelte app to a different port, where my backend API runs. I want to use a rollup proxy in the dev environment.
I read the alternative of using a webpack proxy here, but I want to give rollup proxy a try.
This is not an issue in production.
As suggested, I tried configuring rollup-plugin-dev However, whenever I make a request to weatherforecast I still get an CORS error. Below is my configuration and the call:
import dev from 'rollup-plugin-dev'
// other code
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
dev({
proxy: [{ from: '/weatherforecast', to: 'https://localhost:7262' }]
}),
// other code
];
and App.svelte looks like this:
<script>
import { onMount } from "svelte";
const endpoint = "/weatherforecast";
onMount(async function () {
try {
const response = await fetch(endpoint);
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
});
</script>
Any help in solving this issue is appreciated.
What's happening is the proxy is passing through the CORS headers un-touched, so you're basically interacting with the API as though the proxy wasn't even there, with respect to CORS.
I'll note that you can get around this in dev, but keep in mind this problem will come up in production too, so you may just need to rethink how you're getting this data.
For development though, you can use something like cors-anywhere. This is a middleware that you can run through your dev server that can rewrite the headers for you.
To configure rollup-proxy on dev environment, you need to remove the call to the serve method, call the dev method and move the proxy calls inside the dev method:
import dev from 'rollup-plugin-dev'
// other code
export default {
input: 'src/main.js',
output: {
// other code
commonjs(),
// enable the rollup-plugin-dev proxy
// call `npm run start` to start the server
// still supports hot reloading
!production && dev({
dirs: ['public'],
spa: 'public/index.html',
port: 5000,
proxy: [
{ from: '/weatherforecast', to: 'https://localhost:7262/weatherforecast' },
],
}),
// line below is no longer required
// !production && serve(),
// other code
];

NextJS - how to configure proxy to log api requests and responses?

I am having an issue with the Cloudinary Node SDK where the Admin Resources endpoint is occasionally throwing a 302 error. Their support suggested that I proxy the request so that I can log the response between my api and their SDK and ultimately get a better idea of what might be causing the problem (in the end they're hoping to see the Location headers that are in the Response).
One of their suggestions was to use Charles Proxy, however I'm very new to how this works and am unable to figure it out. I've read through the Charles docs and spent a full day googling, but I can't find any info related to proxying between the NextJS API and Cloudinary SDK specifically.
How do I go about setting up Charles Proxy so that I can see the request and response in this way? Is there another way that I don't know of that would work instead? Since I'm using the newest version of NextJS v12, could I use the new _middleware option instead? In a later suggestion, their Support made this comment too:
if you can't proxy requests to localhost, you may be able to use a local DNS server or a local override so you can access your local IP using a different hostname (e.g. using /etc/hosts on a unix environment, or C:\Windows\System32\Drivers\etc\hosts on a windows PC) and have that proxied - that said, there's probably an easier way using a Node project or adjusting the settings of the Node server.
but I have no idea where to begin with this either.
Here is the api code I have:
pages/api/auth/images.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import cloudinary from 'cloudinary';
require('dotenv').config();
export default async function handler(_: NextApiRequest, res: NextApiResponse) {
cloudinary.v2.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
secure: true,
});
try {
// fetch cloudinary auth images
const response = await cloudinary.v2.api.resources({
type: 'upload',
prefix: 'my_app/auth_pages',
max_results: 20,
});
// fetch random image
const randImage =
response.resources[~~(response?.resources?.length * Math.random())];
// return image
return res.status(200).json({ image: randImage });
} catch (error) {
console.dir({ error }, { colors: true, depth: null });
return res.status(500).json({ error });
}
}
Note: I'm on a Mac.
Try the following:
export default async function handler(_: NextApiRequest, res: NextApiResponse) {
cloudinary.v2.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
api_proxy: 'http://<local_ip>:<charles_port>', //change accordingly
secure: true,
});
To get the port number, In Charles Proxy go to Proxy > Proxy Settings.

Using Express Router to proxy non-CORS content doubles request path

There must be something obvious I am missing. I have an external record like https/udspace.udel.edu/rest/handle/19716/28599 that is not set up for CORS, but I would like to get access to it in my application. In the past, I have set up a server to simply GET the resource and redeliver it for my application. However, I read about Node http-proxy-middleware and thought I'd try out a more direct proxy.
First, I could not use the target in the createProxyMiddleware() constructor because I wanted to send in the hostname and path of the desired resource like, perhaps, http://example.com/https/udspace.udel.edu/rest/handle/19716/28599 to get the resource above.
Relevant Code (index.js)
const express = require('express')
const { createProxyMiddleware } = require('http-proxy-middleware')
const app = express()
app.get('/info', (req, res, next) => {
res.send('Proxy is up.');
})
// Proxy endpoint
app.use('/https', createProxyMiddleware({
target: "incoming",
router: req => {
const protocol = 'https'
const hostname = req.path.split("/https/")[1].split("/")[0]
const path = req.path.split(hostname)[1]
console.log(`returning: ${protocol}, ${hostname}, ${path}`)
return `${protocol}://${hostname}/${path}`
},
changeOrigin: true
}))
app.listen(PORT, HOST, () => {
console.log(`Starting Proxy at ${HOST}:${PORT}`);
})
I was getting a 404 from the DSpace server without other information, so I knew that the request was going through, but transformed incorrectly. I tried again with an item in an S3 bucket, since AWS gives better errors and saw that my path was being duplicated:
404 Not Found
Code: NoSuchKey
Message: The specified key does not exist.
Key: api/cookbook/recipe/0001-mvm-image/manifest.json/https/iiif.io/api/cookbook/recipe/0001-mvm-image/manifest.json
What dumb thing am I doing wrong? Is this not what this proxy is for and I need to do something else?

Stripe Payments with parse server cloud code

I have this code included in my main.js:
var stripe = require("/cloud/stripe.js")("sk_test_*********");
//create customer
Parse.Cloud.define('createCustomer', function (req, res) {
stripe.customers.create({
description: req.params.fullName,
source: req.params.token
//email: req.params.email
}, function (err, customer) {
// asynchronously called
res.error("someting went wrong with creating a customer");
});
});
After pushing this code to my Heroku server the logs indicate that: Error: Cannot find module '/cloud/stripe.js'
I have also tried var stripe = require("stripe")("sk_test_*********"); but this returns the same error. Whenever I try add this new module to my server the whole server becomes dysfunctional. What workarounds are there to this? Thanks
Have you added Stripe to the requirements of your package.json file for your node project? If so, you should be able to reference it using the term require('stripe') as opposed to what you're doing.
I'll tell you what worked for me, I racked my brain on this for a day. Instead of using Cloud Code to make a charge, create a route on index.js. Something like this in index.js
var stripe = require('stripe')('sk_test_****');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: false
}));
app.post('/charge', function(req, res){
var token = req.body.token;
var amount = req.body.amount;
stripe.charges.create({
amount: amount,
currency: 'usd',
source: token,
}, function(err, charge){
if(err)
// Error check
else
res.send('Payment successful!');
}
});
I call this using jQuery post but you could also use a form.

Resources