Saturday, 13 May 2017

Creating a user session - NODE js

I am new to node js & javascript in general. I have the below piece of code that will handle a login. I have a MYSQL database with a customer table. When the customer enters their username and password, it checks does it exist in the database. This part is working.

I now want to enhance this feature so that it will take the username and create some sort of a session variable, which can be used across the application. I am new to JS so I am not yet sure which inbuilt facilities already exist, or best practice around sessions.

I want to be able to use this session variable across the application, and for subsequent logout facility.

Can someone advise me on this, or point me in the right direction? Thanks.

case "/login":

var body = '';

console.log("user Login ");

request.on('data', function (data) {
    body += data;
});

request.on('end', function () {
    var obj = JSON.parse(body);
    console.log(JSON.stringify(obj, null, 2));
    var query = "SELECT * FROM Customer where name='"+obj.name+"'";
    response.writeHead(200, {
        'Access-Control-Allow-Origin': '*'
    });

    db.query(
        query,
        [],
        function(err, rows) {
            if (err) {
                response.end('{"error": "1"}');
                throw err;
            }
            if (rows!=null && rows.length>0) {
                console.log(" user in database" );
                theuserid = rows[0].customerID;
                var obj = {
                    id: theuserid
                }
                response.end(JSON.stringify(obj));

            }
            else{
                response.end('{"error": "1"}');
                console.log(" user not in database");
            }

        }
    );
});

}



via DaveMac001

No comments:

Post a Comment