How can I access an environment var in other modules - node.js

I use the jsonwebtoken module to Encode and Decode JWTs.
The Secret-passphrase is being saved in a config.yml file, which is being loaded in my main index.js Javascript and stored into an app Environment var app.set('jwtToken', config.jwt.token).
How can I access this environment var in another module (for example the Auth-Route Module).
Can I pass it somehow to this file?
Many thanks

I think you will need access to your app instance to access the jwtToken var in app. Alternative for you would be to pass your jwtToken as an process environment variable via
JWT_TOKEN=xyz node server.js
Now you could access it via process.env.JWT_TOKEN

Related

How to access app.locals in other modules in NodeJS?

With my main server.js file, I exported my app variable:
//Assume there's other code in this file of course
var app = express();
app.locals.database = //here's my DB connection. This variable works perfectly within the server.js file!
module.exports = app;
I imported it into another module:
var app = require('../server');
But I cannot access the app.locals variables? I set a few of them within my server.js (such as database connection info) but I get this error:
TypeError: Cannot read property 'database' of undefined
when trying to read:
app.locals.database
What am I doing wrong?
NOTE: In my other module app is {}, but when I check it within the originating module it has tons of info.
As per docs Once set, the value of app.locals properties persist throughout the life of the application.
In your case, as you've exported app, it's perfectly fine to access this at file level (not sure the right term), where you've imported as app.locals.database (remember app is an object).
But if you want to access elsewhere where you've not imported, express makes it available to all middleware via req.app.locals. The docs clearly mentions Local variables are available in middleware via req.app.locals
Also checkout this SO question, it give you a nice insight on app.locals and req.locals

How to use environment variables secrets safely in production

I would like to use environment variables to securely hold secrets with pm2.
I have a reverse proxy to an express backed server that uses a database with a password each time it connects to preform a query.
I would like to access it normally from the program:
procsess.env.my_secret
but I'm assuming that simply setting the variable at run time like the following isn't safe:
MY_SECRET="secret password" pm2/node my_api_server.js
How should I set the secret password considering I'm using pm2 and I would like the variable to persist through restarts/crashes?
I should note that different environment handling and passing code to other developers through the VCN is less important to me.
Storing API keys or credentials using .env gets exposed to the client on Production!
By React docs -
WARNING: Do not store any secrets (such as private API keys) in your React app!
Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.
It's advised to store all env keys directly on the server and the server should be used as a mid point between the client and the API. This way the key is applied directly on the server and is not exposed in the front end. You can check out respective documentation on how to set up env variables on your particular server.
Front End Code
fetchData = () => {
fetch('/users', { method: 'POST', body: JSON.stringify(data) }
.then(res => res.json())
}
Server Code
app.post('/users', (req, res) => {
const API_KEY = process.env.API_KEY;
connection.query(`/apiPath/${API_KEY}`)
}
In past ReactJS projects with Express backends that need to connect to a database, I've used the dotenv package on NPM. Once added as a dependency to your project, you will create a hidden .env file in the root of your server filestructure.
In that .env file, you can create environment variables. These variables will need to be prefixed with REACT_APP like the following:
REACT_APP_DBURI=<conn string here>
REACT_APP_MAILGUN_API_KEY=<key string here>
REACT_APP_CAPTCHA_SECRET_KEY=<key string here>
You need to require the package as follows in your code:
require('dotenv').config();
You can reference them in your server.js (or whatever) code as:
process.env.REACT_APP_VARIABLE_NAME
This Medium article has a full explanation.
Hope this helps!

Questionings about keys and OAuth

I am building a node.js app (script?) that is using google-auth-library and there is something that I don't understand.
I have generated the JSON file containing my OAuth2 client id keys using Google Developers Console, and I am using it in my script the following way :
const keys = require('../client_secret.json');
const oAuth2Client = new OAuth2Client(
keys.web.client_id,
keys.web.client_secret,
keys.web.redirect_uris[0]
);
// Generate the url that will be used for the consent dialog.
const authorizeUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: [
'https://mail.google.com',
'https://www.googleapis.com/auth/drive'
]
});
Then, I am opening the consent dialog, and getting my token back, etc. My app has the will to be open source, so my question is: should I let my client_secret.json file in my repository so other users can use it using their Google account?
The client token must be kept secret: extract from Google documentation
After creating your credentials, download the client_secret.json file from the API Console. Securely store the file in a location that only your application can access.
Your application will remain open source as authentication is a service not source code.
To manage your secret, I would suggest you to use environment variables accessible via process.env.YOUR_VARIABLE.
It does exit packages that will make it easy to handle between you different environments, my favorite is dotenv. dotenv loads environment variables from a non required .env file. You would typically use it in your development environment, you must not commit it!
Dotenv do not require the presence of the .env file, and won't override an environment variable that is already set anyway. You will have to define the environment variables in production and test environment the way your prefer.
You can also see this article

Multiple instances of Node Webkit (nwjs) shares cookies

I have two nwjs apps running in different nwjs executables. But cookies for both app are stored in the same folder C:\Users\Nickname\AppData\Local\node-webkit. For example, I can access cookies of the second app from the first (!!!). It's confusing.
So, one app can stole cookies from another app just using code win.cookies.get()? How to store cookies for each app separately?
You need to run your app and change the data-path, if you don't want to access the running arguments, you can use child_process, for that, the main app will create new app that store the cookies in diferent folder.
var child_process = require('child_process')
var path = require('path');
var profilePath = path.join(gui.App.dataPath,Math.random());
var child = child_process.spawn(process.execPath, ["--data-path="+profilePath,"],{detached: true});
https://github.com/nwjs/nw.js/issues/3724
I recommend you to not use cookies for save app data. You can use files (fs module).
You can also try to encrypt your data.

How to access local ENV variables in angular js

Is it possible to access ENV variables from angularjs?
I've got an angular 1.2.8 app being compiled via Brunch.io
It's hosted as a basic node app on heroku. (I do compiling locally; then push)
I've read a few things about token replacement during the compile stage for ENV variables.
However I'd much rather be able to push up the code to several different servers and have it resolve the correct local settings using just the ENV variables.
Thanks!
You cannot get ENV variables on browser. You can send request to a rest service on your server, and get env on backend, then response back to client
Quick example: (Express.js)
app.get("/rest/getenv", function(req, res) {
var env = process.env.ENV_VARIABLE;
res.json({result: env});
});
Edit:
You need to protect this rest url with token like strings. Or else, anyone can reach that url and get your environment variable value. This can be security concern
There are multiple ways of doing it and as mentioned above you could simply make and API call, however that creates an unnecessary delay in your app.
I would recommend to inject your env variables into your angular constant service on your server. That probably sounds a bit confusing, but it's simpler than it sounds.
I have written a blog post comparing different ways of injecting env varialbes into angular and explaining why you should take this approach: https://medium.com/#kudresov/a-better-way-to-inject-environmental-variables-in-angular-d3b2d01a3c5e
Also I have created sample Node Angular project to show how it works: https://github.com/kudresov/angular-config-vars

Resources