/session.js Secret
Last active
December 14, 2015 11:29
Session Management Using Express, MongoDB (node-mongolian) and NodeJS.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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