Home
Tools
Workshops
Technologies
Pricing
Contact Us



Sign in using Facebook in Sailsjs apps

Part-2 Setting up Sailsjs App

Prerequesities
It is assumed that you already have following installed on your local machine.
  1. node.js
  2. npm
  3. sails.js
    
    $ npm install sails  
    
  4. request
    
    $ npm install request   
    
Apart from this, you should also be aware of basic npm and sails commands.
Create your sails application
To start with, lets create a sails project with the name fbauth and then create a controller user. Following are the commands you need to type into your shell.

$ sails new fbauth
$ cd fbauth
$ sails generate api user  
Our sails application project is now ready and the directory structure of the app looks like the one shown below.

fbauth 
|-.tmp
|-api
|-assets
|-config
|-node_modules
|-tasks
|-views
|-.sailsrc
|-app
|-Gruntfile
|-package
|-README  
Add signup/login page
Now its the time to create a view which hold the markup for our sign in using facebook page. To do this we need to create a new directory called user in the views directory of our app. After creating this directory we need to create a new file index.ejs and add our code to it as shown below.

$ cd views
$ mkdir user
$ touch index.ejs   
Now open the index.ejs file using your favorite code editor and add following code to it.

<h1> Login / Register using Facebook </h1>
		<a href="/user/facebook"> <button> Facebook </button> </a>
Setup actions and routing
We have created our view page. Now we need to do 2 things:
  1. As an action in user controller which returns this page
  2. Add a route in the config/route.js file which routes to the the controller action
First lets edit the user controller file. You can find the UserController.js file in the api/controllers directory. Just open it using your editor of choice and add following code. Make sure to avoid mistakes arising from misplaced commas.

module.exports = {
	
	'index': function(req,res) {
		return res.view();
	}

};
Now open the routes.js file in the config directory present in the root of your project and add following lines to it.

module.exports.routes = {
	
	 '/': 'UserController.index',

};
Go ahead and test what you have done so far by running your app on port 80. After your app start successfully you should be able to see something similar to the screen shot shown below.

$ sails lift --port 80
  
As soon as the user clicks on facebook link button, 'facebook' action in our 'User Controller' is called. Let's setup this action to return facebook sign in page. just add an action named facebook as shown below. Please make sure to replace CLIENT_FACEBOOK_ID with your own facebook client id.

module.exports = {
	
	// api/controllers/UserController.js 
	 
	'index': function(req,res) {
		return res.view();
	},
	'facebook': function(req,res) {
		return res.redirect('https://www.facebook.com/dialog/oauth?client_id=' + CLIENT_FACEBOOK_ID + '&redirect_uri=' + 'http://localhost/home');
	}

};
So far so good. Once the user enters their credentials and facebook authenticates a user it redirects the browser to the redirect url i.e.

   'http://localhost/home' 
along with a code. Now our job is to setup a route which points above route to UserController.home action and secondly we need to setup the action UserController.home
Edit following files as directed.

// config/routes.js 
module.exports.routes = {
	
	 '/': 'UserController.index',

};

module.exports = {
	
	// api/controllers/UserController.js 
	 
	'index': function(req,res) {
		return res.view();
	},
	'facebook': function(req,res) {
		return res.redirect('https://www.facebook.com/dialog/oauth?client_id=' + CLIENT_FACEBOOK_ID + '&redirect_uri=' + 'http://localhost/home');
	},
	
	// make sure to replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your actual client id and secret. You can copy these from facebook app dashboard. 
	'home': function(req,res) {
		if (req.param('code'))
		{
			var code = req.param('code');
			// exchange the code for an access token 
			request('https://graph.facebook.com/v2.3/oauth/access_token?client_id='+YOUR_CLIENT_ID+'&redirect_uri='+'http://localhost/home&client_secret='+'YOUR_CLIENT_SECRET&code='+code, function(error,response,body){
					if(error || response.statusCode != 200 )
					{
						return res.json({
							Message: 'Failed to sign in using Facebook',
							Error: error,
							Description: body 
						});
					}
					else if(!error && response.statusCode == 200)
					{
						return res.json({
							Message: 'Successfully signed in using facebook',
							Result: body 
						});
					}
						
			});
		}
		else if(req.param('error'))
		{
			var error_description = req.param('error_description');
			return res.json({
				Message: 'Failed to login using Facebook',
				Error: error_description 
				
			});
		}
	}

};
Once we have the above files setup our flow is ready. Note that we're returning the access token as the response only for understanding in this workshop. Go ahead and run your app.

$ sails lift --port 80
  
In practice we never return access token, instead we use it to get details about users profile etc. We should store this access token in a secure manner on the server. And we should make additional calls to the server using this access token.
Homework
We have covered the basics of how login flow works but there is still a lot to be done. We need to create a session and store the login status of the user in that session. We can use sails sessions or a key value pair like redis for the same. But for this workshop we'll leave managing sessions to the reader.






developed & nourished with by rishabh.io