Request Handler: ReqHndlr.js

Importing external modules
var fbdata=require('./FBconnector')
var garybot=require('./Garybot')
var http=require('http')
var url=require('url');
var fs=require("fs");
"securityTokens" are getting from facebook. There will be unique security code for each user. We'll insert this security code into "securityTokens" array and uses it as a Cookie.
"fbstatecodes" are guids generated by our application and passes to Facebook while client login. When login is success, Facebook redirects to our page and will show this state code. We can check this state code to confirm that this is our user.
securityTokens=[]
fbstatecodes=[]
This function handles requests to our application
function handleRequest(req,res){	
	var requestURL=url.parse(req.url,true);
	var urlQuery=requestURL.query			
	if(requestURL.pathname==="/"){
		
		if(urlQuery!==undefined){			
		
			if(urlQuery.code!==undefined){		
				
				if(validateState(urlQuery.state)==true){														
					//Hooooooooray  New User 				
					var cookie=urlQuery.code				
					securityTokens.push(cookie.toString())
					console.log('set profile data')
					fbdata.setProfileData(cookie.toString())
					//Everything okay! serve page 
					console.log("Everything okay! serve page ")					
					fs.readFile("./views/index.ejs",function(error,content){
						if(error){
							res.write("error while fs"+error);
							res.end();
						}
						else{						
							res.writeHead(200,{'Content-Type':'text/html'});												
							res.writeHead(200,{'Set-Cookie':cookie});												
							res.end(content,'utf-8');
						}
					});							
				}
				else{
					res.writeHead(200,{'Content-Type':'text/html'});												
					res.writeHead(200,{'Set-Cookie':cookie});																						
					res.end('<html>Invalid Attempt!!! Click <a href="http://sharp-window-7156.herokuapp.com/login?avoidcache='+Math.random().toString()+'"">here</a> to login.</html>','utf-8');
				}				
			}						
		}
	}
	
Handling login requests. Reponse with 301 status to redirect user for Facebook authentication. We'll also create & pass a guid state code to facebook.
	else if(requestURL.pathname==="/login"){
		var guid=GUID()
		fbstatecodes.push(guid.toString())
		res.writeHead(301,{'Content-Type':'text/html'});					
		res.writeHead(301,{'Location':'https://facebook.com/dialog/oauth?client_id=YOURAPPCLIENTID&redirect_uri=https://sharp-window-7156.herokuapp.com/&state='+guid.toString()})
		res.end();						
	}	
	
Handling logout requests. It is important to logout the user from Facebook also. Redirect user to Facebook logout with his "access token". For building the full logout url(including client access token) we need FBconnector service.
	
	else if(requestURL.pathname==="/logout"){	
		if(req.headers.cookie){
			res.writeHead(301,{'Content-Type':'text/html'});									
			res.writeHead(301,{'Location':fbdata.logout(req.headers.cookie.toString())})
		}
		res.end();						
	}
	
Getting Recent Users. Specify the index for users list and FBconnector will give the users from that index. Just pass the result to user.
	
	else if(requestURL.pathname==="/recentusers"){		
		res.writeHead(200,{'Content-Type':'text/plain'});																					
		if(urlQuery.index!==undefined && !isNaN(urlQuery.index*1)){
			var recentusers=fbdata.recentUsers(urlQuery.index*1);			
			console.log(recentusers)		
			res.end(recentusers.toString())
		}
		else{
			res.end("")
		}		
	}
	
This part is responsible for setting User Name in the page, setting logout link, and poking Gary bot to send a welcome message to user.
	
	else if(requestURL.pathname==="/welcome"){		
		var name=''
		if(req.headers.cookie){
			console.log("Welcome")
			var profile_data=fbdata.getProfileData(req.headers.cookie.toString())
			if(profile_data){
				var name=profile_data.name.toString()		
				garybot.garyWelcome(name)				
				res.writeHead(200,{'Content-Type':'text/plain'});																										
				name='<a href="https://www.facebook.com/" target="_blank">'+name+'</a>'	
			}
		}
		res.end(name)
	}	
}
Validating the facebook request while client logging. Checking that state code from facebook request is already registered from our application.
function validateState(state){
	for(guid in fbstatecodes){
		//fbstatecodes.pop(guid)
		return true;
	}
	return false;
}
Creating GUID for state code.
function GUID(){
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0,v=c=='x'?r:r&0x3|0x8;
	return v.toString(16);});
}
Export this file as a node module
exports.handleReq=handleRequest;