javascript – Insert and retrieve user using SHA1 hash value in MySQL

05/02/2018


I want to store (insert) and get (retrieve) a password with SHA1 hash algorithm as it is better than storing passwords in plain text. When inserting into the users table in my database, the SHA1 hash is inserted, however upon login it was not successful. Do I need to modify my function codes in my Javascript file?

I am using a HTML Login Form with POST Method.

This calls for the execution of the SQL codes in my function file.

function authenticate(request, respond) {
var input_username = request.body.username; // username from user input
var input_password = request.body.password; // password from user input
var msg = "";

// Call the getLoginDetails function from DB
DB.getLoginDetails(input_username, function(error, result) {

    if (error) {
        respond.json(error);
    } else {
        // If user can be found, result has one record
        if (result.length > 0) {
            if (input_password == result[0].password) {
                msg = "Successful.";
                console.log(msg);
            } else {
                msg = "Failed.";
                console.log(msg);
            }
        } else { // If user not found, result has no record
            msg = "User not found!";
        }

Before changes(DB.js) file.

insertData(user, callback) {

        var sql = "INSERT INTO users (`id`,`username`,`password`) VALUES(?,?,?)";

        db.query(sql, [user.getId(), user.getUsername(), user.getPassword()], callback)
    }



    getLoginDetails(user, callback) {

        var sql = "SELECT password FROM users WHERE username = ?";

        db.query(sql, [user], callback);
    }

After making changes (DB.js) file

    //Insert user with SHA1 algorithm
    insertData(user, callback) {

        var sql = "INSERT INTO users (`id`,`username`,`password`) VALUES(?,?,SHA1(?))";

        db.query(sql, [user.getId(), user.getUsername(), user.getPassword()], callback)
    }


    //Login with SHA1 algorithm
    getLoginDetails(user, callback) {

        var sql = "SELECT SHA1(password) FROM users WHERE username = ?";

        db.query(sql, [user], callback);
    }

قالب وردپرس