How to trigger a service in App Engine on Firebase data change - node.js

I have created an app engine basic server and connected it for Firebase:
// server.js
// Express packages
const express = require('express');
const app = express();
const path = require(`path`);
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
// Firebase packages
var firebase = require('firebase');
var firebaseConfig = {...};
var fire = firebase.initializeApp(firebaseConfig);
var ref = firebase.database().ref('test');
ref.on('child_added', readMessage);
function readMessage(data) {
console.log('data', data)
};
// Route index
app.get('/', (req, res) => {
res.send('Hello from App Engine!');
});
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
My idea was to trigger this service (not sure which route, but I guess it is open?) when a child is added to the node test on Firebase.
To give a bit of background information, I am basically planning to create a peer connection using webrtc and then parse the video on this nodejs server. I use Firebase for signallin by sending the webrtc information to the node test and then the server can read and process this once there is a change.
I do not understand however how to trigger this service when a child is added (thus when I send some meta data to the node test in Firebase). How do I structure my nodejs code to handle this? Or should this be done differently?

Using cloud function with Firebase Realtime Database triggers, we can call the app engine endpoint using http or Cloud Tasks.

Related

Routes are not working in cPanel deployed json-server

I recently tried to deploy json-server to my interserver's shared hosting plan via cPanel.
I uploaded the app and configured a Node.js app and I'm able to access the endpoint via 'https://soltonbaev.com/json-server/api/contacts' however the jsonServer.rewriter() is not rewriting the "/api/" route to the "/".
In addition I cannot access the individual object via it's id, like for instance "https://soltonbaev.com/json-server/api/contacts/1". Server returns 404.
So clearly, JSON server is not picking up the routes when it is supposed to.
Here is the content of my server.js file
require('dotenv').config();
const jsonServer = require('json-server');
const cors = require('cors');
const server = jsonServer.create();
const router = jsonServer.router('database.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3000;
server.use(
jsonServer.rewriter({
'/api/*': '/$1',
})
);
server.use(cors({origin: process.env.REMOTE_CLIENT_APP, credentials: true}));
server.use(middlewares);
server.use(router);
server.listen(port, () => {
console.log(
`🚀 JSON Server is running on ${process.env.REMOTE_CLIENT_APP}:${port}}`
);
});

Device login detection with node.js and react.js

I need to restrict users to login from multiple devices. I'm using react.js at the frontend and node.js as the backend. Which is the most reasonable way to handle this task?
I can not imagine how you can identify user browser 100 %. Cookies are browser based,so that could not solve the problem. Try Matteo Collina's pino logger, I think that it has many options.so you can choose most suitable for your task.
For example,this simple code
const express = require('express');
const pino = require('pino');
const expressPino = require('express-pino-logger');
const logger = pino({ level: process.env.LOG_LEVEL || 'info' });
const expressLogger = expressPino({ logger });
const PORT = process.env.PORT || 3000;
const app = express();
app.use(expressLogger);
app.get('/', (req, res) => {
logger.debug('Calling res.send');
res.send('Hello World');
});
app.listen(PORT, () => {
logger.info('Server running on port %d', PORT);
});
would show
"level":30,"time":1613817528986,"pid":17345,"hostname":"jholmes","msg":"Server running on port 3000"
You can pick IP,but would dynamic Id's you can not point pot to single user.
React also has plenty libraries for auth(ajv).

How to setup a viberbot webhook for heroku deployed nodejs bot?

I have problem of setting up web hook for my chat bot i made using nodejs. Which is deployed on Heroku.
The app uses the following architecture :
const http = require('http');
const port = process.env.PORT || 8080;
// Viber will push messages sent to this URL. Web server should be internet-facing.
const webhookUrl = process.env.WEBHOOK_URL;
// I have used this as Heroku app name with https://dyno-125-92.herokuapp.com
http.createServer(ot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
Please, help me to setup a webhook using express or anything that can work with my bot?
I'm stuck.
Try this:
const express = require('express');
const app = express();
// contains relative URL path, like: "/viber/webhook"
const webhookUrl = process.env.WEBHOOK_URL;
// ...
app.use(webhookUrl, bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${process.env.EXPOSE_URL}${webhookUrl}`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
If it doesn't work, use - full code example to check.

How to ensure requests to my servers functions only by a single origin / UI?

I have a node.js server that has HTTP CRUD functions to my mongoDB.
And an Android application that sends requests though those functions.
I would like to ensure that my server will answer requests from specific origins.
For example: only answer requests from the android app, or my pc postman's requests.
How can I ensure that no one else sending requests using the same urls and ports will get answered?
This is my server.js file:
const express = require('express');
const MongoClient = require('mongodb');
const bodyParser = require('body-parser');
var db = require('./config/db');
var app = express();
const port = 8000;
app.use(bodyParser.json());
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err)
db = database.db("getremp")
require('./app/routes')(app, db);
app.listen(process.env.PORT || port, () => {
console.log("Express server listening on port %d in %s mode - We Are lIVE!",app.settings.env.port, app.settings.env);
});
})
and my index.js:
const noteRoutes = require('./note_routes');
module.exports = function (app, db) {
noteRoutes(app, db);
};
You can control this with :
Send a specific header with your datas containing a secret key, then control the header in your node app How to check headers in nodejs?
Use HMAC in order to authenticate the user and control the integrity of datas : Node Hmac Authentication
But you've to remember that all traffic going out from an mobile app can be intercept (with Fiddler for example). Never use a static (non-dynamic) value to ensure authentication

Node.js console.log not logging in terminal

I have a simple app where I'm trying to log to the console (terminal where I started Node, not the the browser console). Express seems to execute the route since I can see the response in my browser.
Also the logging in the app.listen(..) seems to work, but I don't see any logs afterwards.
'use strict';
// 3rd-party dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const dbSetup = require('./db-setup');
// Application config
const LOCAL_APP_PORT = 8080;
const PUBLIC_APP_PORT = process.env.PUBLIC_APP_PORT || LOCAL_APP_PORT;
global.dbType = process.env.DB_TYPE;
// Sanity check for debugging
console.log("local app port:", LOCAL_APP_PORT);
console.log("public app port:", PUBLIC_APP_PORT);
console.log("db type:", global.dbType);
// Database setup for either MongoDB or Postgres
dbSetup(global.dbType);
// Express middleware
app.use(bodyParser.json()); // for parsing application/json
// Import routes
//const index = require('./routes/index');
//const owner = require('./routes/owner');
//const shop = require('./routes/shop');
//const product = require('./routes/product');
// Set up express routes
app.use('/',(req,res,next) => {
console.log("This is not showing on the terminal.");
res.send("This is sent to the browser");
next();
})
//app.use('/owner', owner);
//app.use('/shop', shop);
//app.use('/product', product);
app.listen(LOCAL_APP_PORT, () => {
console.log('App started ...');
});
EDIT: Solved. Problem was my app was basically available on two ports at the same time. One the the public port however it was not showing any logs...
Terminal screenshot

Resources