GithubHelp home page GithubHelp logo

passport / todos-express-facebook Goto Github PK

View Code? Open in Web Editor NEW
357.0 13.0 234.0 421 KB

Todo app using Express and Passport for log in with Facebook.

License: The Unlicense

JavaScript 34.66% EJS 20.52% CSS 44.82%
express passport facebook example nodejs sqlite oauth2

todos-express-facebook's Introduction

This example demonstrates how to use Express 4.x and Passport to log users in with Facebook. Use this example as a starting point for your own web applications.

Quick Start

To get started with this example, clone the repository and install the dependencies.

$ git clone [email protected]:passport/express-4.x-facebook-example.git
$ cd express-4.x-facebook-example
$ npm install

This example requires credentials from Facebook, which can be obtained by creating an app in the App Dashboard. The OAuth redirect URI of the app should be set to: http://localhost:3000/oauth2/redirect/www.facebook.com

Once credentials have been obtained, create a .env file and add the following environment variables:

FACEBOOK_CLIENT_ID={{INSERT_APP_ID_HERE}}
FACEBOOK_CLIENT_SECRET={{INSERT_APP_SECRET_HERE}}

Start the server.

$ npm start

Navigate to http://localhost:3000.

Overview

This example illustrates how to use Passport and the passport-facebook strategy within an Express application to log users in with Facebook.

The example builds upon the scaffolding created by Express generator, and uses EJS as a view engine and plain CSS for styling. This scaffolding was generated by executing:

$ express --view ejs express-4.x-facebook-example

The example uses SQLite for storing user accounts. SQLite is a lightweight database that works well for development, including this example.

Added to the scaffolding are files which add authentication to the application.

  • boot/db.js

    This file initializes the database by creating the tables used to store user accounts and credentials.

  • boot/auth.js

    This file initializes Passport. It configures the Facebook strategy and supplies the serialization functions used for session management.

  • routes/auth.js

    This file defines the routes used for authentication. In particular, there are three routes used to authenticate with Facebook:

    • GET /login

      This route renders a page that prompts the user to login with Facebook.

    • GET /login/federated/www.facebook.com

      This route begins the authentication sequence by redirecting the user to Facebook.

    • POST /oauth2/redirect/www.facebook.com

      This route completes the authentication sequence when Facebook redirects the user back to the application. When a new user logs in, a user account is automatically created and their Facebook account is linked. When an existing user returns, they are logged in to their linked account.

License

The Unlicense

todos-express-facebook's People

Contributors

afhaque avatar balatvm avatar goldylucks avatar gordonhgraham avatar itsjw avatar jaredhanson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

todos-express-facebook's Issues

Getting HTTPS error

FacebookAuthorizationError: Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https://

TypeError: OAuth2Strategy requires a clientID option

PS C:\Users\ferda\dev\web\express-4.x-facebook-example> node server.js
C:\Users\ferda\dev\web\express-4.x-facebook-example\node_modules\passport-oauth2\lib\strategy.js:82
if (!options.clientID) { throw new TypeError('OAuth2Strategy requires a clientID option'); }
^

TypeError: OAuth2Strategy requires a clientID option
at Strategy.OAuth2Strategy (C:\Users\ferda\dev\web\express-4.x-facebook-example\node_modules\passport-oauth2\lib\str
ategy.js:82:34)
at new Strategy (C:\Users\ferda\dev\web\express-4.x-facebook-example\node_modules\passport-facebook\lib\strategy.js:
54:18)
at Object. (C:\Users\ferda\dev\web\express-4.x-facebook-example\server.js:13:14)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)

Add in user storage example

I realise this may be a little out of scope for a passport-facebook demo, but I think it'd make sense to have an example of how you could do storage in a database. Of course it wouldn't be worth setting up a real, persistent database, but it'd be a nice way to give the idea of what to store by using a POJO. I'm coming to this reasonably new to node development, so the less comments I see that say things like "you wouldn't do it this way in a production-ready app", the better. You could probably get rid of most of those comment paragraphs above serialize- and deserializeUser that way too.

Possible solution:

// In a real app, you would use a regular database. 
// Using an in-memory dictionary here as a demo. 
var database = {};
...
passport.use(new FacebookStrategy({
    clientID: FACEBOOK_APP_ID,
    clientSecret: FACEBOOK_APP_SECRET,
    callbackURL: "http://localhost:3000/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, cb) {
    database[profile.id] = profile;
    cb(null, user);
  }
));
...
passport.serializeUser(function(user, cb) {
  cb(null, user.id);
});

passport.deserializeUser(function(id, cb) {
  cb(null, database[id]);
});

For those of us with quite a lot of flexibility, not much context, and who just want to find the "normal way" to implement Facebook login, this would make it much easier to reason about where to drop in our data storage solution.

If you'd be receptive, I'd be happy to submit something like the above as a pull request?

Get Only Token from the Facebook Passport

Hi All,

I am very beginner in using the passport strategy and I just want to get only using the facebook strategy how can I achieve this

Like when I hit my custom API http://localhost:3000/graph/photos this should return me only token how can I get it done

	app.get('/graph/photos', passport.authenticate('facebook', (req, res) => {
		res.send(req.token);
	}));

OUTDATED readme

  1. the command to run should be FACEBOOK_CLIENT_ID=__FACEBOOK_CLIENT_ID__ FACEBOOK_CLIENT_SECRET=__FACEBOOK_CLIENT_SECRET__ node server.js

  2. Default port should go to 8080 rather than 3000 as written in the Readme.md

Documentation request - using accessToken on subsequent graph calls

I've also raised this question regarding accessToken on stackoverflow - hoping for some help.

I am trying to figure out how to make further calls to the facebook graph api using the accessToken provided to function(accessToken, refreshToken, profile, cb) { by the second phase of authentication .

(* - My design assumptions are that the accessToken:

  • doesn't have immediate access to req or res, header or session
  • is on the server, not the client
  • shouldn't be saved to a database as part of the User object, as it is short-lived (session duration)
  • is 'sensitive' data)

I can't find any documentation to suggest how to do this*. Please could the README.md be enhanced to include a best/good practice example of saving and then retrieving the accessToken.

Logging a user out

Hi
How do you log a user out? On subsequent get requests to the server the previous user seems to remain logged in.

Please ignore

Okay, let's disregard this. There seems to be problems using this with cloud9 and I can find others asking for a solution on other websites but it just seems like no one has an answer sadly so I will try Heroku.

Please add failureFlash example

I trying to use failureFlash and can't get it work.

return done(null, false, request.flash('auth', 'This email is already bound to another account'));

That works only with local strategy, not facebook strategy. failureFlash: true is passed to options.
Please add it to example or confirm that it is not supported.
Express 4.

Thanks.

Not able to go to facebook url

Getting this error
Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.
after clicking Login with Facebook link.
Can any one help me with this?

Request Object Lost context

Hi,
I am using facebook strategy with my Node-express app,

Sometimes if multiple users log in simultaneously, request object lost context and we get the wrong user details.

example of route
app.get('/', isLoggedIncheck, checkIfFromFacebook, function(req, res) {

     res.setHeader('x-auth-token1111', 'sfdsdf');
     res.header('x-auth-token1111' , 'sfdsdf' );
//    res.status(200).send(data.user);

     const data = {};
    data.spath =req.protocol + '://' + req.hostname +':'+port+'/';
    
    if (req.user != undefined) {



        data.user = req.user;

            

        data.user.token = jwt.sign({
                id: req.user.userid,
            },
            'secret'
        );

        res.cookie(req.user.username, JSON.stringify(data.user.token));
        res.cookie(req.user.userid, JSON.stringify(data.user.token));

    } else {
        
        
        data.user = '';

    }
    data.server = req.hostname;
    data.min = min;
    data.id = generateId();
    data.ver = version;
    data.port = port;
    data.path = '/explore';
    data.page = 'explore';
    data.curl =req.protocol + '://' + req.hostname;
    data.title = 'Woovly | Bucket List | Discover, Connect and Accomplish';
    data.contrl = 'explore';
    data.meta = {};
    data.meta.storyL = {};
    data.meta.storyL.name = 'home';
    data.meta.storyL.title = '';
    data.uuid = "";
    data.is_set = '';
    var htmlFile = '';
    htmlFile = 'explore.html';
    data.utyp = '';
    res.render(htmlFile, { dt: data });
});

app.get("/getFeatured", checkIfFromFacebook, function(req, res) {

     const data = {};
    data.spath =req.protocol + '://' + req.hostname +':'+port+'/';
    
    if (req.user != undefined) {



        data.user = req.user;



        data.user.token = jwt.sign({
                id: req.user.userid,
            },
            'secret'
        );

        res.cookie(req.user.username, JSON.stringify(data.user.token));
        res.cookie(req.user.userid, JSON.stringify(data.user.token));

    } else {
        
        
        data.user = '';

    }
    console.log(req.headers['x-key']);
    data.server = req.hostname;
    data.min = min;
    data.ver = version;
    data.port = port;
    data.path = "getFeatures";
    data.page = "getFeatures";
    data.curl =req.protocol + '://' + req.hostname+'/getFeatured';
    data.title = "getFeatures";
    data.contrl = "getFeatured";

    data.is_set = "";
    data.user_name = "";
    data.uuid = "";
    data.utyp = "";
    data.meta = {};

    res.render("getFeatures.html", { dt: data });
});

app.get('/auth/facebook', (req, res, next) => {
req.session.redirect = req.query.location;
passport.authenticate('facebook', { scope: ['user_friends', 'user_likes', 'email', 'user_birthday', 'user_location'] })(req, res, next)
});

app.get(
    '/auth/facebook/callback', (req, res, next) => {
        console.log("****************");
        console.log(req.session.redirect);
        if (req.session.redirect == undefined || req.session.redirect == 'undefined')
            req.session.redirect = '/';
        passport.authenticate('facebook', {
            successRedirect: req.session.redirect,
            failureRedirect: '/',
        })(req, res, next)

    });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.