Twitter Login Using Node and MySQL

Twitter Login using node is one of the tedious task that developer’s are facing now, due to the update of Express and Middle-ware depreciation, old code which is now at first page of Google either does not work, or gives a pain to your ass to make it run.

Live Demo Download Code
In this tutorial i am going to cover complete steps from scratch to develop Twitter Login app using Node with Oauth protocol. Listed down are Steps that we are going to follow, you may skip some if you did or know already.

Steps to follow :

  1. Creating Twitter app and getting App ID and App secret ( same as consumer ID and consumer secret).
  2. Creating package.json and installing dependencies.
  3. Configuring the database to store User information.
  4. Configuring the app information.
  5. Coding the Server file.
  6. Running the app.

working

Step 1: Creating Twitter App.

Go to the Twitter apps site and sign-in with your twitter account. Create new app with proper name, put call back URL as http://127.0.0.1:3000/auth/twitter/callback  if you are also testing it on your local machine.

Twitter not do not allow ‘localhost’, so i use this numeric presentation. Doesn’t make any difference by the way.

For you reference here is the screen shot of the app i am going to use for this tutorial.

Screenshot from 2014-09-05 11:58:35

Once the app is created, you can go to API Keys tab and copy API KEY and API secret which we will need to authenticate user from our app.

Step 2: Package.json and Dependencies :

Due to Express update, we are going to use following middle ware externally.

  • body-parser
  • cookie-parser
  • express-session

For Oauth authentication we are using Passport module which is awesome piece of code i have ever encountered. It is super easy and modular to code.

package.json
{
"name": "passport-twitter-examples-signin",
"version": "0.0.1",
"dependencies":
{
"body-parser": "1.7.0",
"cookie-parser": "1.3.2",
"ejs": "1.0.0",
"express": "4.8.7",
"express-session": "1.7.6",
"mysql": "2.4.3",
"passport": "0.2.1",
"passport-twitter": "1.0.2"
}
}

You can install all of these dependencies by typing

npm install

You may require ‘sudo‘ access in Linux or Mac System.

Step 3: Configuring Database (Optional).

For those who want to store the information of user after successful authentication can use this step. Twitter returns the ID of user which is unique and could be stored in database for the further operations.

Open up your phpmyadmin  and create database of proper name. Execute following query to create a User information table.

CREATE TABLE user_info
(
user_id INT(100) NOT NULL,
user_name VARCHAR(100) NOT NULL,
PRIMARY KEY(user_id)
);

By using config.js variable you can specify whether you want to use database or not. For just a testing, you can put it as ‘false‘.

Step 4: Configuring the App information.

For your convenience, i have created one configuration file which stores information about :

  • Twitter app
  • You want to use Database or not
  • Database information

If you don’t want to use database for this app, you can put ‘true‘ or ‘false‘ accordingly. This may be useful if you don’t have MySQL database or you have but do not want to use. Here is a configuration file.

configuration/config.js
module.export={
/*
* This file contains the configurations information of Twitter login app.
* It consists of Twitter app information, database information.
*/


"twitter-api-key" : "PUT YOUR API KEY",
"twitter-api-secret" : "PUT YOUR API SECRET",
"callback-url" : "PUT CALL BACK URL, USE LOCALHOST",
"use-database" : "TRUE OR FALSE",
"host" : "DATABASE HOST, MOSTLY LOCALHOST",
"username" : "DATABASE USER NAME, MOSTLY ROOT",
"password" : "DATABASE PASSWORD, MOSTLY BLANK",
"database" : "DATABASE TO USE FOR STORING INFORMATION"
}

Use callback URL as localhost followed by rest. Don’t use 127.0.0.1 here.

Step 5: Coding the Server and Passport.

Passport is node module for Oauth authentication, and we will be using the same for our purpose. We also need Session, cookie-parser, body-parser in order to run our app.

app.js
var express = require('express')
, passport = require('passport')
, util = require('util')
, TwitterStrategy = require('passport-twitter').Strategy
, session = require('express-session')
, cookieParser = require('cookie-parser')
, bodyParser = require('body-parser')
, config = require('./configuration/config')
, mysql = require('mysql')
, app = express();

//Define MySQL parameter in Config.js file.
var connection = mysql.createConnection({
host : config.host,
user : config.username,
password : config.password,
database : config.database
});

//Connect to Database only if Config.js parameter is set.

if(config.use_database==='true')
{
connection.connect();
}

// Passport session setup.
passport.serializeUser(function(user, done) {
done(null, user);
});

passport.deserializeUser(function(obj, done) {
done(null, obj);
});

// Use the TwitterStrategy within Passport.

passport.use(new TwitterStrategy({
consumerKey: config.twitter_api_key,
consumerSecret:config.twitter_api_secret ,
callbackURL: config.callback_url
},
function(token, tokenSecret, profile, done) {
process.nextTick(function () {
//Check whether the User exists or not using profile.id
if(config.use_database==='true')
{
//Perform MySQL operations.
});
}
return done(null, profile);
});
}
));

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'keyboard cat', key: 'sid'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });
});

app.get('/auth/twitter', passport.authenticate('twitter'));

app.get('/auth/twitter/callback',
passport.authenticate('twitter', { successRedirect : '/', failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});

app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});

function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}

app.listen(3000);

We have to define Passport Strategy in which we provide App ID, App Secret, callback variable. In the tick function we define further operations to be taken care of after successful authentication to user.

Once the user is authenticated, we check the database for the user ID entry, if exists we won’t add new row else we will.

Running the app.

Type

node app.js

to run the application. You can visit http://localhost:3000 to view the app. After successful Twitter Login, you will be redirected to home page with welcome message.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126