简体   繁体   English

Express - 检查 session 是否存在

[英]Express - Check if session exist

I am setting up my NodeJS & Express App, using Passport for authentication with Google Sign In and Login.我正在设置我的 NodeJS 和 Express 应用程序,使用 Passport 通过 Google 登录和登录进行身份验证。 Everything works very well when working on localhost.在本地主机上工作时一切正常。

The signin process works very well, and I can see the user information attached to req.user contains all user information.登录过程运行良好,我可以看到附加到 req.user 的用户信息包含所有用户信息。

However, right after that, when calling any route, req.user is undefined然而,在那之后,当调用任何路由时, req.user 是未定义的

I try desperately, to check if any session doesent exist to redirected that, on my login page, but it gives me some error based on Unexpected token我拼命尝试检查在我的登录页面上是否存在任何 session 来重定向它,但它给了我一些基于Unexpected token的错误

index.js: index.js:

const express = require("express");
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const app = express()
const port = 5000

// if user is not logged-in redirect back to login page
app.use(function(req, res, next) {
   if (req.session.user == null){
   res.redirect('http://localhost:3000/login');
   }   else {
    next();
   }
});

app.use(
  session({
  secret: 'keyboard cat',
  resave: false,
  cookie: { httpOnly: false, secure: false, maxAge: 60 * 1000},
  saveUninitialized: false,
     })
  )

passport.use(
  new GoogleStrategy({
  clientID: "process.env.clientID",
  clientSecret: "process.env.clientSecret",
  callbackURL: '/auth/google/callback',
},
async (accessToken, refreshToken, profile, done) => {
  const existingUser = await User.findOne({
    providerId: profile.id,
  })
  if (existingUser) {
      return done(null, existingUser);
  }
  const user = await new User({
    provider: profile.provider,
    providerId: profile.id,
    displayName: profile.displayName,
    
  }).save()
  done(null, user);
 })
)

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

passport.deserializeUser(function (obj, done) {
  done(null, done);
});

My error:我的错误:

ERROR  Error in fetch(): request to http://localhost:3000/login failed, reason: read ECONNRESET

  at ClientRequest.<anonymous> (node_modules/node-fetch/lib/index.js:1461:11)
  at ClientRequest.emit (events.js:400:28)
  at Socket.socketErrorListener (_http_client.js:475:9)
  at Socket.emit (events.js:400:28)
  at emitErrorNT (internal/streams/destroy.js:106:8)
  at emitErrorCloseNT (internal/streams/destroy.js:74:3)
  at processTicksAndRejections (internal/process/task_queues.js:82:21)

Thank you谢谢

For starters, move this:对于初学者,移动这个:

// if user is not logged-in redirect back to login page
app.use(function(req, res, next) {
   if (req.session.user == null){
   res.redirect('http://localhost:3000/login');
   }   else {
    next();
   }
});

to be after this:在此之后:

app.use(
  session({
  secret: 'keyboard cat',
  resave: false,
  cookie: { httpOnly: false, secure: false, maxAge: 60 * 1000},
  saveUninitialized: false,
     })
)

There will NEVER be a req.session until AFTER the session middleware runs so any code that tries to use req.session must be after the session middleware. There will NEVER be a req.session until AFTER the session middleware runs so any code that tries to use req.session must be after the session middleware.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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