How to establish a remote connection with node potsgres? - javascript

I am trying to create an API where I can query information from a database. The DB is hosted on my university's computer cluster. Here is the code I currently have
const Pool = require('pg').Pool
const pool = new Pool({
user: 'username',
host: 'hostname-of-school-computer',
database: 'db-name',
password: 'pass',
port: 5432
})
const getUsers = (request, response) => {
pool.query('SELECT * FROM Inventory ORDER BY ingredient_id ASC', (error, results) => {
if (error) {
throw error.message
}
response.status(200).json(results.rows)
})
}
When I run this code and make a request on localhost, I get the error
no pg_hba.conf entry for host "165.xx.xx.172", user "username", database "db-name", SSL off
I tried adding ssl: true to the pool config but then got the error self signed certificate in certificate chain. Additionally, I have tried editing pg_hba.conf to listen to my school's host IP and that neither worked.
These are the lines I added to pg_hba.conf:
# TYPE DATABASE USER ADDRESS METHOD
host all all 0.0.0.0/0 md5
host all all 165.xx.xx.172/0 md5
I am kind of a noob when it comes to JS and postgres so please any help would be greatly appreciated.

Related

Nodemailer fails only in production

When I try to send an e-mail using nodemailer I got an connection timeout error with code 'ETIMEDOUT', but when I try on my notebook there's no error, both using the same e-mail account and password.
This is the file 'mail.js':
const nodemailer = require('nodemailer');
const user = process.env.EMAIL;
const pass = process.env.EMAIL_PASS;
const transporter = nodemailer.createTransport({
service: 'kinghost',
host: 'smtp.kinghost.net',
port: 587,
secure: false,
pool: true,
auth: { user, pass }
});
module.exports = {
sendMail(to, subject, html) {
const mailOptions = {
from: user,
to,
subject,
html
};
console.log(user)
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err)
};
console.log(`Mail to ${mail} has been sended`);
});
}
};
It might be because on a production website, you are on a server that has a different IP to your own, and perhaps your email service is running some filtering because it thinks it might be unintended behaviour.
You should maybe look into other secure ways of authenticating your email client, or perhaps see if you can register the IP of your production server (less effective).
Hey programmer friend.
I went through the same situation using kinghost. Make sure you check your email provider's dashboard for an option called "SMTP INTERNATIONAL".
Quick fix:
change your config
nodemailer.createTransport({
host: **"smtpi.kinghost.net"**, // smtp international
secure: true, // force port 465
port: 465, // default port
auth: {
user: process.env.EMAIL, //email
pass: process.env.EMAIL_PASS, //pass
}
});
Your ECS or EC2 container must run on a different source, for this reason, activate the international email in your provider and use the same to solve this problem.
Your ECS or EC2 container must run on a different source, for this reason, activate the international email in your provider and use the same to solve this problem.
For my application this worked.

Is there a way to create a database with mongoose that has a username and password?

I'm currently working on a app (dev with electron). I'm using mongoDB and mongoose for my persistant storage but I can't find a way to do something that seem really basic : when creating a database I'd like to add an user and a password to it (I realy search for it, but no way to find anything usable).
I have this need because it's going to be a multi-user app and I definitly don't want an user to know the contents of another user account.
The idea is that once you create an account, the app create a database that has the same username and password of the account. For login, the app try to connect you to the database with your account & password.
I'm working with :
electron
HTML / CSS / javascript
mongoDB
mongoose
Here is the code that I tested :
var mongoose = require('mongoose');
var connStr = "mongodb://localhost:27017/test";
mongoose.connect(connStr, {user: 'newUser', password: 'pwd', useNewUrlParser: true }, function(err) {
if (err) {throw err};
console.log("Successfully connected to MongoDB");
});
I get the error
Uncaught (in promise) MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoError: password must be a string]
However with those, the database is correctly created (but anyone can access it) :
user: '', password: ''
What I expect is to create a new database with the user name set as "newUser" and the password as "pwd", in that way only with the correct id & password would it be possible to connect to it.
Thanks for your help !
I don't know if this will work or not but I ran a mongo service using docker and then connected mongoose to it with the following code
mongoose.connect('mongodb://user:pass#localhost:port/MyDB?authSource=admin', {
useNewUrlParser: true
})
.then(() => console.log('MongoDB connection successful'))
.catch(err => console.error('Could not connect to MongoDB:‌', err));
this is equivalent to
mongo --username user --password pass --authenticationDatabase admin --port 27017

Google Cloud Functions - Connect to Cloud SQL via SSL

The GCF Cloud SQL documentation does not show how to connect via the socket using SSL. Here is my config, however when I try to connect I get an ECONNREFUSED error. But when I try to connect to a non-SSL database it works fine. Any ideas?
const mysql = require('mysql');
const mysqlConfig = {
connectionLimit: 1,
user: dbUser,
password: dbPassword,
database: dbName,
ssl: {
ca: await getFileContents(bucketName, ssl.ca_filename),
key: await getFileContents(bucketName, ssl.key_filename),
cert: await getFileContents(bucketName, ssl.cert_filename)
}
};
if (process.env.NODE_ENV === 'production') {
mysqlConfig.socketPath = `/cloudsql/${connectionName}`;
}
// Connection pools reuse connections between invocations,
// and handle dropped or expired connections automatically.
let mysqlPool;
exports.mysqlDemo = (req, res) => {
// Initialize the pool lazily, in case SQL access isn't needed for this
// GCF instance. Doing so minimizes the number of active SQL connections,
// which helps keep your GCF instances under SQL connection limits.
if (!mysqlPool) {
mysqlPool = mysql.createPool(mysqlConfig);
}
mysqlPool.query('SELECT NOW() AS now', (err, results) => {
if (err) {
console.error(err);
res.status(500).send(err);
} else {
res.send(JSON.stringify(results));
}
});
};
Connections between Cloud Functions and Cloud SQL work in the same way as connections from App Engine . As such SSL/TLS connections are needed only when you are connecting to Cloud SQL using public IP addresses. If Cloud SQL Proxy or the Java Socket Library, is used, setting up SSL is not required encryption happen by default.
How to set this up is set in the following document:
https://cloud.google.com/functions/docs/sql#connecting_to_cloud_sq
For an explanation as to how the connections are implemented please have a look at:
https://cloud.google.com/sql/docs/mysql/configure-ssl-instance

Send multipe emails using nodemailer and gmail

I am trying to send an email to multiple recipients ( about 3.000 ). All emails are stored in my DB ( Mongo ). So I make a query that return all the email addresses, and I use async to send all the emails, like:
function _sendEmail(params, callback) {
async.each(params.email, function(user, cb) {
const mailOptions = {
from: sender
to: user,
subject: Subject,
text: 'Hello Word',
};
app.transporter.sendMail(mailOptions, function(err, response) {
if(err) console.log(err);
else console.log(response);
cb();
});
}, callback);
}
I am creating my nodemailer transporte in my app.js, ,like so:
const transporter = nodemailer.createTransport(smtpTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: senderMail,
pass: senderMailPassword
}
}));
When I try to send this to only 10 mails, it works just fine, but when I try to send to all the emails in my DB, I am getting this error a bunch of times:
{ [Error: Data command failed: 421 4.7.0 Temporary System Problem. Try again later (WS). g32sm7412411qtd.28 - gsmtp]
code: 'EENVELOPE',
response: '421 4.7.0 Temporary System Problem. Try again later (WS). g32sm7412411qtd.28 - gsmtp',
responseCode: 421,
command: 'DATA' }
Am I missing something? Do I need to set something to be able to send lots os emails in a small period of time? I am using a gmail account to do that!
Thanks in advance!
It is because you are attempting to create a new smtp connection for each email.
You need to use SMTP pool.
Pooled smtp is mostly useful when you have a large number of messages that you want to send in batches or your provider allows you to only use a small amount of parallel connections.
const transporter = nodemailer.createTransport(smtpTransport({
host: 'smtp.gmail.com',
port: 465,
pool: true, // This is the field you need to add
secure: true,
auth: {
user: senderMail,
pass: senderMailPassword
}
}));
You can close the pool as
transporter.close();
From Gmail :
421 SMTP Server error: too many concurrent sessions
You may handle your send differently :
wait to close the session between each sending
send by bunch of mail
The best way is to manage to not exceed the limit of 10 session in the same time :)

Trying to connect to SQL Server 2014 on NodeJS

I am trying to connect to SQL Server 2014 with NodeJS, i am using the "mssql" package, i dont have answer here is my code
var sql = require('mssql');
var opciones = {
user: 'myuser',
password: 'mypass',
server: 'myserver',
database: 'mydatabase',
options: {
encrypt: true
}
};
sql.connect(opciones,function(err){
if(err){
console.log(err);
}else{
console.log("CONEXIÓN EXITOSA");
}
});
the name of that js is "cnSQL.js", when i execute on cmd "node cnSQL" I dont have answer.
Tested the code as above with my local DB instance.
The code is actually correct.
var sql = require('mssql');
var opciones = {
user: 'sa',
password: 'mypass',
server: '127.0.0.1',
database: 'mydb',
options: {
encrypt: true
}
};
sql.connect(opciones,function(err){
if(err){
console.log(err);
}else{
console.log("CONEXIÓN EXITOSA");
}
});
I have managed to get the 'Connexion Exitosa' message.
In order to further debug your issue, attempt the following:
With the username you are trying to login with (In my case 'sa')
Open SQL Server Management Studio and attempt to put in the connection information as above. Click login, does that work?
If not:
Open SQL Server Management Studio
Connect to the SQL Server Instance you are trying to connect to from NodeJS
Right click on the instance of your SQL server and click properties
Click security and ensure that the "SQL Server and Windows Authentication mode" radio button is selected.
When done click OK
On the left hand navigation expand the Node "Security"
Expand Logins
Find your user and ensure it is enabled and that the password you selected reflects the password within your NodeJS app.
If so:
Amend all the information within the code to reflect exactly the credentials used to login
Special Note: '.' will not represent localhost here. Use 127.0.0.1 or localhost
Furthermore, if the SQL server instance you are trying to connect to is not hosted locally. Ensure that the machine it is hosted on accepts connections on port 1433 (by default for SQL Server).
Hope it helps!

Categories

Resources