Creating a User Database

Next step after my earlier experiments with MongoDB databases was to create a system where users could log on and view their step data from a pedometer. To do this I needed to make a database of users and store their data. To make the database I used Passport.JS a user authentication Node package which would create user sessions. This makes the user’s data more secure by hashing their passwords, so that they can’t be stolen easily.

project structure
The file structure of my project

As the project was going to be quite big, I decided to use Express.js which is a web framework for node. It automatically creates a web app file structure which saves time creating it from scratch. I also used Jade which is a html template engine, which means you can add variables to html more easily to pass through my data.

var mongoose = require('mongoose');

module.exports = mongoose.model('User',{
	id: String,
	username: String,
	password: String,
	previousSteps : Number,
	changeInSteps: Number
	//email: String,
	//firstName: String,
	//lastName: String
});

First off was to create my Mongoose model, with a user id, username, password and a logging system for past steps and the change in steps from yesterday to today.

var login = require('./login');
var signup = require('./signup');
var User = require('../models/user');

module.exports = function(passport){

	// Passport needs to be able to serialize and deserialize users to support persistent login sessions
    passport.serializeUser(function(user, done) {
       // console.log('serializing user: ');console.log(user);
        done(null, user._id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
          //  console.log('deserializing user:',user);
            done(err, user);
        });
    });

    // Setting up Passport Strategies for Login and SignUp/Registration
    login(passport);
    signup(passport);

}

Next was to create user sessions, by serializing and deserializing the user through passport. This creates a “logged on” state for the user.

 function(req, username, password, done) { 
            // check in mongo if a user with username exists or not
            User.findOne({ 'username' :  username }, 
                function(err, user) {
                    // In case of any error, return using the done method
                    if (err)
                        return done(err);
                    // Username does not exist, log the error and redirect back
                    if (!user){
                        console.log('User Not Found with username '+username);
                        return done(null, false, req.flash('message', 'User Not found.'));                 
                    }
                    // User exists but wrong password, log the error 
                    if (!isValidPassword(user, password)){
                        console.log('Invalid Password');
                        return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
                    }
                    // User and password both match, return user from done method
                    // which will be treated like success
                    return done(null, user);
                }

This function checks if a user is registered in the system and tells them what is wrong if their username or password does not match any of the ones that are stored.

loginsignup

 

The sign in and registration page.

I also created pages for users to create a new profile, and a home page to view their information.

home

 

The home page

From the home page I created a method where users can input the number of steps they have walked that day.

/* POST home page */
	router.post('/steps', function(req, res) {

		if (req.user.previousSteps != null) {

			var change = req.body.currentSteps - req.user.previousSteps;

			console.log(change);

			req.user.changeInSteps = change;

			console.log(req.user.changeInSteps);

		}

		req.user.previousSteps = req.body.currentSteps;

		req.user.save();


		res.redirect('/home');
	});

Next I will look at different ways this data can be used.

Passportjs.org, 2015. Passport. [online] Available from: http://passportjs.org/ [Accessed 28 Nov. 2015].

Expressjs.com, 2015. Express – Node.js web application framework. [online] Available from: http://expressjs.com/ [Accessed 28 Nov. 2015].

Jade-lang.com, 2015. Jade – Template Engine. [online] Available from: http://jade-lang.com/ [Accessed 28 Nov. 2015].