Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var express = require('express');
- var MemoryStore = express.session.MemoryStore;
- var sessionStore = new MemoryStore();
- var connect = require('connect');
- var Session = connect.middleware.session.Session;
- var cookie = require('cookie');
- module.exports.startServer = function() {
- var app = express();
- // Configuration
- app.configure(function() {
- app.use(express.bodyParser());
- app.use(express.methodOverride());
- app.use(express.cookieParser());
- app.use(express.session({
- store : sessionStore,
- secret : 'secret',
- key : 'express.sid'
- }));
- app.use(express.static(__dirname + '/public'));
- app.use(app.router);
- });
- app.configure('development', function() {
- app.use(express.errorHandler({
- dumpExceptions : true,
- showStack : true
- }));
- });
- app.configure('production', function() {
- app.use(express.errorHandler());
- });
- // Init routes
- app.post('/login', function(req, res){
- var credentials = req.body;
- if (!(credentials.username && credentials.password)){
- res.redirect('/login.html');
- return;
- }
- if (credentials.username === 'user1' && credentials.password === 'pass1'){
- req.session.user = credentials.username;
- req.session.clientId = credentials.clientId;
- res.redirect('/post-message.html');
- }else{
- req.session.destroy();
- res.redirect('/login.html');
- }
- });
- app.post('/postMsg', authenticate, function(req, res){
- res.send('posted');
- });
- app.listen(4000);
- function authenticate(req, res, next) {
- // check if there's a cookie header
- if (req.headers.cookie) {
- // if there is, parse the cookie
- req.cookie = cookie.parse(req.headers.cookie);
- req.sessionID= req.cookie['express.sid'];
- // note that you will need to use the same key to grad the
- // session id, as you specified in the Express setup.
- sessionStore.get(req.sessionID, function(err, session) {
- if (session && session.user) {
- // save the session data and accept the connection
- req.session = new Session(req, session);
- next();
- }
- else {
- //Turn down the connection
- res.redirect('/login.html');
- }
- });
- } else {
- // if there isn't, turn down the connection with a message
- // and leave the function.
- res.redirect('/login.html');
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement