req.user没有获得当前用户,但是req.session.passport.user有

时间:2019-11-21 02:24:44

标签: javascript node.js passport.js

我正在尝试以某种方式调整代码,以使当前用户与req.user不在同一个位置。我正在使用googleoAuth,看来req.user仅获得了第一个登录的用户,因此如果您使用其他Google帐户登录,则req.user仍会显示旧用户google登录的用户。

我想使用req.user而不是req.session.passport.user,应该调整什么?

sessionConfig.ts

import session from "express-session";
import Sequelize from "sequelize";
import dotenv from "dotenv";
dotenv.config();
const SequelizeStore = require("connect-session-sequelize")(session.Store);

let sequelize;
if (process.env.NODE_ENV === "development") {
  sequelize = new Sequelize(
    process.env.PSQL_NAME,
    process.env.PSQL_USER,
    process.env.PSQL_PASS,
    {
      dialect: "sqlite",
      storage: "./session.sqlite"
    }
  );
} else {
  sequelize = new Sequelize(process.env.DATABASE_URL, {
    dialect: "sqlite",
    storage: "./session.sqlite"
  });
}

const myStore = new SequelizeStore({
  db: sequelize
});

export interface sessionInterface {
  store: object;
  secret: string;
  resave: boolean;
  saveUninitialized: boolean;
  cookie: object;
}

const sessionConfig: sessionInterface = {
  store: myStore,
  secret: "nodetoken",
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: false,
    path: "/",
    secure: false,
    maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
  }
};

myStore.sync();
export default sessionConfig;

checkSession.ts

import { Response, NextFunction } from "express";
import models from "../models";

export default () => async (req: any, res: Response, next: NextFunction) => {
  console.log(req.session);
  if (req.session && req.session.user) {
    const user = await models.User.findOne({
      where: {
        id: req.session.user.id
      },
      raw: true
    });
    if (user) {
      req.user = user;
      delete req.user.password; // delete the password from the session
      req.session.user = user; // refresh the session value
      res.locals.user = user;
    }
    // finishing processing the middleware and run the route
    next();
  } else {
    next();
  }
};

passport.ts

import passport from "passport";
import GoogleStrategy from "passport-google-oauth20";
import dotenv from "dotenv";
import models from "../models";
dotenv.config();
const GoogleSta = GoogleStrategy.Strategy;

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

passport.deserializeUser((id, done) => {
  console.log(id);
  models.User.findOne({ id: id })
    .then(usr => {
      return done(null, usr);
    })
    .catch(err => {
      done(err);
    });
});

passport.use(
  new GoogleSta(
    {
      clientID: process.env.clientID,
      clientSecret: process.env.clientSecret,
      callbackURL: process.env.callbackURL
    },
    async (token, tokenSecret, profile, done) => {
      console.log(profile);
      models.User.findOne({ where: { googleId: profile.id } }).then(
        async userExist => {
          let transaction;
          if (userExist) {
            console.log("hi");
            return done(null, userExist);
          } else {
            try {
              transaction = await models.sequelize.transaction();

              console.log("test", profile.emails[0].value);
              await Promise.all([
                models.User.create(
                  {
                    googleId: profile.id,
                    username: null,
                    email: profile.emails[0].value
                  },
                  { transaction }
                )
              ]).then(async user => {
                await transaction.commit();
                return done(null, user);
              });
            } catch (err) {
              if (transaction) {
                await transaction.rollback();
                return done(null, err);
              }
            }
          }
        }
      );
    }
  )
);

currentUser.ts

currentUser: (req: any, res: Response) => {
    let curUser;
    let token;
    /* save session */

    // console.log("currr", req.session.passport.user.id);

    if (req.session && req.session.user) {
      curUser = req.session.user.id;
    } else if (req.session) {
      curUser = req.session.passport ? req.session.passport.user : null;
    }
    if (req.session && req.session.passport) {
      token = jwt.sign(
        { id: req.session.passport.user.id },
        process.env.JWT_SECRET
      );
    } else if (req.session && req.session.user) {
      token = jwt.sign({ id: req.session.user.id }, process.env.JWT_SECRET);
    }

    return res.status(200).send({
      user: curUser,
      token: token ? token : null
    });
  },

app.ts

import express from "express";
import http from "http";
import cors from "cors";
import logger from "morgan";
import { Request, Response, NextFunction } from "express";
import cookieParser from "cookie-parser";
import bodyParser from "body-parser";
import apiRouter from "./routers";
import dotenv from "dotenv";
import path from "path";
import passport from "passport";
import "./config/passport";
import models from "./models/";
import { useSession, checkSession } from "./middlewares";
dotenv.config();
const PORT = process.env.PORT || 5000;
const app: express.Application = express();
const httpServer = http.createServer(app);
/**
 * middlewares
 */
/* development build, use logger & simulateLatency */
if (process.env.NODE_ENV === "development") {
  app.use(logger("dev"));

  // to simulate latency of 50ms - 1000ms
  // app.use(simulateLatency(50, 1000));
}

app.set("port", PORT);
// app.use(
//   session({
//     saveUninitialized: false,
//     resave: false,
//     cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
//     secret: "nodeauth"
//   })
// );
app.use(cookieParser());
app.use(bodyParser.json({ limit: "5mb" }));
app.use(bodyParser.urlencoded({ limit: "5mb", extended: true }));
app.use(useSession());
app.use(checkSession());
app.use(passport.initialize());
app.use(passport.session());
app.use(
  cors({
    origin: process.env.ALLOW_ORIGIN,
    preflightContinue: true,
    credentials: true,
    allowedHeaders: "X-Requested-With, Content-Type, Authorization",
    methods: "GET, POST, PATCH, PUT, POST, DELETE, OPTIONS",
    exposedHeaders: ["Content-Length", "X-Foo", "X-Bar"]
  })
);
app.use(express.static(path.join(__dirname, "../../client", "build")));
app.use("/api/v1", apiRouter);
app.get("/", (req, res) => {
  res.send("Hello World!");
});

/**
 * middlewares
 */
/* development build, use logger & simulateLatency */
if (process.env.NODE_ENV === "production") {
  app.use(logger("dev"));

  app.use("*", (req, res: Response) => {
    console.log(path.join(__dirname, "../../client", "build", "index.html"));
    res.sendFile(path.join(__dirname, "../../client", "build", "index.html"));
  });
}

models.sequelize.sync().then(() => {
  httpServer.listen(PORT, () => {
    console.log(
      "App is running at http://localhost:%d in %s mode",
      app.get("port"),
      app.get("env")
    );
    console.log("  Press CTRL-C to stop\n");
  });
});

export default app;

0 个答案:

没有答案