Xenilo
Xenilo

Reputation: 25

How do you authenticate on facebook using passport in a web application?

So, I successfully used the node package passport-google-oauth20 to authenticate users on a test web application I'm writing...here's that code:

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbackURL: 'http://localhost:3000/auth/google/secrets',
      userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo'
    },

    (accessToken, refreshToken, profile, done) => {
      User.findOne({ googleId: profile.id }).then(currentUser => {
        if (currentUser) {
          //if we already have a record with the given profile ID
          done(null, currentUser);
        } else {
          //if not, create a new user
          new User({
            googleId: profile.id
          })
            .save()
            .then(newUser => {
              done(null, newUser);
            });
        }
      });
    }
  )
);

But, when I import and attempt to use the node package passport-facebook, like so:

passport.use(
  new FacebookStrategy(
    {
      clientID: process.env.FACEBOOK_APP_ID,
      clientSecret: process.env.FACEBOOK_APP_SECRET,
      callbackURL: 'http://localhost:3000/auth/facebook/secrets'
    },

    (accessToken, refreshToken, profile, done) => {
      User.findOne({ facebookId: profile.id }).then(currentUser => {
        if (currentUser) {
          //if we already have a record with the given profile ID
          done(null, currentUser);
        } else {
          //if not, create a new user
          new User({
            facebookId: profile.id
          })
            .save()
            .then(newUser => {
              done(null, newUser);
            });
        }
      });
    }
  )
);

I run into a problem. In my application, I reach the "log in with facebook" screen. But then, the application just hangs and gives me an error rather than redirection. Here's the error:

UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: userDB.users index: username_1 dup key: { username: null }

Has anyone encountered this with passport.js authentication strategies?

Upvotes: 0

Views: 52

Answers (1)

Ebert Roos
Ebert Roos

Reputation: 36

The username property that is returned from currentUser or newUser is null and your username field in MongoDB is marked as unique. There is already a record that is null in your MongoDB collection so it sees it as a duplicate. I wouldn't use a username as your unique key, rather assign a uuid to each user, but do a check on your DB to insure that the username is unique.

You can try to console.log your newUser or currentUser objects and figure out why the usernames are returned as null.

I've personally only used Passport.js for Linkedin and Twitter, but I hope this helps.

Upvotes: 1

Related Questions