Created
November 28, 2013 21:47
-
-
Save missinglink/7698563 to your computer and use it in GitHub Desktop.
minimal express + passport + facebook app
This file contains hidden or 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') | |
| , passport = require('passport') | |
| , FacebookStrategy = require('passport-facebook').Strategy; | |
| var usercache = {}; | |
| var User = function(){} | |
| User.findOrCreate = function( profile, cb ){ | |
| usercache[ profile.id ] = profile; | |
| console.log( usercache ); | |
| return cb( null, profile ); | |
| } | |
| User.findById = function( id, cb ){ | |
| return cb( null, usercache[ id ] ); | |
| } | |
| passport.use(new FacebookStrategy({ | |
| clientID: '...', | |
| clientSecret: '...', | |
| callbackURL: 'http://localhost:3000/auth/facebook/callback' | |
| }, | |
| function(accessToken, refreshToken, profile, done) { | |
| User.findOrCreate( profile, function(err, user) { | |
| if (err) { return done(err); } | |
| done(null, user); | |
| }); | |
| } | |
| )); | |
| app = express(); | |
| app.configure(function() { | |
| app.use(express.static('public')); | |
| app.use(express.cookieParser()); | |
| app.use(express.bodyParser()); | |
| app.use(express.session({ secret: 'keyboard cat' })); | |
| app.use(passport.initialize()); | |
| app.use(passport.session()); | |
| app.use(app.router); | |
| }); | |
| passport.serializeUser(function(user, done) { | |
| done(null, user.id); | |
| }); | |
| passport.deserializeUser(function(id, done) { | |
| User.findById(id, function(err, user) { | |
| done(err, user); | |
| }); | |
| }); | |
| // Redirect the user to Facebook for authentication. When complete, | |
| // Facebook will redirect the user back to the application at | |
| // /auth/facebook/callback | |
| app.get('/auth/facebook', passport.authenticate('facebook')); | |
| // Facebook will redirect the user to this URL after approval. Finish the | |
| // authentication process by attempting to obtain an access token. If | |
| // access was granted, the user will be logged in. Otherwise, | |
| // authentication has failed. | |
| app.get('/auth/facebook/callback', | |
| passport.authenticate('facebook', { successRedirect: '/', | |
| failureRedirect: '/login' })); | |
| app.get('/', function( req, res ){ | |
| res.header( 'Content-Type', 'text/html' ); | |
| res.send( 200, '<html><body><a href="/auth/facebook">Login with Facebook</a></body></html>' ); | |
| }); | |
| app.listen(3000); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Set up the facebook app like this:
