Load credential from environment varaible - node.js

I want to call some Fortify APIs using nodejs
But for that i need to give administrator credentials
How can i load the credentials from my environment variable?
Example:-
SSCURL = xyz
SSCUSERNAME=changeme
SSCPASSWORD=changeme

There is a system variable process.env, first example in node.js:
const SSCURL = process.env.SSCURL;
const SSCURSERNAME = porcess.env.SSCURSERNAME;
const SSCPASSWORD = process.env.SCCPASSWORD;
You can use this as normal constant afterwards...

Related

Dynamic requires in nodejs before module.exports

I have an app I'm working on that has active directory login and local login. When checking for permissions I want to allow permissions to either be set by AD group membership, or if not using AD then locally stored permissions in the database. As a result I have 2 different modules to handle permission checks. Is there a way to have a require at the top, before module.exports to be done dynamically through an if statement or something similar? I thought I could assign a process.env.isLocal and process from there but it doesn't seem to work I get an error that says Permissions is not defined
const moment = require('moment');
const AdminPortal = require('../models/adminportal');
if(process.env.isLocal) {
const Permissions = require('../models/localLogin/localPermissions');
} else {
const Permissions = require('../models/permissions');
}
const isAuthenticated = require("../config/middleware/isAuthenticated");
const config = require("../config/configFile.js").get(process.env.NODE_ENV.trim());
module.exports = function(app){
I suppose maybe I need to have both code sets in one file and then choose which one to use based on if its a local login or not, I was just hoping to keep them separated.
Your issue with the Permissions variable is that it's block scoped so it's only available inside the block in which you declare it. So, this:
if(process.env.isLocal) {
const Permissions = require('../models/localLogin/localPermissions');
} else {
const Permissions = require('../models/permissions');
}
Creates a Permissions variable that is only usable within the if/else block. If you want it to be available at a higher scope and use the same if/else construct, then you have to declare the variable at that higher scope which means you can't use const:
let Permissions;
if(process.env.isLocal) {
Permissions = require('../models/localLogin/localPermissions');
} else {
Permissions = require('../models/permissions');
}
// you can use Permissions here
FYI, this is a place where the ternary operator can be useful:
const Permissions = process.env.isLocal ?
require('../models/localLogin/localPermissions') :
require('../models/permissions');

Access string stored in secret manager from CDK

I am storing the Codestar connection string for Bitbucket in Secret manager. How can I retrieve it in the CDK app:
I am trying with:
// Get Bitbucket Connection String
const bitbucketConnectionString = Secret.fromSecretCompleteArn(this, "bitbucketConnectionString", "arn:aws:secretsmanager:us-west-2:1000000000:secret:BitbucketCloudConnection-abcdef0");
// SourceAction
const sourceAction = new BitBucketSourceAction({
actionName: 'BitbucketSource',
owner: 'abc',
repo: repoName,
output: sourceOutputArtifact,
connectionArn: bitbucketConnectionString,
})
bitbucketConnectionString is not a string though.
How do I access the secret value which is actually a connectionString stored in Secret Manager.
What is the right way to replace region and accountId with Pseudo variables in the connection string;
arn:aws:secretsmanager:us-west-2:1000000000:secret:BitbucketCloudConnection-abcdef0
The account and region reference can be set up on the basis of the environment variables you have. You should be able to use a this.account or this.region to reference the current stack/constructs environment details.

How set API KEY in Google Translate Node.js code

I'm trying to create a Node.js code that uses google translate api.
I got the code below from the google doc (https://cloud.google.com/translate/docs/translating-text)
But when I run it, it says "Error: The request is missing a valid API key."
I have the key, but i don't know how and where to set it.
async function translate() { // Imports the Google Cloud client library
const { Translate } = require('#google-cloud/translate');
// Creates a client
const translate = new Translate();
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
const text = 'Hello, world!';
const target = 'ru';
// Translates the text into the target language. "text" can be a string for
// translating a single piece of text, or an array of strings for translating
// multiple texts.
let [translations] = await translate.translate(text, target);
translations = Array.isArray(translations) ? translations : [translations];
console.log('Translations:');
translations.forEach((translation, i) => {
console.log(`${text[i]} => (${target}) ${translation}`);
});
}
translate()
This page on setting up authentication explains that you need to download a credentials file from the create service account key page. This can then be added to your path (.bashrc) as follows:
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
Alternately, you could add the line above to a .env file on your project root and source it when you are running the application:
. ./.env
npm start
or
sh -ac '. ./.env; npm start'
Checkout this Google Authentication Page to add the key
In the GCP Console, go to the Create service account key page.
From the Service account list, select New service account.
In the Service account name field, enter a name.
From the Role list, select Project > Owner. Click
Create. A JSON file that contains your key downloads to your computer.
and
export GOOGLE_APPLICATION_CREDENTIALS="[PATH to key downloaded]"
create api-key see documentation create api key doc
use it like:
import { v2 } from '#google-cloud/translate';
const translateClint = new v2.Translate({
projectId:'your-projectId-here',
key: 'your-api-key-here',
});
I don't check it for v3, but I see the same interface:
new v3.TranslationServiceClient({
key:"may be works",
projectId:"may be works"
})
Try this... no environment variables AND please... add this file to your .gitignore
import * as credentials from 'credentials.json';
...
const {Translate} = require('#google-cloud/translate').v2;
const translationApi = new Translate({
projectId:'your-project-id',
credentials:credentials
});

Pulumi: Manipulate connection string during deployment

I'm using Pulumi to deploy several Azure ressources, which works fine.
I'm deploying a TopicAuthorizationRule and I need to manipulate the connection string in order to have it working with an Azure Function Trigger.
const myPolicy = new azure.eventhub.TopicAuthorizationRule(...);
const myPolicyConnectionString = myPolicy.primaryConnectionString.get();
const goodConnectionString = myPolicyConnectionString .substr(0, myPolicyConnectionString .lastIndexOf(';EntityPath'));
And I have this error: Cannot call '.get' during update or preview
How can I do this string manipulation in order to set it in AppSettings?
Connection string value is unknown yet at the time of preview, so you can't use it directly. It's contained in a value of type Output<T> which is going to be resolved at update time.
You can transform the values of Output<T> by using apply function:
const goodConnectionString =
myPolicy.primaryConnectionString.apply(s => s.substr(0, s.lastIndexOf(';EntityPath'));
which can then be used to assign AppSettings (without calling get explicitly).

Environment variable not accepting for azure

I have defined environment variables for azure in terminal like as below,
SET AZURE_STORAGE_ACCOUNT=accountname
SET SAS_TOKEN="sr=c&sp=rwl&sig=signatureKey%3D&sv=2017-04-17&se=2018-03-10"
After defining the varibale, i have called these variables inside the azure blob storage function like,
AZURE_STORAGE_ACCOUNT= process.env.AZURE_STORAGE_ACCOUNT;
SAS_TOKEN = process.env.SAS_TOKEN;
var blobUri = "http://"+AZURE_STORAGE_ACCOUNT+".blob.core.windows.net";
var blobService = azureStorage.createBlobServiceWithSas(blobUri, SAS_TOKEN).withFilter(new azureStorage.ExponentialRetryPolicyFilter());
blobService.createBlockBlobFromLocalFile('mycontainer', 'sparks-events-data', fileToWrite, function(error, result, response) {
if (!error) {
console.log("upload successful..");
} else {
console.log(error);
}});
When i run above file i am getting error like
StorageError: Server failed to authenticate the request. Make sure
the value of Authorization header is formed correctly including the
signature.
But when i call the SAS token directly inside the code it works fine. I am using like this
var sasKey = "sr=c&sp=rwl&sig=signatureKey%3D&sv=2017-04-17&se=2018-03-10";
var blobService = azureStorage.createBlobServiceWithSas(blobUri, sasKey ).withFilter(new azureStorage.ExponentialRetryPolicyFilter());
it works fine for me. I need to set the SAS token as environment variable. Here what i am missing. Please someone suggest me a solution for this.
Thanks in Advance,
export those env vars instead. Exporting a variable causes the variable to be inherited by subsequent processes started in that shell.
export SAS_TOKEN="..."
You may want to take a look at this npm package before rolling your own env var secrets handling logic. We already cracked this, as a people —
https://github.com/motdotla/dotenv
In Windowsland, just use set, but make sure your Node process starts in the same terminal window:
C:\lab> set KEY="secret"
C:\lab> type app.js
let key = process.env.KEY;
console.log('KEY is ' + key);
C:\lab> node app.js
KEY is "secret"
Watch out for those quotes!

Resources