var express = require('express'); var router = express.Router(); /* GET Home / Login Form */ router.get('/', function(req, res) { var util = require('util'); var request = util.inspect(req, {depth: 2}); // If the user isn't logged in if ( ! req.session.uid) { res.render('login', { title: 'Node Task Manager', csrfToken: req.csrfToken() }); } else { res.render('index', { title: 'Node Task Manager', user: req.session.username, req: request }); } }); /* Login action */ router.post('/login', function(req, res) { var bcrypt = require('bcrypt-nodejs'); var user = req.body.user, pass = req.body.pass; req.getConnection(function(err, connection) { if (err) throw err; var sql = " SELECT id, username, email, password, timezone, num_format " + " FROM todo_user " + " WHERE email = ? OR username = ? "; // Find the username / email connection.execute(sql, [user, user], function(err, rows, fields) { if (err) throw err; var user = rows[0]; // Verify the password hash bcrypt.compare(pass, user.password, function(err, passRes) { if (err) throw err; // Password is good, set session data and redirect if (passRes === true) { req.session.uid = user.id; req.session.num_format = user.num_format; req.session.username = user.username; res.redirect(303, '/'); } }); }); }) }); /* Logout action */ router.get('/logout', function(req, res) { // Destroy the session, and redirect to the index page req.session.destroy(function(err) { res.redirect(303, '/'); }); }); module.exports = router;