Passport js如何在会话中保存用户?

时间:2018-10-27 10:34:57

标签: node.js express passport.js express-session

我想访问应该存储在会话中的req.user中的用户。这是我的服务器js代码

const express = require("express");
const bodyParser = require("body-parser");
const socketIO = require("socket.io");

const http = require("http");
const app = express();
const server = http.createServer(app);
const io = socketIO(server);

const router = require("express-promise-router")();
const cors = require("cors");
const cookieParser = require("cookie-parser");
const validator = require("express-validator");
const session = require("express-session");
const MongoStore = require("connect-mongo")(session);
const mongoose = require("mongoose");
const passport = require("passport");
const keys = require("./config/keys");

//import cloudinary
require("./services/cloudinaryUpload");
mongoose.connect(
  "mongodb://localhost/chat-app",
  { useNewUrlParser: true },
  () => console.log("Connected to Mongo Server")
);

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//require the models
require("./models/users.js");
require("./models/groups.js");


//require passport
require("./services/passport");
app.use(
  session({
    secret: "thisisasecretkey",
    resave: true,
    saveInitialized: true,
    saveUninitialized: true,
    store: new MongoStore({ mongooseConnection: mongoose.connection })
  })
);
app.use(passport.initialize());
app.use(passport.session());

app.use(router);

//Require sockets
require("./sockets/groupchat")(io);

app.set("trust proxy", 1);

//Require routes
require("./routes/users")(router);
require("./routes/admin")(router);
require("./routes/home")(router);
require("./routes/group")(router);

app.use(express.static("public"));

app.use(validator());

server.listen(5000, () => {
  console.log("Server is listening on the port 5000");
});

这是我的护照js代码:

const passport = require("passport");
const mongoose = require("mongoose");
const User = mongoose.model("users");
const LocalStrategy = require("passport-local").Strategy;
const FacebookStrategy = require("passport-facebook").Strategy;
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const keys = require("../config/keys");

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser(async (id, done) => {
  try {
    const user = await User.findById(id);
    console.log("passport has deserialized the user", user);
    done(null, user);
  } catch (error) {
    done(error, null);
  }
});


passport.use(
  new FacebookStrategy(
    {
      clientID: keys.facebook.clientID,
      clientSecret: keys.facebook.clientSecret,
      profileFields: ["email", "displayName", "photos"],
      callbackURL: "/api/auth/facebook/callback",
      passReqToCallback: true,
      proxy: true
    },
    async (req, token, refreshToken, profile, done) => {
      try {
        const user = await User.findOne({ facebook: profile.id });
        if (user) {
          return done(null, user);
        }
        const newUser = new User();
        newUser.facebook = profile.id;
        newUser.fullname = profile.displayName;
        newUser.email = profile._json.email;
        newUser.userImage = `https://graph.facebook.com/${
          profile.id
        }/picture?type=large`;
        newUser.fbTokens.push({ token });
        const savedUser = await newUser.save();
        done(null, savedUser);
      } catch (err) {
        return done(err, false);
      }
    }
  )
);

passport.use(
  new GoogleStrategy(
    {
      clientID: keys.google.clientID,
      clientSecret: keys.google.clientSecret,
      profileFields: ["email", "displayName", "photos"],
      callbackURL: "/api/auth/google/callback",
      passReqToCallback: true,
      proxy: true
    },
    async (req, accessToken, refreshToken, profile, done) => {
      try {
        const user = await User.findOne({ google: profile.id });
        if (user) {
          return done(null, user);
        }
        const newUser = new User();
        newUser.google = profile.id;
        newUser.fullname = profile.displayName;
        newUser.email = profile.emails[0].value;
        newUser.userImage = profile._json.image.url;
        const savedUser = await newUser.save();
        done(null, savedUser);
      } catch (err) {
        return done(err, false);
      }
    }
  )
);
module.exports = passport;

我有一条“获取用户”路由,想发送用户,但不起作用:

  router.get("/api/get-user", (req, res) => {
    if (req.user) {
      return res.status(200).send(req.user);
    }
    return res.status(401).send({ message: "The user does not exist" });
  });

0 个答案:

没有答案