Unknown error during authentication - couchdb

I'm using PouchDB 4.0. To test the credentials to a remote CouchDB server, I use the following code:
testCredentials: function(credentials, callback){
var remoteDb = new PouchDB('http://X.X.X.X/dbName', {
auth: {
username: credentials.username,
password: credentials.password
}
});
remoteDb.info(function(err, info) {
if (err) {
if(err.status == 401)
callback("unauthorized");
else {
console.log(err);
callback("error");
}
} else {
callback("success");
}
});
}
When I pass invalid credentials (e.g. existing user but invalid password), I see a 401 error returned inside the CouchDB log file. However, PouchDb always returns the following 500 error:
{"status":500,
"name":"unknown_error",
"message":"Database encountered an unknown error",
"error":true}
The same problem occurs when using the pouchdb-authentication plugin.
This code worked perfectly in previous versions of PouchDB.

Can you file a bug with steps to reproduce at the Github issues page? Seems to be a new bug in PouchDB. Also if you could print out the logs from the error (might be an HTTP error, check the "Network" tab), then that would be helpful too.
"Database encountered an unknown error" is a generic error message that PouchDB throws up when it hits an error it doesn't know how to handle, so posting or screenshotting that other error would be very helpful. :)
Also, if you are using pouchdb-authentication, then you typically don't need to add the auth option when creating a new PouchDB; that option is for plain http-based authentication, whereas pouchdb-authentication uses cookie authentication.

Related

Heroku postgres timeout and SSL issues on API calls with Node

I'm trying to put my REST API built in Node and with PostgresSQL to Heroku. So, I created my application to Heroku, and created his own database. At this point, I tryied to commit, and the build worked corretly. This until I tryied to make some calls to the API. If the api calls I do has the uncorrect method, or doesn't exists, it gives me the correct error, but when the call is correct, there is a 503 error, with code H12, and description that is timeout error. Here is the code of one of the calls to the database that I'm testing:
router.get('/allpoints', async (req,res) =>{
try {
const points = await pool.query(
`SELECT nome, latitudine,longitudine
FROM luogo`);
res.json(points.rows);
}catch(err){
console.error(err.message);
}
});
Here there are the information about how I connect to the database.
const pool = new Pool({
connectionString: process.env.DATABASE_URL || 'postgresql://postgres:psw#localhost:5432/campione',
ssl: process.env.DATABASE_URL ? true : false
})
module.exports = pool;
The build on Heroku seems to work properly.
I read this question: Heroku h12 Timeout Error with PG / Node.js
It says that you have to put res.end() where there is not res.json(), but here there is the res.json(). So, I thought that the issue could be that there is an error that the route manage, and can't give back anything. So, I changed from console.log(err) to res.json(err), and the API response with `ssl self signed, as an error. At this point, in the second file, I put ssl as false by default, but it gaves me error because there is no SSL. I searched for a really long time for a solution, but I have not been able yet to fix the issue.
Someone thinks he knows what should I change? Thank you in advice
this option in databse config maybe useful
ssl: {
rejectUnauthorized : false,
}

NodeJS can't connect to XERO

I am using xero as my accounting software. I have one requirement that part of my application need to be integrated with xero to perform automation. Using the nodejs sdk seems so easy, but the fact is i cannot connect to xero even using the simplest example. Here is the code:
const xero = require('xero-node');
const config = {
"userAgent": "Firefox",
"consumerKey": "<MY_CONSUMER_KEY>",
"consumerSecret": "<MY_CONSUMER_SECRET>",
"privateKeyPath": "./privatekey.pem"
};
const xeroClient = new xero.PrivateApplication(config);
xeroClient.core.contacts.getContacts()
.then(contacts => {
console.log(contacts);
}).catch(err => {
console.log(err);
});
The code does nothing and prints no error. Anyone ever deal with this problem?
The most likely reason is that your privatekey is invalid. If you put these lines(https://github.com/XeroAPI/xero-node/pull/169/files) into your module then it will check it first.
You could also copy a few of those lines and validate your privateKey.
At the moment the SDK swallows the exception when the key is invalid.
Also, please make sure you are running server side - not browser side.
Solved. I need to add following code:
if (config.privateKeyPath && !config.privateKey)
config.privateKey = fs.readFileSync(config.privateKeyPath);

Silently reporting errors to Papertrail

I'm working with a large Node.js application on Heroku, with logging maintained by Papertrail. I have a central error handling and logging function which, at the moment, just logs an error to the console, displays a generic "An error occurred!" dialog, and redirects a client to a specific page (depending on where the error occurred). But neither Papertrail nor Heroku detect this as a real error, and I don't get any sort of notifications or alerts if and when they occur.
At the moment, this is my function:
utilities.errorLogger = (err) => {
console.error(err);
};
I've tried to throw the error, which works like below:
utilities.errorLogger = (err) => {
throw new Error(err);
};
But then the error is displayed to the client, rather than being redirected away, leaving the end user confused. Similarly, putting the error in a try-catch block does not change anything from what I currently have (the error is logged but not picked up on by Papertrail or Heroku).
utilities.errorLogger = (err) => {
try {
throw new Error(err);
}
catch (err) {
console.error(err);
}
};
How can I silently throw an error for Papertrail and Heroku to pick up on and treat as an error, without needing to send the error to the client? I'd like to be able to silently handle the error and have the reporting go on in the background, rather than sending any of the error details to the client.
Ended up finding out the answer. I'm using KeystoneJS which comes with a default error handler that I hadn't seen before; I've modified it now to just redirect people while still being able to log the error.

Active directory proxy in node.js

I'm trying to write an activty directory proxy, that will receive search requests, run some code, and then recreate the request with the real server.
I'm not able to get it to work, here's the code so far:
var ldap = require('ldapjs');
var ActiveDirectory = require('activedirectory');
var server = ldap.createServer();
server.bind('cn=root', function(req, res, next) {
console.log('BIND REACHED');
if (req.dn.toString() !== 'cn=root' || req.credentials !== 'somepassword')
return next(new ldap.InvalidCredentialsError());
res.end();
return next();
});
server.listen(389, '127.0.0.1', function() {
console.log('LDAP server listening at %s', server.url);
});
var ad = new ActiveDirectory({
url: 'ldap://127.0.0.1',
baseDN: 'dc=lab,dc=ldapproxy,dc=local',
username: 'root',
password: 'somepassword'
});
ad.findUser('root', function (err, results) {
if (err) {
console.log('AD Login Failed: '+err);
}
else
console.log('AD Login Succeeded.');
});
The error that im getting is:
ProtocolError: InvalidDistinguishedNameError: root
It seems no matter how or what i put in the ActiveDirectory credentials i keep getting the same error.
But when i run that same code with different credentials on a real active directory server it works without any errors.
What am i missing here?
The site i'm reading is explaining how to do this on linux and with the passwords file, i'm not using linux or any files and i don't see any samples describing how to configure the server on the binding and searching based on what i wrote.
EDIT I forgot to mention that this code snappit is for debugging, i know that i'm trying to connect to the same server i just created, that's for testing purposes and learning how to ldap.
The error says it all: root is not a valid distinguished name you can use for binding.
In generic LDAP (OpenLDAP, for instance), you can only perform a bind operation with a "username" that is a fully qualified distinguished name (FQDN) of the object (the user, in the ldap database) with which you want to bind. That would be something like this:
CN=root,OU=Users,DC=example,DC=local
This, of course, depends on where the user account is located in the database.
Note: In Active Directory, the bind operation is not limited to a FQDN of the user - there are several other options what can be used as a username during binding. I have covered this in a previous SO question. However, I am unsure if ldapjs supports these username formats, considering the error message you are seeing.

Debug Node.js & Express App - Intermittently using 100% CPU

I'm developing an app using NGinx + Node.js + Express + Firebase that simply takes input from a mobile app and stores it to Firebase, optionally uploading files to S3.
In its simplest terms, the "create" function does this
Validates input
Formats the input Checks if there is a file uploaded
(via the multer plugin) and stores it
If there was a file, upload
to Amazon S3 and delete the source file (it's important to note I was
encountering this issue before the inclusion of S3).
Create the item
by pushing into the items reference on Firebase
Create the item for
the user by pushing into the user_items reference on Firebase.
There are a few other functions that I have implemented as an API.
My trouble is coming from an intermittent spike in CPU usage, which is causing the nginx server to report a gateway timeout from the Node.js application.
Sometimes the server will fall over when performing authentication against a MongoDB instance, other times it will fall over when I'm recieving the input from the Mobile app. There doesn't seem to be any consistency between when it falls over. Sometimes it works fine for 15+ various requests (upload/login/list, etc), but sometimes it will fall over after just one request.
I have added error checking in the form of:
process.on('uncaughtException', function(err) {
console.error(err.stack);
});
Which will throw errors if I mistype a variable for example, but when the server crashes there are no exceptions thrown. Similarly checking my logs shows me nothing. I've tried profiling the application but the output doesn't make any sense at all to me. It doesn't point to a function or plugin in particular.
I appreciate this is a long winded problem but I'd really appreciate it if you could point me in a direction for debugging this issue, it's causing me such a headache!
This may be a bug in the Firebase library. What version are you using?
I've been having a very similar issue that has had me frustrated for days. Node.js + Express + Firebase on Heroku. Process will run for a seemingly random time then I start getting timeout errors from Heroku without the process ever actually crashing or showing an error. Higher load doesn't seem to make it happen sooner.
I just updated from Firebase 1.0.14 to latest 1.0.19 and I think it may have fixed the problem for me. Process has been up for 2 hours now where it would only last for 5-30 min previously. More testing to do, but thought I'd share my in-progress results in case they were helpful.
It seems the answer was to do with the fact that my Express app was reusing one Firebase connection for every request, and for some reason this was causing the server to lock up.
My solution was to create some basic middleware that provides a new reference to the Firebase on each API request, see below:
var Middleware = {
/*
* Initialise Firebase Refs per connection
*/
initFireBase: function(req, res, next) {
console.log('Intialising Firebase for user');
// We need a authToken
var authToken = req.param('authToken');
// Validate the auth token
if(!authToken || authToken.length === 0) {
return res.send(500, {code: 'INVALID_TOKEN', message: 'You must supply an authToken to this method.'});
}
else {
// Attempt to parse the auth token
try {
var decodedToken = JWTSimple.decode(authToken, serverToken);
}
catch(e) {
return res.send(500, {code: 'INVALID_TOKEN', message: 'Supplied token was not recognised.'});
}
// Bail out if the token is invalid
if(!decodedToken) {
return res.send(500, {code: 'INVALID_TOKEN', message: 'Supplied token was not recognised.'});
}
// Otherwise send the decoded token with the request
else {
req.auth = decodedToken.d;
}
}
// Create a root reference
var rootRef = new Firebase('my firebase url');
// Apply the references to each request
req.refs = {
root: rootRef,
user: rootRef.child('users'),
inbox: rootRef.child('inbox')
};
// Carry on to the calling function
next();
}
};
I then simply call this middleware on my routes:
/*
* Create a post
*/
router.all('/createPost', Middleware.initFireBase, function(req, res) {
var refs = req.refs;
refs.inbox.push({}) // etc
....
This middleware will soon be extended to provide Firebase.auth() on the connection to ensure that any API call made with a valid authToken would be signed to the user on Firebase's side. However for development this is acceptable.
Hopefully this helps someone.

Resources