Skip to content

Instantly share code, notes, and snippets.

@dvideby0
Last active December 14, 2015 11:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvideby0/284f5589d0a53250ffd1 to your computer and use it in GitHub Desktop.
Save dvideby0/284f5589d0a53250ffd1 to your computer and use it in GitHub Desktop.
Session Management Using Express, MongoDB (node-mongolian) and NodeJS.
var express = require('express');
var uuid = require('node-uuid');
var Mongolian = require("mongolian");
var server = new Mongolian;
var db = server.db("yourdb");
var sessions = db.collection("sessions");
sessions.ensureIndex({ ttl:1 },{ expireAfterSeconds: 60}); //this tells mongo to expire documents in sessions after 60 seconds
var app = express();
app.use(express.bodyParser());
function CheckSession(session, callback){
sessions.findOne({SessionID: session},{_id:0}, function(err, post) {
if(!post){
callback(null);
}
else{
sessions.update({SessionID:session}, {$set:{ttl:new Date()}}, function(){ // This refreshes the session so it wont expire for another 60 seconds
callback(post);
});
}
})
}
// Login function. this is up to you how to handle authenticating users...
function Login(username, pass, callback){
// Do Something with username and pass then send response in callback.
callback(errorResponse, successResponse);
}
// Login API Call
app.post('/login', function(req,res){
//Your application's Login Logic
Login(req.body.UserName, req.body.UserPass, function(err, success){ // In your POST your body needs to contain {UserName: [username], UserPass: [password]} to send to your login function which has a callback of err and success.
if(fail){
res.send(401, JSON.stringify({Response: {"Error": err.name, "Message": "Login Failed"}}))
}
if(success){
sessions.insert({SessionID: SessionID, ttl: new Date()}, function(){ // Create Record in DB for the User Session
res.send(200, JSON.stringify({Response: {SessionID: SessionID}}));
});
}
});
});
// Some API Call
app.get('/someresource', function(req, res){
// API requires that client sends a header named "sessionid" with the session ID as its value. It is accessed via req.headers.sessionid
CheckSession(req.headers.sessionid, function(result){
if(result){
// Do something if the session exists
}
else{
// Do something if the session has expired or does not exist
}
});
});
app.listen(4687);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment