Login with Twitter using passport.js in node.js not working

2.2k views Asked by At

I am using passport.js for twitter login in node.js. But it is not working. It is stay in process for sometime, then return without error or success.

My Code:

module.exports.loginWithTwitter = function (req, res) {

var passport = require('passport');
var Strategy = require('strategy');
var TwitterStrategy = require('passport-twitter').Strategy;

// used to serialize the user for the session
passport.serializeUser(function (user, done) {
    done(null, user.id);
});

// used to deserialize the user
passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
        done(err, user);
    });
});

passport.use(new TwitterStrategy({
    consumerKey: "HMtGdCax3EMhUAikCi2uySwoQ",
    consumerSecret: "QZlWEdjVbPkWPr7cfS6ohbZgNAkpiboRbP0HGaiv1AvTJRtATw",
    callbackURL: "http://192.168.0.102:4000/api/userData/get"
}, function (token, tokenSecret, profile, cb) {
    console.log('call');
    process.nextTick(function () {
        console.log(profile);
    });
}));
}

I am not getting "console.log('call');" call.

My App.js Code

var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    mongoose = require('mongoose'),
    http = require('http'),
    cors = require('cors');


app.use(cors());

app.use(function(req, res, next) {
    var allowedorigins = ['http://localhost:4000'];
    var origin = req.headers.origin;
    //if (allowedorigins.indexof(origin) > -1) {
    //    res.setheader('access-control-allow-origin', origin);
    //}
    res.header("access-control-allow-credentials", "true");
    res.header("access-control-allow-headers", "x-requested-with");
    res.header("access-control-allow-headers", "origin, x-requested-with, content-type, accept,application/x-www-form-urlencoded");

    next();
});

app.get('/', function(req, res) {
    res.setHeader('Content-Type', 'application/json,application/x-www-form-urlencoded');
    res.send(JSON.stringify({
        Server: "A"
    }));
});

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

app.get('/auth/twitter/callback', passport.authenticate('twitter', {
    failureRedirect: '/login'
}), function(req, res) {
    console.log('callback')
        // Successful authentication, redirect home.
    res.redirect('/');
});

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Eviral'); // mongo DB Connection

var server = app.listen(4000);
var router = express.Router();
app.use(bodyParser.urlencoded({
    limit: '100mb',
    extended: true
})); // configure app to use bodyParser() this will let us get the data from a POST
app.use(bodyParser.json({
    limit: '100mb'
}));


app.use(function(req, res, next) {
    var _send = res.send;
    var sent = false;
    res.send = function(data) {
        if (sent) return;
        _send.bind(res)(data);
        sent = true;
    };
    next();
});

app.use(express.static(__dirname));
app.use(require('./routes/clientMSTRoute'));
1

There are 1 answers

0
Ravi Shankar Bharti On

You have not initialized passport in your app.js. You need to configure passport, before using its authentication strategies.

Also, you need to initialize express-session to create login sessions for you users.

Add these lines in your app.js. Ingore whatever you already have some of them. But, make sure you maintain the order.

app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'your_secret_keyword' }));
//Below two lines are required to initialize passport
app.use(passport.initialize());
app.use(passport.session());//this should come after express-session  
                            //to ensure login session is restored in correct order

Make sure you import all the required node modules. Below are the one's required for these. Add those you dont already have in your app.js

var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var passport = require('passport');

Please read passport configure documentation for more information.