simple-git: SSH authentication example using simple-git - javascript

How to clone a repository with SSH using simple-git?
I'm trying to clone using this code
const git: SimpleGit = simpleGit();
const sshUri = 'git#..........'
const localPath = '/usr/workspace';
git
.clone(
sshUri,
localPath
).then((data) => {
console.log('success');
}).catch((err) => {
console.log(err);
});
But I am getting an exception
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

If your git repo is private, you will need to generate SSH key and add this key to your GIT account.
To generate SSH Key:
https://docs.github.com/en/authentication/connecting-to-github-with-ssh
Add your SSH to git account:
You can find it here
https://github.com/settings/keys
Code example
private async cloneRepo() {
const gitSSH = 'FILL YOUR SSH GIT ADDRESS';
const sourceDir = path.resolve(`${os.tmpdir()}/${this.projectKey}`);
const sshKnownHosts = path.resolve(`${process.cwd()}/settings/ssh/known_hosts`)
const sshKey = path.resolve(`${process.cwd()}/settings/ssh/id_ed25519`)
const GIT_SSH_COMMAND = `ssh -o UserKnownHostsFile=${sshKnownHosts} -o StrictHostKeyChecking=no -i ${sshKey}`;
console.log(sourceDir);
const git: SimpleGit = simpleGit()
.env('GIT_SSH_COMMAND', GIT_SSH_COMMAND)
.clean(CleanOptions.FORCE);
await git.clone(gitSSH, sourceDir, ['-b', 'YOUR-BRANCH-NAME', '--single-branch'])
.then(() => console.log('finished'))
.catch((err) => console.error('failed: ', err));
}

Related

How to log into gcloud using discord without service accounts/how to enter gcloud auth code without terminal

so im currently developing a software which hosts your vps automaticly and bypasses the gcloud free tier 50 hours limit. so anyways on the login part, it executes the command "gcloud auth login --no-launch-browser" and sends the link to a discord channel, but then, it requires a code, ive already setted up a message listner which executes after 7 seconds of sending the gcloud auth link.
so yeah how do I input the code, any help would be apreciated
heres my full code
const Discord = require("discord.js")
const { Client, Intents } = require('discord.js');
const { token, channelId } = require("./config.json");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
var embed = new Discord.MessageEmbed()
client.on("ready", () => {
console.log(`(login bot) Logged in as ${client.user.tag}!`)
})
const { spawn } = require( 'child_process' );
client.on("message", msg => {
if (msg.content.startsWith("WARNING: The --[no-]launch-browser flags are deprecated and will be removed in future updates. Use --no-browser to replace --no-launch-browser.")){
msg.delete();
}
if(msg.content === '!ping2'){
embed = embed
.setDescription(`pong!2`)
.setColor("BLUE")
return msg.channel.send({embeds: [embed]})
}
if(msg.content.toLowerCase() === '!login'){
//collector
//collectors const
let filter = (m) => m.author.id === msg.author.id
let limit = 60000 * 15 //minute
const collected = {filter, time: limit, max: 1, errors: ['time']};
//collectors const
//aray
var colArray = {}
//collectorThing
const collector = async function() {
let genderEmbed = await msg.channel.send('Please enter in the code that you recived')
msg.channel
.awaitMessages(collected)
.then((collected) => {
let code = collected.first()
colArray.code = code
const codeCollected = spawn( 'echo', [ colArray.code ] );
codeCollected.stdout.on( 'data', ( data ) => {
msg.channel.send(data.toString())
} )
codeCollected.stderr.on( 'data', ( data ) => {
msg.channel.send(data.toString())
} )
codeCollected.on( 'out', ( code ) => {
msg.channel.send(code.toString())
} )
}
)
.catch(collected => {
console.log(collected)
})
}
//collectorEnd
'use strict';
const login = async function() {
const login = spawn( 'gcloud', [ 'auth', 'login', '--no-launch-browser' ] );
login.stderr.on( 'data', ( data ) => {
msg.channel.send(data.toString())
} )
}
login()
setTimeout(collector, 7000);
}
}
)
client.login(token)
edit: also heres what it does currently
As mentioned in the thread :
To authenticate a fresh gcloud when GOOGLE_APPLICATION_CREDENTIALS
points to a file with user credentials rather than service account
credentials.
cat ${GOOGLE_APPLICATION_CREDENTIALS}
{
"client_id": "aaa",
"client_secret": "bbb",
"refresh_token": "ccc",
"type": "authorized_user"
}
gcloud config set auth/client_id aaa
gcloud config set auth/client_secret bbb
cloud auth activate-refresh-token user ccc
This uses the undocumented auth activate-refresh-token subcommand -
which isn't ideal - but it does work. Paired with gcloud auth
activate-service-account --key-file=credentials.json, this makes it
possible to initialize gcloud regardless of the credential type
available at $GOOGLE_APPLICATION_CREDENTIALS.
You can also refer to the thread :
For automated processes, a service account is the recommended way.
You can use the google-oauth library for this. You can generate
an access token like this
# With default credential (your user account or the Google Cloud Component service account.
# Or with the service account key file defined in the GOOGLE_APPLICATION_CREDENTIALS env var -> for platform outside GCP)
credentials, project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
# With service account key file (not recommended)
# credentials = service_account.Credentials.from_service_account_file('service-account.json',
# scopes=["https://www.googleapis.com/auth/cloud-platform"])
from google.auth.transport import requests
credentials.refresh(requests.Request())
print(credentials.token)
For more information, you can refer to the thread where local development without using a service account has been discussed.

How to manually create Git blob object and then read the contents using node.js like in the ProGit chapter on Git internals?

I read the chapter called "Git Internals - Git Objects" in the ProGit book.
The final part, entitled "Object Storage", shows you how you can manually create a Git blob object, and then read the contents of that object. This is shown using Ruby.
I tried to do the same thing in node.
First I created a directory called my-git-tests, and in it I ran git init. I created one javascript file called s.js analogous to the commands in the chapter with Ruby, and here it is:
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const zlib = require('zlib');
const content = 'what is up, doc?';
const header = `blob ${Buffer.from(content).length}\0`;
console.log('Header', header.length, header);
const store = header + content;
console.log('Store is ', store);
const hash = crypto.createHash('sha1');
const sha1 = hash.update(store, 'utf-8').digest('hex');
console.log('SHA-1 is ', sha1);
const objectPath = `.git/objects/${sha1.substr(0, 2)}/${sha1.substr(2)}`;
console.log('Path is ', objectPath);
fs.mkdirSync(path.dirname(objectPath));
let zlibCompress;
zlib.deflate(store, (err, buffer) => {
if (!err) {
zlibCompress = buffer.toString('base64');
console.log('zlib: ', zlibCompress);
fs.writeFile(objectPath, zlibCompress, function(err) {
if (err) {
console.log(err);
}
console.log('saved');
});
} else {
console.log('Error compressing.');
}
});
When I run this script, the output is
Header 8 blob 16
Store is blob 16what is up, doc?
SHA-1 is bd9dbf5aae1a3862dd1526723246b20206e5fc37
Path is .git/objects/bd/9dbf5aae1a3862dd1526723246b20206e5fc37
zlib: eJwFwYEBACAEBMCV8kKNQ8/+I3RXvKyxzJbU4yDF4AHF9sLC8rZ5Gh/tqwrk
saved
However, when I try to read the Git object:
git cat-file -p bd9dbf5aae1a3862dd1526723246b20206e5fc37
I get
error: inflate: data stream error (incorrect header check)
error: unable to unpack bd9dbf5aae1a3862dd1526723246b20206e5fc37 header
fatal: Not a valid object name bd9dbf5aae1a3862dd1526723246b20206e5fc37
I'm not sure what I am doing wrong here.
Don't use base64.
Replace zlibCompress = buffer.toString("base64); with zlibCompress = buffer;
git cat-file will read this perfectly fine.

Getting: Firebase service named 'database' already registered error, even tho I am not importing firebase/database anywhere

Environment
Operating System version: Mac OS 10.15.1
Firebase SDK version: 8.8.0
Firebase Product: database (auth, database, storage, etc)
Node.js version: 8.15.1
NPM version: 6.9.0
"firebase": "7.5.0",
"firebase-admin": "8.8.0",
"firebase-functions": "3.3.0"
Problem
When I call firebase deploy --only functions, it stops on step functions: preparing functions directory for uploading... and throws:
database: Firebase: Firebase service named 'database' already registered (app/duplicate-service)
This is the where the error is found:
at error (....../functions/node_modules/#firebase/app/dist/index.node.cjs.js:41:21)
Also I started getting: Error parsing triggers: The gRPC binary module was not installed. This may be fixed by running "npm rebuild"
Of course I have tried npm rebuild but without any luck...
Relevant Code
The only way I reference database is through:
// Init firebase access to DB
const firebase_admin = require("firebase-admin");
// Get a database reference
const firebase_db = firebase_admin.database();
I do this in multiple files tho.
After a little more digging, I managed to find out that it is caused by code in these two files:
// Init firebase access to DB
const firebase_admin = require("firebase-admin");
// Get a database reference to our blog
const firebase_db = firebase_admin.database();
const get_firebase_data = async (page_type, call_back) => {
const is_paypal_page = page_type === "paypal"
const is_admin_page = page_type === "admin"
const content = await firebase_db.ref("/content").once("value")
const footer_content = await firebase_db.ref("/footer_content").once("value")
const header_items = await firebase_db.ref("/header_items").once("value")
const translations = await firebase_db.ref("/translations").once("value")
const single_product_homepages = await firebase_db.ref("/single_product_homepages").once("value")
const couple_products_homepages = await firebase_db.ref("/couple_products_homepages").once("value")
const categories_of_product_variety = await firebase_db.ref("/categories_of_product_variety").once("value")
let products;
let shipping_options;
let admin;
if(is_paypal_page || is_admin_page) {
products = await firebase_db.ref("/products").once("value")
shipping_options = await firebase_db.ref("/shipping_options").once("value")
}
if(is_admin_page)
admin = await firebase_db.ref("/admin").once("value")
const final_object = {
...
}
call_back(null, final_object)
}
module.exports = (req,res) => {
get_firebase_data(req.params[0].replace("/", ""), (err,result) => {
if(err) res.send(err)
res.send(result)
})
}
and
const paypal = require('paypal-rest-sdk')
const { paypal_config } = require("../config")
const axios_instance = require("./inventorysource/axios_inventorysource_instance")
const create_order = require("./inventorysource/create_order")
paypal.configure(paypal_config)
const paymentPaypal = (paymentID, execute_payment_json, call_back) => {
paypal.payment.execute(paymentID, execute_payment_json, (error, paymentLog)=> {
if (error)
return call_back(error)
else {
call_back(null, paymentLog)
}
})
}
module.exports = (req, res) => {
const body = req.body
const execute_payment_json = { "payer_id": body.data.payerID }
const paymentID = body.data.paymentID
paymentPaypal(paymentID, execute_payment_json, (err, paypal_data) => {
if(err)
res.send(err)
else
create_order(
axios_instance(body.data.is_production),
body.data.is_production,
body.data.amount,
body.data.user_and_product_data,
res, paypal_data
)
})
}
However I dont import or require "firebase/database" anywhere in my code.
What I have tried
As answers to similar issues suggest, I have deleted node_modules and package-lock.json and tried re-installing with npm install multiple times.
I have also tried using different versions od Node and completely rebuilding my packages with npm rebuild.
Furthermore I have tried installing latest versions of the above mentioned firebase packages and then deleting and install npm all over again. Still with no luck...
I also tried commenting out parts of my code that deal with firebase but still, the error remains.

Google cloud dialogflow intent detection nodejs example not working

I am trying to implement a very simple dialogflow agent integration with nodejs.
Here is what I did so far
I followed the code from Intent detection
I added the service account private key file .json to my server.
I added the environment variable GOOGLE_APPLICATION_CREDENTIALS with the path to my .json private key file.
Here is the code I am trying to run right now:
require('dotenv').config()
const projectId = 'gg-chatbot-216808';
const sessionId = 'quickstart-session-id';
const query = 'hello';
const languageCode = 'en-US';
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient();
// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: languageCode,
},
},
};
// This prints the private key path correctly.
console.log(process.env.GOOGLE_APPLICATION_CREDENTIALS);
// Send request and log result
sessionClient
.detectIntent(request)
.then(responses => {
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
})
.catch(err => {
console.error('ERROR:', err);
});
Then I get this error in the console when I run this file
Auth error:Error: invalid_user: Robot is disabled.
ERROR: { Error: 14 UNAVAILABLE: Getting metadata from plugin failed with error: invalid_user: Robot is disabled.
at Object.exports.createStatusError (/var/www/html/google_auth/node_modules/grpc/src/common.js:87:15)
at Object.onReceiveStatus (/var/www/html/google_auth/node_modules/grpc/src/client_interceptors.js:1188:28)
at InterceptingListener._callNext (/var/www/html/google_auth/node_modules/grpc/src/client_interceptors.js:564:42)
at InterceptingListener.onReceiveStatus (/var/www/html/google_auth/node_modules/grpc/src/client_interceptors.js:614:8)
at callback (/var/www/html/google_auth/node_modules/grpc/src/client_interceptors.js:841:24)
code: 14,
metadata: Metadata { _internal_repr: {} },
details: 'Getting metadata from plugin failed with error: invalid_user: Robot is disabled.' }
i also faced a similar issue for my angular bot.
What i did was, instead of using using the google_credentials from the json file, i created an object with private_key,client_email {these values can be taken from the service account private key file .json}, and passed the object while setting up the session client.
var config = {
credentials: {
private_key: "YOUR_PRIVATE_KEY",
client_email: "YOUR_CLIENT_EMAIL"
}
}
const sessionClient = new dialogflow.SessionsClient(config);
note: do copy the full private_key string from .json. It will start as "-----BEGIN PRIVATE KEY-----\n......" .
Also, in GCP go to the project->IAM then try setting role for the service as DIALOGLOW API ADMIN. Check if this works.
If this has not been resolved yet , the solution is to provide "fileKey" inside sessionClient.
const sessionClient = new dialogflow.SessionsClient({
fileKey:" path of your credentials.json file"
});
or
let filePath = process.env.GOOGLE_APPLICATION_CREDENTIALS ="Location of credentials file".
const sessionClient = new dialogflow.SessionsClient({
fileKey:filePath
});
this will even work if there is no system env variable is set as GOOGLE_APPLICATION_CREDENTIALS.
Hope this is helpful.

Error with Firebase deploy function to send push notifications

I'm developing an iOS app and now I'm stuck with Firebase deploy functions. I'm trying to send push notifications and I prepared the codes like below.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotifications = functions.database.ref('/messages/{messageId}')
.onCreate(event => {
const data = event.data;
const fromId = data.fromId;
const toId = data.toId;
const message = data.message;
console.log(fromId + ' sent a message to' + toId);
return admin.database().ref('/users/' + fromId).once('value', snapshot => {
var user = snapshot.val();
var payload = {
notification: {
title: user.username,
body: message
}
}
admin.messaging().sendToDevice(user.fcmToken, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
})
Database structure:
messages - messageId -fromId
└toId
└Message
└ messageId -fromId
└toId
└Message
.
.
.
And this is the error message.
37:1 error Parsing error: Unexpected token
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/...
Error: functions predeploy error: Command terminated with non-zero exit code1
Also in the log, I get errors like:
TypeError: Cannot read property 'fromId' of undefined
Is the error occurring because I'm not fetching fcmToken right?
I've never coded with JavaScirpt. I would appreciate any suggestion!
Change this:
exports.pushNotifications = functions.database.ref('/messages/{messageId}')
.onCreate(event => {
const data = event.data;
const fromId = data.fromId;
const toId = data.toId;
const message = data.message;
into this:
exports.pushNotifications = functions.database.ref('/messages/{messageId}')
.onCreate((snap,context) => {
const data = snap.val();
const fromId = data.fromId;
const toId = data.toId;
const message = data.message;
});
Check here for more info:
https://firebase.google.com/docs/functions/beta-v1-diff
You are most likely running v1 of firebase functions, which is the latest version which brought quite a few changes to the api. You can read more about the changes here. Specifically, you want to change your event => parameter to (snap, context) =>
exports.dbWrite = functions.database.ref('/path').onCreate((snap, context) => {
const data = snap.val();
const { fromId, toId } = data;
...
});

Categories

Resources