PassportJs在React App中获取页面刷新时登录用户的详细信息

时间:2018-12-18 09:34:54

标签: reactjs express passport.js

我正在使用服务器处理带有护照js的身份验证的简单博客应用程序。这是我的服务器代码:

import express from 'express';
import passport from 'passport';
import cookieSession from 'cookie-session'; // encrypt cookie

import router from './routes/routes';
import authRouter from './routes/authRoutes';
import middleware from './middleware';
import keys from './keys';

const app = express();

// use cookies for login/logout session, send cookie to browser
// happens only when user logs in.
app.use(cookieSession({
  maxAge: 24 * 60 * 60 * 1000, // 1 day
  keys: [keys.session.cookieKey], // encrypt cookie
}));

app.use(passport.initialize());
app.use(passport.session());

// auth routes
app.use('/auth', authRouter);

我的authRoutes.js

import Router from 'express';
import passport from 'passport';
import GoogleStrategy from 'passport-google-oauth20';
import popupTools from 'popup-tools';

import { User } from '../database/model';
import keys from '../keys';

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

passport.deserializeUser(async (id, done) => {
  const usr = await User.findById(id);

  done(null, usr);
});

passport.use(new GoogleStrategy({
  clientID: keys.google.clientID,
  clientSecret: keys.google.clientSecret,
  callbackURL: '/auth/google/redirect',
}, async (accessToken, refreshToken, profile, people, done) => {
  let usr = await User.findOne({ googleID: people.id });
  if (!usr) {
    const user = new User({
      name: people.displayName,
      email: people.emails[0].value,
      googleID: people.id,
      image: people._json.image.url,
    });

    usr = await user.save();
   }
  // calls serializeUser
  done(null, usr);
}));

const authRouter = Router();

authRouter.get('/google', passport.authenticate('google', {
  scope: ['profile', 'email'],
}));

authRouter.get('/logout', (req, res) => {
  req.logout();
  res.set('Content-Type', 'text/html');
  res.end(popupTools.popupResponse({
    status: true,
    message: 'Logged out!',
  }));
});

// callback for google auth
authRouter.get('/google/redirect',
  passport.authenticate('google'),
  (req, res) => {
    // here we have the user as req.user
    res.set('Content-Type', 'text/html');
    res.end(popupTools.popupResponse({
      status: true,
      message: {
        data: req.user,
      },
    }));
  }
);

// I want this route to get me the current user
authRouter.get('/getActiveUser', (req, res) => {
  res.json({
    user: req.user,
  });
});

export default authRouter;

我正在使用popupTools来帮助登录弹出窗口。在前端,当用户登录并关闭弹出窗口时,我将用户信息保存在mobx存储中。但是,当我重新加载页面时,我无法保留任何信息。 我想要服务器上的路由,例如/ getActiveUser,从中我可以让用户当前登录。但这似乎无效。

1 个答案:

答案 0 :(得分:1)

您将需要在React App中使用localStorage API或sessionStorage。我使用localStorage,例如:

成功验证用户身份后,将用户对象保存在localStorage中: localStorage.setItem('user', JSON.stringify(userObject));

使用您的localStorage将React应用安装到浏览器中后,从mobx加载用户,例如: const user = JSON.parse(localStorage.getItem('user'));

这样,您将拥有用户对象,以防万一您想再次在前端使用该对象,从而可以保存用户的会话。

在注销过程中,您将从user中删除localStorage的项目。 localStorage.removeItem('user');