Skip to content

Instantly share code, notes, and snippets.

@dvideby0
Created March 5, 2013 15:10
Show Gist options
  • Save dvideby0/5090954 to your computer and use it in GitHub Desktop.
Save dvideby0/5090954 to your computer and use it in GitHub Desktop.
This is an example of using MongoDB, Express to have simple API with security
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");
var users = db.collection("users");
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){ // This function will check our collection to see if the session exists
sessions.findOne({SessionID: session},{_id:0}, function(err, post) {
if(!post){
callback(null); // If it does not find a record it returns a null response in our callback
}
else{
sessions.update({SessionID:session}, {$set:{ttl:new Date()}}, function(){ // This refreshes the session so it wont expire for another 60 seconds
callback(post); // This sends back the session to the function requesting it via a callback
});
}
})
}
// 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('/usersbyfirstname', 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
// This makes a query to a collection you have named "users" and looks for all users that have a first name
//that matches your query parameter "firstname". So your request would look like http://localhost:4687/usersbyfirstname?firstname=Seth
users.find({FistName: req.query.firstname}, {_id:0}).toArray(function(err, array){ // here we take the results and put them into an array
res.send(200, JSON.stringify({Response: array})); // in our response we send back a JSON string.
});
}
else{
// Do something if the session has expired or does not exist
res.send(401, JSON.stringify({Response: {"Error": "Access Denied", "Message": "Invalid Session"}}))
}
});
});
app.listen(4687); // This is the port our app is listening on. http://localhost:4687
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment