Created
May 4, 2017 18:05
-
-
Save anonymous/a6a65e5db0b623e02be6a534b73fde20 to your computer and use it in GitHub Desktop.
NodeJS and ExpressJS: Using Twitter authentication via Passport
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var path = require('path'); | |
var favicon = require('serve-favicon'); | |
var logger = require('morgan'); | |
var cookieParser = require('cookie-parser'); | |
var bodyParser = require('body-parser'); | |
var passport = require('passport'); | |
var Strategy = require('passport-twitter').Strategy; | |
var session = require('express-session'); | |
passport.use(new Strategy({ | |
consumerKey: 'KKBIawUSE_OWNPJwM', | |
consumerSecret: 'BJCahJjoUSE_OWNTStPFAj', | |
callbackURL: 'http://localhost:3000/twitter/return' | |
}, function(token, tokenSecret, profile, callback) { | |
return callback(null, profile); | |
})); | |
passport.serializeUser(function(user, callback) { | |
callback(null, user); | |
}) | |
passport.deserializeUser(function(obj, callback) { | |
callback(null, obj); | |
}) | |
var app = express(); | |
// view engine setup | |
app.set('views', path.join(__dirname, 'views')); | |
app.set('view engine', 'jade'); | |
// uncomment after placing your favicon in /public | |
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); | |
app.use(logger('dev')); | |
app.use(bodyParser.json()); | |
app.use(bodyParser.urlencoded({ extended: false })); | |
app.use(cookieParser()); | |
app.use(express.static(path.join(__dirname, 'public'))); | |
app.use(session({secret: 'whatever', resave: true, saveUninitialized: true})) | |
app.use(passport.initialize()) | |
app.use(passport.session()) | |
// | |
app.get('/', function(req, res) { | |
res.render('index', {user: req.user}) | |
}) | |
app.get('/twitter/login', passport.authenticate('twitter')) | |
app.get('/twitter/return', passport.authenticate('twitter', { | |
failureRedirect: '/' | |
}), function(req, res) { | |
res.redirect('/') | |
}) | |
module.exports = app;$ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends layout | |
block content | |
if user | |
p Hello #{user.username} | |
img(src=user.photos[0].value) | |
else | |
a(href='/twitter/login') Login using twitter! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment