DEV Community

Cover image for Twitter authentication using nodejs ejs template and mysql
Pankaj Kumar
Pankaj Kumar

Posted on • Updated on

Twitter authentication using nodejs ejs template and mysql

Hey guys, Since day by day login using social media is getting popular so, Today I am going to discuss login with twitter step by step. So at first we need to create a twitter app, since we need client ID and client secret to intigrate in our code.

So go to Twitter and after login into your account create an app. And fill the basic details asked there and put callback url : http://localhost:3000/auth/twitter/callback for performing the task from local system. Once app is created over twitter, Copy API KEY and API SECRET which is required to authenticate the app.

Now lets come to the next step:

So let's have a look on our Package.json of our nodejs app. Where we have defined all the the dependencies of our application and basic information of the app.


{
  "name": "twitter-authentication-nodjs-app",
  "description": "twitter-authentication demo",
  "main": "server.js",
  "author": "Suraj Roy",    
  "version": "0.0.1",
  "dependencies": 
    {
        "express": "4.8.7",        
        "body-parser": "1.7.0",
        "cookie-parser": "1.3.2",
        "express-session": "1.7.6",            
        "ejs": "1.0.0",
        "mysql": "2.4.3"
      }
}

Enter fullscreen mode Exit fullscreen mode

Now let's move to the next part, where we will configure the credentials needed for our application.


module.exports={
    "twitter_api_key" : " YOUR CLIENT ID",
    "twitter_api_secret"    :    "CLIENT SECRET HERE",
    "callback_url"    :    "http://localhost:3000/auth/twitter/callback",
    "host"  :    "localhost",
    "username"    :    "root",
    "password"    :    "root",
    "database"    :    "demo_twitter_login"
}


Enter fullscreen mode Exit fullscreen mode

In the above file we have provided the credentials needed for our app.

Now in the next step we will set import the mysql db.


CREATE TABLE user_master
(
user_id BIGINT(30) NOT NULL,
user_name VARCHAR(100) NOT NULL,
PRIMARY KEY(user_id)
);

Enter fullscreen mode Exit fullscreen mode

We have just created the basic fields here, you can make as per the requirement of your application.

Now lets come to nodejs part Server.js, where intially we will have a serve.js file where every task happens. Let's have a look.


let express = require('express'), 
    app = express(),
    passport = require('passport'),
    TwitterStrategy = require('passport-twitter').Strategy,
    session = require('express-session'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    mysql = require('mysql');

let util = require('util'),
    config = require('./utils/config');

// Set database connection with the credentials in config.
var connection = mysql.createConnection({
    host     : config.host,
    user     : config.username,
    password : config.password,
    database : config.database
});

connection.connect(); // set db connection...

app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(session({ secret: 'jsonworldthebestplatformfordemo'})); // session secret
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));

/************************************************************************
 *********** PASSPORT SETTINGS STARTS HERE  *************************
 ***********************************************************************/

// 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 id...
          if(config.use_database==='true'){
              connection.query("SELECT * from user_master where user_id="+profile.id,function(err,rows,fields){
              if(err) throw err;
              if(rows.length===0){  
                  console.log("There is a new user");
                  connection.query("INSERT into user_master(user_id,user_name) VALUES('"+profile.id+"','"+profile.username+"')");
              }else{
                  console.log("User already registered in database");
              }
              });
          }
          return done(null, profile);
      });
  }
));

/************************************************************************
 ***************** PASSPORT SETTINGS ENDS HERE  ************************* 
 ***********************************************************************/

app.get('/', function(req, res){
    res.render('index', { 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);

Enter fullscreen mode Exit fullscreen mode

In the above file intially, we have included package of nodejs needed for any basic nodejs appliication. After that we have created mysql db connection and then se the ejs as view engine and set session secret. Below that passport related task goes on where we authenticate user with twitter and then check the user whether exists in our database or not. if not exists data is inserted into database. otherwise user login successfully.

At the end type node server.js At and type http://localhost:3000/ on your browser.

You can download the zipped code from here and then directly use after changing the basic settings.

Hope you get it easily. Thanks alot!

This article is originally posted over jsonworld

Top comments (0)