sqlnode.jsphppgadmin

Authentication with nodejs


I have a problem to make login work in my nodejs app. When I authenticate even if I enter the wrong user I have my page home render:

This is my code for the authentication:

app.post('/auth', urlencodedParser, function(req, res) {
    var username = "'" + req.body.usernames + "'";
    var password = "'" + req.body.passwords + "'";
    var client = new Client(conString);
    client.connect();
    if (username && password) {
        client.query('SELECT * FROM Utilisateur WHERE username = ? AND password = ?', [username, password],function(err, results) {
            if (err) {
               console.log('error running the authentication:', err);
            }
            results = JSON.parse("[{},{}]")
            if (results.length > 0) {
                req.session.loggedin = true
                req.session.username = username
                res.render('home')
            }
        });
    }
});

Solution

  • Use sql library instead of client.

    app.post('/auth', urlencodedParser, function(req, res) {
            var username = "'" + req.body.usernames + "'";
            var password = "'" + req.body.passwords + "'";
            var mysql = require('mysql');
            var con = mysql.createConnection({
              host: "localhost",
              user: "yourusername",
              password: "yourpassword",
              database: "mydb"
           });
    
            if (username && password) {
                con.connect(function(err) {
                     if (err) throw err;
                     con.query('SELECT * FROM Utilisateur WHERE username = ? AND password = ?', [username, password],function(err, results) {
                        if (err) {
                            console.log('error running the authentication:', err);
                        }
                        results = JSON.parse("[{},{}]")
                        if (results.length > 0) {
                            req.session.loggedin = true
                            req.session.username = username
                            res.render('home')
                        }
                     });  
                });
            }
        });