Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var bcrypt = require('bcryptjs');
- var cookieParser = require('cookie-parser');
- var session = require('express-session'); //this will allow us to store a users information as a cookie
- var RedisStore = require("connect-redis")(session);
- var express = require('express');
- var router = express.Router();
- var app = express();
- var http = require('http').Server(app);
- var io = require('socket.io')(http);
- var sessionio = require("socket.io")(http);
- var bodyParser = require('body-parser');
- var hour = 3600000;
- var zero = 0;
- var listenPort = 80;
- var mongoose = require('mongoose');
- mongoose.connect('mongodb://localhost/data');
- http.listen(listenPort, function(){
- console.log('listening on *:' + listenPort);
- });
- app.use(session({
- cookieName: 'session',
- store: new RedisStore({}),
- secret: 'qwtwet7ew9e77qw86QWF85QW9FQ6W78F', //random string to protect the cookie's information
- duration: 30 * 60 * 1000, //in milliseconds
- activeDuration: 5 * 60 * 1000, //absolute limit, up to 30 minutes. Each page request will lenghthen the session by five minutes.
- cookie: {httpOnly: false},
- resave: true,
- saveUninitialized: true
- //secure: true //enable this if we want cookies to only be stored over a http connection
- //httpOnly: enable if you want the browser to be able to exacute javascript and use cookies
- //ephemeral: true
- }));
- sessionio.use(function(socket, next) {
- session(socket.request, socket.request.res, next);
- });
- sessionio.sockets.on("connection", function(socket) {
- console.log(socket.request.session);
- });
- app.use('/public/', express.static(__dirname + '/public/'));
- app.use('/public/js', express.static(__dirname + '/public/js'));
- app.use('/views/', express.static(__dirname + '/views/'));
- app.use(bodyParser.json());
- app.set('view engine', 'jade'); //Template engine is to be jade
- app.locals.pretty = true; //make the source code pretty (redability)
- //io.use(ios(session)); // session support for sockets
- /*
- io.on('connection', function(socket)
- {
- socket.on('chat message', function(msg)
- {
- var jsonString = []
- io.emit('chat message', msg);
- });
- });*/
- /////////////////////////////////////////////////////////////////////////////////////
- //*User registeration and other processes involved in registeration and logging in*//
- /////////////////////////////////////////////////////////////////////////////////////
- //Mongoose database user model and Schema
- var Schema = mongoose.Schema;
- var ObjectId = Schema.ObjectId;
- var User = mongoose.model('user', new Schema({ //Define object user, mongoose model of a 'User' in a database, Mongoose can access it internally by specificying what model we're using, hence model('user') and the schema for that user.
- id: ObjectId, //This is a listed field, Mongodb Id
- username: { type: String, unique: true }, //username is a unique string preventing multiple users with the same name
- password: String, //another listed field for the users password
- }));
- //use the middleware body-parser
- //express middleware, before we run any requests to the server, we'll take the body of the http request and run it through the body-parser function first.
- app.use(bodyParser.urlencoded({extended: true }));
- app.use(cookieParser());
- app.use(router);
- app.get('/', function(req, res) {
- res.render('index.jade');
- });
- app.get('/register', function(req, res) {
- res.render('register.jade');
- });
- //register a user to the database
- app.post('/register', function(req, res){
- var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10)); //We will use this to hash our users passwords
- var userData = new User({
- username: req.body.username,
- password: hash,
- });
- userData.save(function(err){
- if (err) {
- var err = "Register function error.";
- if (err.code === 11000/*This is the error code MongoDB returns if a unique string was found to already exist in the DB*/) {
- error = "That username is already in use, please try another."
- }
- res.render('register.jade', {error: error}); //If there is an error with the saving of the user, show them one of the two errors.
- } else {
- res.redirect('/');
- }
- })
- });
- app.get('/login', function(req, res) {
- res.render('login.jade');
- });
- //post handler for logging in
- app.post('/login', function(req, res)
- {
- User.findOne ({username: req.body.username}, function(err, userData){ //check the collection User and 'findOne' user by looking for the unique string username to identify who is logging in
- if (!userData)
- { //if the username does not much the password then:
- res.render('login.jade', { error: 'Invalid username or password'});
- }
- else
- {
- if (bcrypt.compareSync(req.body.password, userData.password))
- { //else if both the password in the form being submitted and the collection 'User.password' is the same, redirect to the chatroom and Confirm login.
- req.session.userData = userData; //set-cookie: sessions="encrypedInformation" e.g. username, password.
- res.redirect('/chatroom'); //will set a response to the above and ha
- }
- else
- { //if the password does not match the username then:
- res.render('login.jade', { error: 'Invalid username or password'});
- }
- }
- });
- });
- app.get('/chatroom', function(req, res) {
- if (req.session && req.session.userData) { //if the session exists and the session of the current user exists
- User.findOne({ username: req.session.userData.username }, function(err, userData){ //then find the username of the user using the session and check to see if the sesson cookie is equal to the session user
- if(!userData){ //if user isn't found then redirect to login
- req.session.destroy();
- res.redirect('/login');
- } else {
- req.session.cookie.expires = new Date(Date.now() + hour);
- res.locals.userData = userData; //sets an object pass to our jade rendering engine in the app 'index.js'. In the render they're global variables thus they do not need to be prepend to use.
- res.render('chatroom.jade', {message: "Session id: "+req.sessionID});
- }
- });
- } else {
- res.redirect('/login');
- }
- });
- io.on('connection', function(socket)
- {
- console.log(req.sessionID);
- console.log('=============================================');
- console.log(socket.handshake.session);
- socket.emit('message', "Session id: " + socket.handshake.session); // this will echo session above
- });
- app.get('/logout', function(req, res) {
- req.session.destroy();
- res.redirect('/');
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement