如何在Redux商店中使用passport.js获取有关Facebook授权的信息?

时间:2019-04-07 14:49:48

标签: reactjs express redux passport.js mern

我使用MERN堆栈。

在我的反应组件中,我有这样的一行(删除了大部分代码以缩短代码):

class Login extends Component {
  render() {
    return (
      <a href="/" onClick={this.onLogin}>Enter via email</a>
      <a href="https://localhost:5000/api/users/auth/facebook">Enter via facebook</a>
    )
  }
}

server.js

// Passport middleware
app.use(passport.initialize());
// Passport Config
require("./config/jwt")(passport);
require("./config/facebook")(passport);

护照Facebook策略- facebook.js

const passport = require('passport')
const FacebookStrategy = require('passport-facebook').Strategy;
const mongoose = require("mongoose");
const User = mongoose.model("users");
const keys = require("./keys");

module.exports = passport => {
  passport.use(
    new FacebookStrategy(
      {
        clientID: keys.facebook.clientID,
        clientSecret: keys.facebook.clientSecret,
        callbackURL: "https://localhost:5000/api/users/auth/facebook/callback",
        profileFields: ['id', 'emails', 'name', 'picture.type(large)']
      },
      (accessToken, refreshToken, profile, done) => {
        // console.log("FacebookStrategy", profile);
        User.findOne({
          // 'facebook.id': profile.id 
          $or: [
            { 'facebook.id': profile.id },
            { 'email': profile.emails[0].value }
          ]
        })
          .then(user => {
            if (user) {
              console.log("__user already exists", user);
              if (user.facebook.id == undefined) {
                user.facebook.id = profile.id;
                user.facebook.token = accessToken;
                user.facebook.email = profile.emails[0].value;
                user.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
                user.save();
              }

              return done(null, user);
            } else {
              console.log("__user doens't exist", user);
              const newUser = new User({
                facebook: {
                  id: profile.id,
                  token: accessToken,
                  email: (profile.emails) ? profile.emails[0].value : undefined,
                },
                name: profile.name.givenName + ' ' + profile.name.familyName,
                email: (profile.emails) ? profile.emails[0].value : undefined,
                privilege: 1
              });

              newUser
                .save()
                .then(user => console.log("passport facebook save user -> ", user))
                .catch(err => console.log("passport facebook save err -> ", err))

              return done(null, newUser);
            };
          })
          .catch(err => console.log("Passport err ->  ", err));
      }
    ));
};

api / routes.js

router.get("/auth/facebook",
  passport.authenticate('facebook', { session: false, scope: ['email'] }) //, { session: false, scope: ['email'] })
);

router.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    session: false,
    scope: ['email'],
    successRedirect: 'https://localhost:3000',
    failureRedirect: 'https://localhost:3000/login'
  }), (req, res) => {
    console.log("facebook success");
    res.redirect('https://localhost:3000');
    res.render('json', { data: JSON.stringify(req.user.access_token) });
  }
);

在后端方面效果很好。用户要么创建要么登录。在JWT的情况下,我有onClick调用authAction,后者将有效负载从数据库存储到redux存储。但是我无法在我的React应用程序中如何将有关Facebook登录的信息传递到Redux商店

0 个答案:

没有答案