Advertisement
Guest User

Untitled

a guest
Jan 20th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.53 KB | None | 0 0
  1. var bcrypt = require('bcryptjs');
  2. var cookieParser = require('cookie-parser');
  3. var session = require('express-session'); //this will allow us to store a users information as a cookie
  4. var RedisStore = require("connect-redis")(session);
  5. var express = require('express');
  6. var router = express.Router();
  7. var app = express();
  8. var http = require('http').Server(app);
  9. var io = require('socket.io')(http);
  10. var sessionio = require("socket.io")(http);
  11. var bodyParser = require('body-parser');
  12. var hour = 3600000;
  13. var zero = 0;
  14. var listenPort = 80;
  15. var mongoose = require('mongoose');
  16. mongoose.connect('mongodb://localhost/data');
  17. http.listen(listenPort, function(){
  18. console.log('listening on *:' + listenPort);
  19. });
  20.  
  21. app.use(session({
  22. cookieName: 'session',
  23. store: new RedisStore({}),
  24. secret: 'qwtwet7ew9e77qw86QWF85QW9FQ6W78F', //random string to protect the cookie's information
  25. duration: 30 * 60 * 1000, //in milliseconds
  26. activeDuration: 5 * 60 * 1000, //absolute limit, up to 30 minutes. Each page request will lenghthen the session by five minutes.
  27. cookie: {httpOnly: false},
  28. resave: true,
  29. saveUninitialized: true
  30. //secure: true //enable this if we want cookies to only be stored over a http connection
  31. //httpOnly: enable if you want the browser to be able to exacute javascript and use cookies
  32. //ephemeral: true
  33. }));
  34.  
  35. sessionio.use(function(socket, next) {
  36. session(socket.request, socket.request.res, next);
  37. });
  38.  
  39. sessionio.sockets.on("connection", function(socket) {
  40. console.log(socket.request.session);
  41. });
  42.  
  43.  
  44. app.use('/public/', express.static(__dirname + '/public/'));
  45. app.use('/public/js', express.static(__dirname + '/public/js'));
  46. app.use('/views/', express.static(__dirname + '/views/'));
  47. app.use(bodyParser.json());
  48. app.set('view engine', 'jade'); //Template engine is to be jade
  49. app.locals.pretty = true; //make the source code pretty (redability)
  50. //io.use(ios(session)); // session support for sockets
  51.  
  52. /*
  53. io.on('connection', function(socket)
  54. {
  55. socket.on('chat message', function(msg)
  56. {
  57. var jsonString = []
  58.  
  59. io.emit('chat message', msg);
  60. });
  61. });*/
  62.  
  63. /////////////////////////////////////////////////////////////////////////////////////
  64. //*User registeration and other processes involved in registeration and logging in*//
  65. /////////////////////////////////////////////////////////////////////////////////////
  66. //Mongoose database user model and Schema
  67. var Schema = mongoose.Schema;
  68. var ObjectId = Schema.ObjectId;
  69.  
  70. 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.
  71. id: ObjectId, //This is a listed field, Mongodb Id
  72. username: { type: String, unique: true }, //username is a unique string preventing multiple users with the same name
  73. password: String, //another listed field for the users password
  74. }));
  75.  
  76. //use the middleware body-parser
  77. //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.
  78. app.use(bodyParser.urlencoded({extended: true }));
  79. app.use(cookieParser());
  80.  
  81. app.use(router);
  82. app.get('/', function(req, res) {
  83. res.render('index.jade');
  84. });
  85.  
  86. app.get('/register', function(req, res) {
  87. res.render('register.jade');
  88. });
  89.  
  90. //register a user to the database
  91. app.post('/register', function(req, res){
  92. var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10)); //We will use this to hash our users passwords
  93. var userData = new User({
  94. username: req.body.username,
  95. password: hash,
  96. });
  97. userData.save(function(err){
  98. if (err) {
  99. var err = "Register function error.";
  100. if (err.code === 11000/*This is the error code MongoDB returns if a unique string was found to already exist in the DB*/) {
  101. error = "That username is already in use, please try another."
  102. }
  103. res.render('register.jade', {error: error}); //If there is an error with the saving of the user, show them one of the two errors.
  104. } else {
  105. res.redirect('/');
  106. }
  107. })
  108. });
  109.  
  110. app.get('/login', function(req, res) {
  111. res.render('login.jade');
  112. });
  113.  
  114. //post handler for logging in
  115. app.post('/login', function(req, res)
  116. {
  117. 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
  118. if (!userData)
  119. { //if the username does not much the password then:
  120. res.render('login.jade', { error: 'Invalid username or password'});
  121. }
  122. else
  123. {
  124. if (bcrypt.compareSync(req.body.password, userData.password))
  125. { //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.
  126. req.session.userData = userData; //set-cookie: sessions="encrypedInformation" e.g. username, password.
  127. res.redirect('/chatroom'); //will set a response to the above and ha
  128. }
  129. else
  130. { //if the password does not match the username then:
  131. res.render('login.jade', { error: 'Invalid username or password'});
  132. }
  133. }
  134. });
  135. });
  136.  
  137. app.get('/chatroom', function(req, res) {
  138. if (req.session && req.session.userData) { //if the session exists and the session of the current user exists
  139. 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
  140. if(!userData){ //if user isn't found then redirect to login
  141. req.session.destroy();
  142. res.redirect('/login');
  143. } else {
  144. req.session.cookie.expires = new Date(Date.now() + hour);
  145. 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.
  146. res.render('chatroom.jade', {message: "Session id: "+req.sessionID});
  147. }
  148. });
  149. } else {
  150. res.redirect('/login');
  151. }
  152. });
  153.  
  154. io.on('connection', function(socket)
  155. {
  156. console.log(req.sessionID);
  157. console.log('=============================================');
  158. console.log(socket.handshake.session);
  159. socket.emit('message', "Session id: " + socket.handshake.session); // this will echo session above
  160. });
  161.  
  162. app.get('/logout', function(req, res) {
  163. req.session.destroy();
  164. res.redirect('/');
  165. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement