Advertisement
Guest User

Untitled

a guest
Mar 4th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. var express = require('express');
  2. var MemoryStore = express.session.MemoryStore;
  3. var sessionStore = new MemoryStore();
  4. var connect = require('connect');
  5. var Session = connect.middleware.session.Session;
  6. var cookie = require('cookie');
  7.  
  8. module.exports.startServer = function() {
  9.  
  10. var app = express();
  11.  
  12. // Configuration
  13. app.configure(function() {
  14. app.use(express.bodyParser());
  15. app.use(express.methodOverride());
  16. app.use(express.cookieParser());
  17. app.use(express.session({
  18. store : sessionStore,
  19. secret : 'secret',
  20. key : 'express.sid'
  21. }));
  22. app.use(express.static(__dirname + '/public'));
  23. app.use(app.router);
  24. });
  25.  
  26. app.configure('development', function() {
  27. app.use(express.errorHandler({
  28. dumpExceptions : true,
  29. showStack : true
  30. }));
  31. });
  32.  
  33. app.configure('production', function() {
  34. app.use(express.errorHandler());
  35. });
  36.  
  37.  
  38.  
  39. // Init routes
  40. app.post('/login', function(req, res){
  41. var credentials = req.body;
  42.  
  43. if (!(credentials.username && credentials.password)){
  44. res.redirect('/login.html');
  45. return;
  46. }
  47.  
  48. if (credentials.username === 'user1' && credentials.password === 'pass1'){
  49. req.session.user = credentials.username;
  50. req.session.clientId = credentials.clientId;
  51. res.redirect('/post-message.html');
  52. }else{
  53. req.session.destroy();
  54. res.redirect('/login.html');
  55. }
  56. });
  57.  
  58. app.post('/postMsg', authenticate, function(req, res){
  59. res.send('posted');
  60. });
  61.  
  62. app.listen(4000);
  63.  
  64. function authenticate(req, res, next) {
  65. // check if there's a cookie header
  66. if (req.headers.cookie) {
  67. // if there is, parse the cookie
  68. req.cookie = cookie.parse(req.headers.cookie);
  69.  
  70. req.sessionID= req.cookie['express.sid'];
  71. // note that you will need to use the same key to grad the
  72. // session id, as you specified in the Express setup.
  73.  
  74. sessionStore.get(req.sessionID, function(err, session) {
  75.  
  76. if (session && session.user) {
  77. // save the session data and accept the connection
  78. req.session = new Session(req, session);
  79. next();
  80. }
  81. else {
  82. //Turn down the connection
  83. res.redirect('/login.html');
  84. }
  85. });
  86. } else {
  87. // if there isn't, turn down the connection with a message
  88. // and leave the function.
  89. res.redirect('/login.html');
  90. }
  91. }
  92. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement