This happens even when the DB user specified in .env file is different. For the record "ankitj" is also the username of my system. I don't understand why this is happening.
Here's the error:
Unhandled rejection SequelizeConnectionError: password authentication failed for user "ankitj"
at connection.connect.err (/home/ankitj/Desktop/skillbee/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:128:24)
at Connection.connectingErrorHandler (/home/ankitj/Desktop/skillbee/node_modules/pg/lib/client.js:140:14)
at Connection.emit (events.js:160:13)
at Socket.<anonymous> (/home/ankitj/Desktop/skillbee/node_modules/pg/lib/connection.js:124:12)
at Socket.emit (events.js:160:13)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at Socket.Readable.push (_stream_readable.js:213:10)
at TCP.onread (net.js:599:20)
I'm assuming that you're getting this error using Sequelize with Node.js. I ran into the same error when I had the following:
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.DATABASE_USER,
process.env.DATABASE_PASSWORD,
{
dialect: 'postgres',
}
)
I was able to solve the issue by replacing it with a connection ur:
const sequelize = new Sequelize("postgres://postgres:postgres#localhost/gql", {
dialect: 'postgres'
// anything else you want to pass
})
where gql is the name of DATABASE in my .env file.
The user "ankitj" executes the command to run the Node script, so the script is trying to connect as that user. I first tried to solve this on the Postgres end by adding a user and granting permissions, but was unable to get that to work--I'd be interested in seeing that solution--but specifying a connection url worked for me.
I had the same issue when I was using the default password for the PostgreSQL. Try to change it from the command line as follows.
psql
\password
Then Enter a new password and update your .env files and that should Work.
Instead of using the process.env variables I put the actual names but wrapped in quotes (" ") and it's worked.
I have faced the same issue when I connect with NodeJS and Postgres SQL. I found a solution. We need to check db.config.js file(database config file) and index.js(where u called the const sequelize = new Sequelize(.......) properties name is matching or not.
// db.config.js
module.exports = {
user: '******',
host: 'localhost',
database: '***********',
password: '***',
port: 5432,
dialect: "postgres", // we need to implement
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
const Sequelize = require("sequelize");
const dbConfig = require("../config/db.config.js");
const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
host: dbConfig.host,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
},
})
Mentioned the above params line as (dbConfig.database, dbConfig.user, dbConfig.password) we need to check with db.config.js file
Note: please add dialect properties on the db.config.js file.
Now Problem is solved...Thanks
Console verbiage log
I also had the same error but I solved it by using template strings
const sequelize = new Sequelize(`${process.env.DB_NAME}`, `${process.env.DB_USER}`, `${process.env.DB_PASSWORD}`, {
host: process.env.DB_HOST,
dialect: 'postgres'
});
Related
I'm currently trying to create a functional query from the database to post it into a created a csv file, however I am unable to connect to the PSQL host programmatically. So what I am trying to do is :-
Connect to DB and query results
Push results to an Excel File
Continue()
SFTP Results to myself on SFTP Server and place file in directory.
I am able to connect to the PostgresDB manually by the following in CLI:-
ssh username#xx.xx.xx.xx //Doesnt need password because my id_rsa key is stored on the Server
psql -U username -h LOCALHOST -p 5432 -d databasename pass- password (Manually input)
Furthermore, connecting through Visual Studio Code works as well however I need to connect to the server (Remote Connection) and then connect to the Database using a postgres Driver.
After investigating it, I figured I firstly need to connect using SSH to the server, then and only then I will be allowed to access the Database.
This is how I approached it through Code :-
Index.js
const serverConnectionParams = require('./src/config/serverConn');
function testConnectionServer() {
try {
serverConnectionParams.connectToServer();
} catch (err) {
console.error(err);
}
}
testConnectionServer();
serverConn.js
const { Client } = require('ssh2');
const { readFileSync } = require('fs');
const databaseConnectionParams = require('./databaseConn');
function connectToServer() {
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('uptime', (err, stream) => {
if (err) throw err;
databaseConnectionParams.auth(); *// This is the database connection param*
stream.on('data', (data) => {
console.log('STDOUT: ' + data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'xx.xx.xx.xx',
username: 'username',
privateKey: readFileSync('src/key/id_rsa')
});
}
exports.connectToServer = connectToServer;
databaseConn.js
const { readFileSync } = require('fs');
const envParam = require('./env.js');
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize(envParam.database, envParam.username, envParam.password, {
host: envParam.host,
dialect: envParam.dialect,
ssl: true,
pool: {
max: envParam.pool.max,
min: envParam.pool.min,
acquire: envParam.pool.aquire,
idle: envParam.pool.idle
}
});
async function auth() {
try {
console.log('trying to connect')
sequelize.validate();
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
exports.auth = auth;
env.js
const env = {
database: 'databasename',
username: 'username',
password: 'password',
host: 'ip#',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
aquire: 30000,
idle: 10000
}
};
module.exports = env;
After running my node index.js I receive the following error statement :-
Client :: ready
trying to connect
STDOUT: 10:43:09 up 1:21, 1 user, load average: 5.71, 6.03, 5.15
C:\Users\~\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:184
reject(new sequelizeErrors.ConnectionError(err));
^
ConnectionError [SequelizeConnectionError]: no pg_hba.conf entry for host "xx.xx.xx.xx", user "username", database "databasename", SSL off
at Client._connectionCallback
{
parent: error: no pg_hba.conf entry for host "xx.xx.xx.xx", user "username", database "databasename", SSL off
at Parser.parseErrorMessage
{
length: 154,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '490',
routine: 'ClientAuthentication'
},
original: error: no pg_hba.conf entry for host "x.x.x.x", user "username", database "password", SSL off
at Parser.parseErrorMessage (C:\Users\~\node_modules\pg-protocol\dist\parser.js:287:98)
at Parser.handlePacket (C:\Users\~\node_modules\pg-protocol\dist\parser.js:126:29)
at Parser.parse (C:\Users\~\node_modules\pg-protocol\dist\parser.js:39:38)
at Socket.<anonymous> (C:\Users\~\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:394:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:199:23) {
length: 154,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'auth.c',
line: '490',
routine: 'ClientAuthentication'
}
}
Investigating the Error Code: 28000
Found this link explaining the issue as an authentication attempt failure
https://help.heroku.com/DR0TTWWD/seeing-fatal-no-pg_hba-conf-entry-errors-in-postgres
Also found several solutions online regarding pg_hba.conf needs to use md5 and then restart postgress (Not tried, as i cannot restart the postgress service)
error: Ident authentication failed for user
Found another solution explaining it was an SSL issue (Tried it and it didnt work)
Node.js, PostgreSQL error: no pg_hba.conf entry for host
After using SSL it would change the error code to the following :-
SequelizeConnectionError: self signed certificate
Found a solution to that here:-
SequelizeConnectionError: self signed certificate
After I put that it would give me a different error that rejectUnauthorized is depreciated and very old version (Cant seem to reproduce the error code as of the moment)
So my hands are tied at the moment, any help will be great!
I've also tried using different Javascript modules instead of sequelize however they all have the same authentication issue.
I also tried to pass my id_rsa key, however it wouldnt solve my issue at all.
My assumptions are even though I am passing the connToDatabase function inside the SSH connection, it is still searching for the ip# in the incorrect location. (Ip# of DB on the server is 192.168.31.4)
But when using that IP# it will say ERR Connection Timed out
Another Assumption I have is that the Database has many restrictions from connecting and require further more params.
UPDATE:
I tried editting the pg_hba.conf file through remote access on VSC however it would give me error cannot read file.
Any help would be great!
I had completely forgotten that I posted this question.
The solution to it was pretty straight forward, after investigating it for a while I realized I was making a mistake in connection params.
For others who require help with such issues I will post the solution in a simple manner.
Basically, I needed first to SSH to the server and add a tunnel to my connection to connect to the database. Then and only then will my sequelize params for the database pass through because I have completely connected to the server and internal postgresql database.
So TLDR
SSH -> Tunnel -> Sequelize
ssh(10.x.x.1, etc) -> addTunnel(localhost, etc) -> sequelize(databaseName, etc)
EDIT: Added Code for reference
const Ssh2Promise = require('ssh2-promise');
const { readFileSync } = require('fs');
async function connectToServer(callback) {
const ssh = new Ssh2Promise({
host: '10.x.x.1',
username: 'usernameofssh',
privateKey: readFileSync('src/key/id_rsa'), //This is only for RSA Fingerprint, if you do not have said fingerprint you can use "passphrase" with your password instead
});
const tunnel = await ssh.addTunnel({
remoteAddr: '192.168.0.1', //This is the database connection ip#, once connected to it you can fetch from LOCALHOST. Incase its AWS it would be test.test-test.amazonaws.com
remotePort: 1234, //Port for connection
localPort: 1234,
});
//Don't forget to throw it in a try catch for feedback
await auth(callback); //Send it wherever you need it to go
}
I have a postgresql database, schema and username:password.
If i run:
sequelize db:migrate --config=./dist/options/db.options.js --migrations-path=./dist/migrations --env=main
...then i catch error:
CREATE SCHEMA IF NOT EXISTS my_schema;
**ERROR**: permission denied for database my_database
My user cannot create schema, but this schema already exists.
How i can to disable this step on sequelize migrations options?
It is my sequelize config:
const CONNECTION: any = {
dialect: 'postgres',
host: process.env.PG_HOST,
port: parseInt(process.env.PG_PORT, 10),
database: process.env.PG_DATABASE,
username: process.env.PG_USERNAME,
password: process.env.PG_PASSWORD,
models: [
...
],
autoLoadModels: true,
sync: false,
migrationStorage: "sequelize",
migrationStorageTableName: genTableName('migrations'),
migrationStorageTableSchema: process.env.PG_SCHEMA,
logging: (...msg) => console.log(msg)
};
Google couldn't help me...
I found answer on my question. In my situation need to remove key migrationStorageTableSchema from config.
I'd like to connect to Redshift using temporal credentials.
I'd tried connecting with master username and password and it works fine. The problem of the temporal credentials is the username that is following format:
username: 'IAM:awsuser'.
So I think the connection is not understanding correctly the ":". So it always through invalid password. I have try this username and password from the Redshift query-editor and it connects without any problem.
This is the configuration I'm using:
const configRed = {
host: 'redshift-cluster-name.aaaaaaa.eu-west-1.redshift.amazonaws.com',
user: 'IAM:awsuser',
password: data.DbPassword,
database: 'dev',
port: 5439,
idleTimeoutMillis: 0,
max: 10000
};
redshiftPool = new psql.Pool(configRed);
redshiftCon = await redshiftPool.connect();
I have also tried using the username with encodeURIComponent:
user: encodeURIComponent('IAM:awsuser'),
It through next error:
"errorMessage": "password authentication failed for user \"IAM:awsuser\"",
Could be possible to change the connection URL in the PG library, for some custom URL like:
jdbc:redshift:iam://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/dev
Specifying "ssl: true" in the params argument when creating the Pool object indeed works:
const configRed = {
host: 'redshift-cluster-name.aaaaaaa.eu-west-1.redshift.amazonaws.com',
user: 'IAM:awsuser',
password: data.DbPassword,
database: 'dev',
port: 5439,
idleTimeoutMillis: 0,
max: 10000,
ssl: true
};
I am developping a backend application with node and sequelize. My database is from postgresql.
When lauching the app, the database connection works fine, but when it tries to communicate with the database to read or update, it fails with a connection error:
password authentication failed for user "wushin".
Seems really weird to me because database connection has already been done, and password has been validated. Do you guys know what's happening ? Maybe an issue with pg module but I tried different versions.
Versions
Node: 10.17.0
Sequelize: 5.21.3
Postgres: 10.11
pg module: 7.17.1
-> This code works fine:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})
-> But this promise fails with SequelizeConnectionError:
models.Question.findAll()
.then(data => {
console.log('-> Succeeded data fetching\n')
console.log(data)
})
.catch(err => {
console.log('-> Failed data fetching\n')
console.log('Error', err)
})
Logs:
yarn run v1.19.2
$ node index.js
Example app listening on port 4000 or something!
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
- Trying to fetch data:
-> Failed data fetching
Error:
{ SequelizeConnectionError: password authentication failed for user "wushin"
at connection.connect.err (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:182:24)
at Connection.connectingErrorHandler (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/client.js:194:14)
at Connection.emit (events.js:198:13)
at Socket.<anonymous> (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/connection.js:128:12)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:287:12)
at readableAddChunk (_stream_readable.js:268:11)
at Socket.Readable.push (_stream_readable.js:223:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'SequelizeConnectionError'
It seems that you pass no configurations to Sequelize but the host. The minimum configurations are host, port, databasename, dialect username, and password.
From the docs:
const Sequelize = require('sequelize');
// Option 1: Passing parameters separately const sequelize = new
Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});
// Option 2: Passing a connection URI const sequelize = new
Sequelize('postgres://user:pass#example.com:5432/dbname');
I finally fixed this. The issue was that with sequelize, requiring the models calls an index.js that is supposed to do the sequelize connection for you, using the config repository sequelize creates.
My connection to sequelize was working well but the one that was launched by requiring models had some bad information on my database.
Therefore I could not use the imported model to fetch data on the database.
I inserted good config information :
require('dotenv').config()
module.exports = {
development: {
url: process.env.DATABASE_URL,
dialect: 'postgres',
},
test: {
url: process.env.DATABASE_TEST_URL,
dialect: 'postgres',
},
production: {
url: process.env.DATABASE_PROD_URL,
dialect: 'postgres',
},
}
And completely removed the line that I wrote myself:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
It is now the models/index.js that connects to the database with :
const sequelize = new Sequelize(process.env.DATABASE_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})
I've come across several posts for this question however, none of them seem to have an actual answer. Several ideas, yet none of them work.
After digging around both the Sequelize and Tedious packages and watching my config get passed down correctly, I'm at a loss.
I am trying to run migrations against a new database in MSSQL. I have no problem connecting to it with the same creds I'm using here so I know that's not the issue.
I have my config.js that is pulling env vars. With the exception of my custom console statements, this file was auto generated from sequelize and is correctly referenced in my sequelizerc
require('dotenv').config()
console.log('[+] Loading database config...')
if (process.env.NODE_ENV === 'production') {
console.log(`[+] Using database: ${process.env.PROD_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'development') {
console.log(`[+] Using database: ${process.env.DEV_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'test') {
console.log(`[+] Using database: ${process.env.TEST_DB_DATABASE}`)
} else if (process.env.NODE_ENV === 'local') {
console.log(`[+] Using database: ${process.env.LOCAL_DB_DATABASE}`)
} else {
console.log(`[-] CANNOT LOAD DATABASE FROM ENV: ${process.env.NODE_ENV}`)
process.exit()
}
module.exports = {
production: {
database: process.env.PROD_DB_DATABASE,
username: process.env.PROD_DB_USERNAME,
password: process.env.PROD_DB_PASSWORD,
host: process.env.PROD_DB_HOST,
port: process.env.PROD_DB_PORT,
dialect: process.env.PROD_DB_DIALECT,
storage: process.env.PROD_DB_STORAGE,
logging: false,
dialectOptions: {
instanceName: process.env.PROD_INSTANCE_NAME
},
pool: {
min: 5,
max: 1,
acquire: 6000,
idle: 6000
}
},
development: {
database: process.env.DEV_DB_DATABASE,
username: process.env.DEV_DB_USERNAME,
password: process.env.DEV_DB_PASSWORD,
host: process.env.DEV_DB_HOST,
port: process.env.DEV_DB_PORT,
dialect: process.env.DEV_DB_DIALECT,
storage: process.env.DEV_DB_STORAGE,
logging: console.log,
dialectOptions: {
instanceName: process.env.DEV_INSTANCE_NAME,
debug: true
},
pool: {
min: 5,
max: 1,
acquire: 6000,
idle: 6000
}
},
test: {
database: process.env.TEST_DB_DATABASE,
username: process.env.TEST_DB_USERNAME,
password: process.env.TEST_DB_PASSWORD,
host: process.env.TEST_DB_HOST,
port: process.env.TEST_DB_PORT,
dialect: process.env.TEST_DB_DIALECT,
storage: process.env.TEST_DB_STORAGE,
logging: false
},
local: {
database: process.env.LOCAL_DB_DATABASE,
username: process.env.LOCAL_DB_USERNAME,
password: process.env.LOCAL_DB_PASSWORD,
host: process.env.LOCAL_DB_HOST,
port: process.env.LOCAL_DB_PORT,
dialect: process.env.LOCAL_DB_DIALECT,
storage: process.env.LOCAL_DB_STORAGE,
logging: false
}
}
When i run my migration i get the error:
> node_modules/.bin/sequelize db:migrate
// ERROR: Login failed for user ''.
As mentioned above I dug through sequelize and tedious and my config is getting passed properly through both so i know it's not an env var issue or a NODE_ENV issue.
Anyone have any ideas here? I'm about to smash my face into my keyboard.
More for older versions:
If you are using sequelize#4, then it seems there is a hidden requirement that you must use tedious#<=5.
Which version of Sequelize are you using? If it's v5,
According to Sequelize v5's document:
Sequelize now works with tedious >= 6.0.0
However, in its package.json, it does not depend on tedious at all.
Since your program still runs, I guess you manually installed an older version of tedious before, which caused this strange problem.
Manually installing tedious of version>=6 should solve this problem, just like stated in its Getting started document page:
You'll also have to manually install the driver for your database of choice:
# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
const Sequelize = require('sequelize');
const sequelize = new Sequelize(
process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
dialect: 'mssql',
host: process.env.DB_HOST, //This is an IP
dialectOptions: {
options: {
instanceName: process.env.DB_INSTANCE_NAME,
trustServerCertificate: true
},
}
}
);
module.exports = {
sequelize,
Sequelize
};
Here is another solution, it's working for me.
I was getting the same error. The reason was due to explicitly mentioning the name of the DB in the sequelize config file and it did not exist. The reason could be different in your case but a quick look at SQL Server error logs will give you the reason for the failure.
Login failed for user 'user'. Reason: Failed to open the explicitly specified database 'dbo'. [CLIENT: XX.XX.XX.XX]