MongoDB not authorized error on Ubuntu 16.04 - node.js

I am installing a server on Digitalocean and have a MongoDB issue. I installed Mongo on the server and allowed remote access.
I created two users. One is super-user for me and the other is a regular user for the website users. I am able to connect to the mongo through Robomongo 3T (a mongo client) remotely for both users.
However, when I use the application from a browser, a simple login request gives an authentication error. Here is the error:
MongoError: not authorized on DATABASE_NAME to execute command { find: "users", filter: { email: "YYY", password: "XXX" }, limit: 1, singleBatch: true, batchSize: 1 }
Here is the realted server-side code:
Connecting the database at server.js:
MongoClient.connect(config.mongo_url, (err, client) => {
if(err) throw err
console.log('db connected')
app.locals.db = client
// start the server
app.listen(process.env.PORT || 3000, ()=>console.log('listening on port 3000!'))
});
Trying to connect to the local mongo on the server:
database.collection(config.mongo_col_user)
.findOne({
email: username,
password: hash
}, (err, user)=>{
if(err) return done(err)
if(!user) return done(null, false, {msg: 'not found'})
if(user.password)
return done(null, user)
})
I use pm2 on the server side and I use ecosystem.config.js which has the below code:
module.exports = {
apps : [
{
name: "NAME",
script: "SCRIPT_NAME",
watch: true,
env: {
"mongo_url": 'mongodb://USER_NAME:PASSWORD#localhost:27017?authMechanism=SCRAM-SHA-1&authSource=DATABASE_NAME',
"mongo_db_name": 'DATABASE_NAME',
"mongo_col_query": "COLLECTION_NAME",
}
}
]
}
Could you help with the problem please?

I have figured it out.
When I did make changes to pm2 environment file ecosystem.config.js, I did always restart pm2 with pm2 restart all. However, when you change the file, you should tell pm2 that you changed it by pm2 reload ecosystem.config.js --update-env.
Additionally, the correct syntax is no
mongodb://USER_NAME:PASSWORD#localhost:27017?authMechanism=SCRAM-SHA-1&authSource=DATABASE_NAME'
but
mongodb://USER_NAME:PASSWORD#localhost:27017/DATABASE_NAME'

Related

How to add proxy to connect with Azure Postgresql?

I use this script to connect node.js with Azure Postgresql.
But the ssl verification of our firewall blocks the connection, so in the past I need to use a proxy. Where in the code can I add the proxy settings as like host and port?
Means when I start the code, vscode should connect through the proxy to postgresql.
const pg = require('pg');
const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};
const client = new pg.Client(config);
client.connect(err => {
if (err) throw err;
else { queryDatabase(); }
});
function queryDatabase() {
console.log(`Running query to PostgreSQL server: ${config.host}`);
const query = 'SELECT * FROM inventory;';
client.query(query)
.then(res => {
const rows = res.rows;
rows.map(row => {
console.log(`Read: ${JSON.stringify(row)}`);
});
process.exit();
})
.catch(err => {
console.log(err);
});
}
To configure proxy for Visual Studio Code
Edit the settings.json file
Depending on your platform, the user settings file is located here:
Windows: %APPDATA%\Code\User\settings.json
macOS: $HOME/Library/Application Support/Code/User/settings.json
Linux: $HOME/.config/Code/User/settings.json
Modify and Add the below lines to configure your proxy
"http.proxy": "http://user:pass#proxy.com:portnumber",
"https.proxy": "http://user:pass#proxy.com:portnumber",
"http.proxyStrictSSL": false
If your proxy doesn't require authentication, you could simply use
"http.proxy": "http://proxy.com:portnumber",
"https.proxy": "http://proxy.com:portnumber"
"http.proxyStrictSSL": false
Restart VS Code
The documentation related to settings and schema of the settings.json file is here for reference

Connection to postgresql db from node js

I'm tyring to make a connection from my nodejs script to my db connection, but seems like there is a suspicius issue i'm not able to figure out.
At the moment, this is my code:
const { Pool } = require('pg');
const pool = new Pool({
user: 'user',
host: '192.168.1.xxx',
database: 'database',
password: 'password',
port: 5432,
});
pool.on('error', (err, client) => {
console.error('Error:', err);
});
const query = `SELECT * FROM users`;
pool.connect()
.then((client) => {
client.query(query)
.then(res => {
for (let row of res.rows) {
console.log(row);
}
})
.catch(err => {
console.error(err);
});
})
.catch(err => {
console.error(err);
});
The issue seems to be in pool.connect(), but i can't understand what i'm missing because i got no errors in the log. I've installed pg module in the directory of my project with npm install --prefix pg and i know modules are loaded correctly.
I edited postgresql.conf:
# - Connection Settings -
listen_addresses = '*'
and pg_hba.conf
host database user 192.168.1.0/24 md5
to make the database reachable via lan and seems liek it works, because i'm able to connect successfully with apps like DBeaver...but i can't with NodeJS.
It's possible there is some kind of configuration i've to active?

How to add x.509 certificate subject as a user to Mongodb 3.4 by Node.js MongoDB Driver API?

I need to add users to my MongoDB 3.4 Replica Set using an Node.js application that already has the Node.js MongoDB Driver API package.
The problem is: The API documentation doesn't cover how to add x.509 Certificate subject as a User.
Does anyone know how to do that? In other words, I need a Node.js mechanism/API which I can use to perform the mongodb command below:
mongo --host mongo-node-0
use admin
db.getSiblingDB("$external").runCommand(
{createUser: "emailAddress=foo#bar.com,CN=admin,OU=Clients,O=FOO,L=Dublin,ST=Ireland,C=IE",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db:"admin" },
{ role: "clusterAdmin", db: "admin" }
]})
Following the Mongo documentation, on Node, execute a command hash against MongoDB. This lets you access any commands not available through the API on the server.
command(selector[, options], callback)
Arguments:
selector (object) – the command hash to send to the server, ex: {ping:1}.
[options] (object) – additional options for the command.
callback (function) – this will be called after executing this method. The command always return the whole result of the command as the second parameter.
Returns:
null
So, you can try it:
var db = new Db('$external', new MongoServer('localhost', 27017));
db.open(function(err, db) {
if (err) {
console.log(err);
}
db.command({
createUser: "emailAddress=foo#bar.com,CN=admin,OU=Clients,O=FOO,L=Dublin,ST=Ireland,C=IE",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db:"admin" },
{ role: "clusterAdmin", db: "admin" }
]}, function(err, result){
if (err) {
console.log(err);
}
console.log(result)
db.close();
});
});

Unable to use tedious with Azure database

I've a node application which do have a connection to SQL Server.
Also, I'm using database as a service from Azure.
Code Snippet :
import { Connection } from 'tedious';
import { Request } from 'tedious';
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
instanceName: 'SQLEXPRESS', // Removed this line while deploying it on server as it has no instance.
database: 'dbname'
}
};
connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log('error : '+err);
} else {
console.log("Connected to Database");
}
});
It has a successful connection, if done, locally.
Console Output => Connected to Database.
Deep dive done using console log :
-> Connection object is being created, but, the event ".on" is not being able to establish.
-> The connection gets established when deployed locally, while, when deployed on server, it doesn't works.
Based on the documentation here, you need to provide an additional option for encrypted connection.
Please try the following for config:
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
database: 'dbname',
encrypt: true //Need to add this for connecting to Azure DB
}
};
Using this configuration, I was able to connect to my database hosted in Azure.

deployd mongodb connection error

I'm learning Angular js and trying to run deployd server. Followed http://terraltech.com/how-to-setup-deployd-on-ubuntu-server/ steps mentioned here.
When I try to add a row from deployd dashboard am getting below error as a response
{"message":"Database connection error","status":400}
Here is my production.js server configuration.
var deployd = require('deployd');
var server = deployd({
port: process.env.PORT || 5000,
env: 'production',
db: {
host: 'SAMLP15070001',
port: 27017,
name: 'deployd',
credentials: {
username: 'deployd',
password: 'deployd'
}
}
});
server.listen();
server.on('listening', function() {
console.log("Server is listening");
});
server.on('error', function(err) {
console.error(err);
process.nextTick(function() { // Give the server a chance to return an error
process.exit();
});
});
Here is my mongo information which I configured in production.js
> getHostName( )
SAMLP15070001
> show dbs;
admin 0.078GB
local 0.078GB
test 0.078GB
I'm not sure whey is my deployd db is not getting displayed here.
Can someone help me in resolving this issue ?
From your mongo you have to execute the following commands:
mongo shell
use admin
db.addUser( { user: "deployd", pwd: "deployd", roles: [ "userAdminAnyDatabase" ] } )
use deployd
db.addUser( { user: "deployd", pwd: "deployd", roles: [ "readWrite", "dbAdmin" ] } )

Resources