Get JSON list of apps from Heroku account - node.js

Making a Node/Express app to be my portfolio.
Using this CLI command, I'm able to see a JSON list of my apps and their properties within the CLI itself: https://devcenter.heroku.com/articles/using-the-cli#app-commands
How can I use this CLI command to be able to use this data within backend node/express code?
My goal is to have Node collect data for all of my apps from Heroku and loop through them to display the title/description on a page with a link to the app.
I've installed the NPM package for Heroku, and so far all I've figured out how to do is get it to start a Heroku shell within my terminal when the Node instance is run, not how to actually return the information from Heroku into the app itself to be used to display on the page.

Alrighty! Figured out how to get it working with Axios!
Also had to use the Heroku CLI to generate an OAUTH token:
heroku authorizations:create
And then throw that into an Environment Variable process.env.HEROKU_TOKEN
async getLandingPage(req,res,next) {
try {
const projects = await axios.get('https://api.heroku.com/apps',{headers:
{
Accept: "application/vnd.heroku+json; version=3",
Authorization: `Bearer ${process.env.HEROKU_TOKEN}`
}
});
console.log(projects);
res.render('index', {projects, page:'home'});
} catch(err) {
console.log(err);
res.redirect('/');
}
}
Man, I feel really dumb that it took that long to figure it out. Hopefully I'll be smarter about it in the future.

Related

How to implement FCM with heroku backend app

I need to send FCM push notification from a chrome extension. I've implemented at the moment the chrome.gcm api that is the easiest way to get FCM working and I'm able to get a registration token and get incoming notifications sended from the FCM console.
Since I need to use the server key into the POST requests to the fcm endpoint to send messages, I want to setup a simple heroku backend as an alternative to cloud functions.
at the moment I have this POST request in my client code, but I'm using it only for dev the chrome extension
axios.post('https://fcm.googleapis.com/fcm/send', {
to: 'APA91bELmJY8xTU...',
notification: {
title: 'Test notification',
body: 'Some cool text payload'
}
}, {
headers: {
'Authorization': 'key=AAAA6C5BuxA:...',
'Content-Type': 'application/json'
}
}).then( (res) => {
console.log(res)
})
Into the production version I want to move this code to the heroku app.
Is possible to use firebase-functions npm package on heroku or I need to setup an express app with an endpoint?
I've found this buildpack but I'm not sure if it will give me the ability to write my heroku nodejs code like a cloud function
functions.https.onRequest( (req, res) => { ... })
Is possible to use firebase-functions npm package on heroku?
The firebase-functions package is the glue between Google Cloud Functions and your (server-side) Firebase code. There is no simple way to use it on a Heroku instance.
Setting up a custom Express endpoint sounds like the more idiomatic approach here.

How to delete user from Auth0 on Next.js?

I can login and logout users on Next.js after reading these resources amongst others:
The Ultimate Guide to Next.js Authentication with Auth0
#auth0/nextjs-auth0 library
API Call Example
SPA + API: Node.js Implementation for the API
But nowhere could I find out if I can delete users using the auth0/nextjs-auth0 library.
I also looked into the module's handlers here.
Am I right to think there is no way to delete a user using the #auth0/nextjs-auth0 library?
If yes, what is the most preferred way to delete a user? I'd like to allow users to click a button in the browser to delete themselves from Auth0.
At this point, I'm thinking of using node-auth0 library to do it following this solution:
management.users.delete({ id: USER_ID }, function (err) {
if (err) {
// Handle error.
}
// User deleted.
});
But it requires a node back end, which I sort of wanted to avoid. Even so, is this the best solution or are there better ones? The Auth0 ecosystem is quite sprawling.
Edit 27 Oct 2020: Will try using node-auth0 library in "serverless" function in Next.js to allow user to delete their account over the weekend. Secrets are hidden with Next's runtime configuration. If this is not the best way to do it, please let me know. Thanks.
I believe you mean logging out a user by "deleting a user". Because If you want to delete a user from the database, you have to have node server which handles the db connection. If you want to log out the user, in "pages/api/v1" create a logout.js. in next.js, serverless functions or api functions are written in "pages/api".
import auth0 from "/utils/auth0";
// auth0 file is where you set the configuration for the auth0.
export default async function logout(req,res) {
try {
await auth0.handleLogout(req, res);
} catch (error) {
console.error(error);
res.status(error.status || 400).end(error.message);
}
}

Invalid credentials problem when consumig tone analizer from a nodejs app

I'm trying to consume a tone analyzer service from a nodejs app. I get unauthorized access problem, but these credentials work fine when I use them in a curl.
Running locally, in my app.js file I've included the data of the tone analyzer as follows:
var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3');
var toneAnalyzer = new ToneAnalyzerV3({
version: '2017-09-21',
iam_apikey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
});
Then I've added this, so my app listens for post requestes in the /tone url:
app.post('/tone', function(req, res, next) {
var params = {'tone_input': req.body}
toneAnalyzer.tone(params, function(err, data) {
if (err) {
return next(err);
}
return res.json(data);
});
});
But when I call it I get "Unauthorized: Access is denied due to invalid credentials".
The thing is that these credentials work fine in curl:
curl -X POST -u "apikey:XXXXXXXXXXXXXXXXXXXXXXXXXXXXX" --header "Content-Type: application/json" --data-binary #tone.json "https://gateway-lon.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&sentences=false"
{"document_tone":{"tones":[{"score":0.6165,"tone_id":"sadness","tone_name":"Sadness"},{"score":0.829888,"tone_id":"analytical","tone_name":"Analytical"}]}}
The reason you are getting unauthorised errors when running locally is that your service is hosted in https://gateway-lon.watsonplatform.net. If you don't specify an endpoint / url in your ToneAnalyzerV3 constructor then the API / SDK defaults to Dallas. So although your credentials may be correct for London, they are not correct for Dallas.
When you deployed your app to the cloud (which I guess was to the London location), you probably bound the service into your application. This sets environment variables allowing the SDK to determine the endpoint.
You constructor should look like:
var toneAnalyzer = new ToneAnalyzerV3({
version: '2017-09-21',
iam_apikey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
url: 'https://gateway-lon.watsonplatform.net/tone-analyzer/api',
});
I don't see problem with code (also never used watson stuff), but you may check the following point :
How the request you really send is formated : Because I see that you send param that is not present in your curl request.
Is your function using POST aswell (you don't provide much detail on what the call to toneAnalyzer.tone does exactly) ? Maybe it's a conflict of headers or Content-Type.
Do you use a proxy (enterprise settings or stuff like that) ? If you do, you may check that node is correctly using it.
You should also provide a bit more details on what exactly your tone object do, and try to find where the call to the IBM API is done.

Shopify Script Tags Create method does not show response in a console

I am attempting to make a Shopify app using shopify-node-app.I have done all initial setup for making an app.I have done with setting-up App-Proxy.I have started with the Script Tag which is necessary part on making an app.I am using shopify-api-node to create ScriptTag create method and the code is below.
const registerScriptTags = function(shopDomain, accessToken, scriptTag) {
const shopName=shopDomain.replace('.myshopify.com','');
const shopify = new ShopifyAPIClient({ shopName: shopName, accessToken: accessToken });
console.log('scriptTag= ', scriptTag);
shopify.scriptTag.create({
event: 'onload',
src: 'http://yourjavascript.com/1448951127/scripttag.js'
})
.then(response => console.log(response))
.catch(err => console.error(err));
console.log('scriptTag= ', scriptTag);
}
I do not see any response , error , scriptTag in an console.
I need to Check whether I am calling this function passing the params. I am adding scriptTag as 3rd param but also hard-coding it in function.
What I needs to do here ?
1) Do I needs to hit any specific url to see the response?
2) Can anyone able to explain last two statement above with my same code ?
Thanks.
The above code was perfect.I have to stop and restart server app, unless you use nodemon which is not currently. Also I uninstall and reinstall app in demo store. Since afterAuth is called once after installation. So any code changes in afterAuth, registerWebhook, registerScriptTag will need uninstall and install.

POST request with updating json file using create-react-app

I'm making a project using create-react-app. There is a configured server and so on. I'm using react-router-dom for routing in my app. There is 'Comments' component. When it starts render itself it goes to my local json file and takes comments from there using ajax. When user clicks 'submit' It sends POST request with form's fields to the same json file. I have code for adding a new object to my json file. It should work when user in '/api/comments' route . This is the code for adding a new object to my json file (requires express):
`app.post('/api/comments', function(req, res) {
fs.readFile(COMMENTS_FILE, function(err, data) {
if (err) {
console.error(err);
process.exit(1);
}
var comments = JSON.parse(data);
var newComment = {
id: Date.now(),
author: req.body.author,
text: req.body.text,
};
comments.push(newComment);
fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null, 4),
function(err) {
if (err) {
console.error(err);
process.exit(1);
}
res.json(comments);
});
});
});`
But I don't know where I shoud put this code if I'm using 'create-react-app' and it uses it's own configured server (as far I know). Maybe there is a way to change server which 'create-react-app' uses and put there this code to handle this route? Or maybe there is a way to handle this route using 'react-router'?
If I understand your question correctly the code you have posted here is server side code. The app you have made using create-react-app is a front end application and therefore does not have any server side code. You could however host a second server that would expose the api routes you need and then call into that server using a http library like axios.
I'm using a create-react-app and express as my api server. Setting up express to run alongside webpack-dev-server is a supported feature of create-react-app.
I use npm-run-all to fire-up both the client and proxy express api server in my start-up script defined in package.json. Here is what I believe is all that I needed to do:
In my webpack.config.dev.json file I defined a proxy setting in the devServer json block. Specifically:
proxy: { "/api": "http://localhost:3001" },
In my package.json file I configured a start script that uses npm-run-all to fire up both the react-app and express simultaneously.
I use server.js to fire-up express; this is where I store the equivalent of the code you outlined in your question.

Resources