401 Unauthorized error when connecting to custom MySQL database

Hey all,

I’m trying to make a custom database connection. Our database is MySQL and it’s hosted on a webserver, which means we need to be able to SSH into it. Here’s my login action script, which uses the mysql-ssh library:

function login(email, password, callback) {
	const mysqlssh = require('mysql-ssh');
	const bcrypt = require('bcrypt');

	mysqlssh.connect(
	{
		host: "<host IP>",
		port: 3822,
		user: "root",
		password: "<password>"
	}, 
	{
		host: "localhost",
		user: "root",
		password: "<password>",
		database: "user-db",
	})
	.then(client => {
		var query = 'SELECT id, username, email, password FROM users WHERE email = ?';
			
		client.query(query, [ email ], function(err, results, fields) {
			if (err) return callback(err);
			if (results.length === 0) return callback(new WrongUsernameOrPasswordError(email));
			const user = results[0];

			bcrypt.compare(password, user.password, function(err, isValid) {
				if (err || !isValid) return callback(err || new WrongUsernameOrPasswordError(email));

				callback(null, {
					user_id: user.id.toString(),
					username: user.username,
					email: user.email
				});
			});

			mysql.close();
		});
	})
	.catch (err => {
		return callback(err);
	});
}

When I save & try it, it comes back with “401 - Unauthorized”. I’ve checked and there is no firewall on our webserver.

Any help with this issue would be appreciated. Thanks!

The problem was the username and password I was trying to authenticate with didn’t exist in the database. I don’t know if the “401 - Unauthorized” is the error I should be getting back in this case, but that is something for another topic.

1 Like

Glad you have figured it out and thanks for sharing with the rest of community!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.