简体   繁体   中英

PassportJs get details of logged in user on page refresh in react app

I am building a simple blogging app with the server handling auth with passport js. Here is my server code:

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);

My 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;

I am using popupTools to help sign in with popup. On the front end, when the user logs in and the popup closes, I am saving the user information in mobx store. But when I am reloading the page, I can't preserve any of that information. I want a route on my server like the /getActiveUser from where I can get the user currently logged in. But it doesn't seem to work.

You will need to use either localStorage API or sessionStorage in your React App. I use localStorage , such like:

Save user object in localStorage once the user is authenticated successfully: localStorage.setItem('user', JSON.stringify(userObject));

Load user from the localStorage , once the React app is mounted in the browser using your mobx , such like: const user = JSON.parse(localStorage.getItem('user'));

this way you have the user object, in case you want to use in the front again, this way you will be saving the user's session.

in case of logout process, you will be removing the user 's Item from localStorage . localStorage.removeItem('user');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM