Я пытаюсь создать API входа / регистрации с помощью nodejs, express и mysql. При тестировании я не получаю ошибок и получаю "Успешная регистрация!" сообщение. Однако, когда я проверяю базу данных, таблица пользователей все еще пуста.
Вот запрос, который я пытаюсь выполнить.
con.query("INSERT INTO user (unique_id, email, encrypted_password, salt, created_at, updated_at) VALUES (?,?,?,?,NOW(),NOW())",[uid, email, password, salt], function (err, result, fields) {
con.on('error', function (err) {
console.log('[MySQL ERROR]',err);
res.json('Resgister Error: ',err);
});
res.json('Succesful Sign Up!');
})
А вот полный код.
//Libraries
var crypto = require('crypto');
var uuid = require('uuid');
var express = require('express');
var mysql = require('mysql');
var bodyParser = require('body-parser');
//connection with MySQL
var con = mysql.createConnection({
host: "localhost",
user: "user",
password: "password",
database: "database",
});
//Encrypting password
var genRandomString = function (length) {
return crypto
.randomBytes(Math.ceil(length / 2))
.toString('hex')
.slice(0, length);
};
var sha512 = function (password, salt) {
var hash = crypto.createHmac('sha512', salt);
hash.update(password);
var value = hash.digest('hex');
return {
salt: salt,
passwordHash: value,
};
};
function saltHashPassword(userPassword) {
var salt = genRandomString(16);
var passwordData = sha512(userPassword, salt);
return passwordData;
}
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Sign up
app.post('/register/', (req, res, next) => {
var post_data = req.body;
var uid = uuid.v4();
var plaint_password = post_data.password;
var hash_data = saltHashPassword(plaint_password);
var password = hash_data.passwordHash;
var salt = hash_data.salt;
var email = post_data.email;
con.query("SELECT * FROM user where email=?", [email], function (err,result,fields) {
con.on('error', function (err) {
console.log('[MySQL ERROR]', err);
});
if (result && result.length)
res.json('User already exists');
else
{
con.query("INSERT INTO user (unique_id, email, encrypted_password, salt, created_at, updated_at) VALUES (?,?,?,?,NOW(),NOW())",[uid, email, password, salt], function (err, result, fields) {
con.on('error', function (err) {
console.log('[MySQL ERROR]',err);
res.json('Resgister Error: ',err);
});
res.json('Succesful Sign Up!');
})
}
});
})
//Login
app.post('/login/', (req, res, next) =>{
var post_data = req.body;
var user_password = post_data.password;
var email = post_data.email;
con.query("SELECT * FROM user where email=?", [email], function (err,result,fields) {
con.on('error', function (err) {
console.log('[MySQL ERROR]', err);
});
if (result && result.length)
{
var salt = result [0].salt;
var encrypted_password = result[0].encrypted_password;
var hashed_password = checkHashPassword(user_password,salt).passwordHash;
if(encrypted_password==hashed_password)
res.end(JSON.stringify(result[0]))
else
res.end(JSON.stringify('Wrong Credentials'))
}
else
{
res.json('Wrong Credentials')
}
});
})
app.listen(3000, () => {
console.log("RESTFul API running in port 3000");
});