【问题标题】:req.user is undefined, using typescriptreq.user 未定义,使用打字稿
【发布时间】:2022-10-06 12:57:46
【问题描述】:

我是打字稿的新手,我正在使用护照进行 Oauth2.0 项目,req.user 返回未定义,我不知道为什么,这是我的代码。

function checkLoggedIn(req: Request, res: Response, next: NextFunction): any {
  console.log('current user is: ', req.user);
  const isLoggedIn = true;
  if (!isLoggedIn) {
    return res.status(401).json({
      error: 'you must log in',
    });
  }
  next();
}

登录用户时我总是不确定

current user is:  undefined

有谁知道这是什么课程?

  • 整个代码

async function verifyCallback(accessToken: any, refreshToken: any, profile: any, done: any) {
  const newUser = {
    googleId: profile.id,
    displayName: profile.displayName,
    email: profile.emails[0].value,
    Image: profile.photos[0].value,
  };

  try {
    let user = await Oauth.findOne({ googleId: profile.id });

    if (user) {
      done(null, profile);
    } else {
      user = await Oauth.create(newUser);
      done(null, profile);
    }
  } catch (err) {
    console.log(err);
  }
}

passport.use(new Strategy(AUTH_OPTIONS, verifyCallback));

// save the session to the cookie
passport.serializeUser((user: any, done) => {
  done(null, user.id)
});

// load the session from the cookie
passport.deserializeUser((id: any, done) => {
  done(null, id)
});

app.use(helmet());

app.use(cookieSession({
  name: 'session',
  maxAge: 24 * 60 * 60 * 1000, 
  keys: [ config.COOKIE_KEY_1, config.COOKIE_KEY_2 ],
}))

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

function checkLoggedIn(req: Request, res: Response, next: NextFunction): any {
  console.log('current user is: ', req.user);
  const isLoggedIn = true;
  if (!isLoggedIn) {
    return res.status(401).json({
      error: 'you must log in',
    });
  }
  next();
}

// Authentication route
router.get(
  '/auth/google',
  passport.authenticate('google', {
    scope: ['profile', 'email', 'https://www.googleapis.com/auth/youtube.upload'],
  }),
);

router.get(
  '/auth/google/callback',
  passport.authenticate('google', {
    failureRedirect: '/failure',
    successRedirect: '/user',
    session: true,
  }),
  (req, res) => {
    console.log('google called us back');
  },
);

router.get('/user', checkLoggedIn, async (req, res) => {
  try {
    const user: any = await Oauth.findOne({ username: String });
    res.status(200).json(user);
  } catch (err) {
    res.status(500).json(err);
  }
});

router.get('/logout', (req, res) => {
  res.redirect('/')
});

router.get('/failure', (req, res) => {
  res.send('failed to log in');
});

【问题讨论】:

  • 登录req时显示什么?还要检查是否请求从快递进口
  • 这与 TypeScript 无关,这是您的应用程序中的设置问题(未正确配置护照、会话无法正常工作等)。
  • 是什么让您认为应该设置req.user?也分享该代码。
  • @YJR 是的,请求是从 express 导入的
  • @Evert,当我加载我得到的回调网址时,我的浏览器上的用户详细信息,所以我想保护用户路线,我需要用户数据来做到这一点。我刚刚编辑了这个问题。

标签: node.js typescript express oauth-2.0 passport.js


【解决方案1】:

** 尝试这个 **

您可以将值 (req.user) 更改为 (req.body.user)

function checkLoggedIn(req: Request, res: Response, next: NextFunction): any {
  console.log('current user is: ', req.body.user);
  const isLoggedIn = true;
  if (!isLoggedIn) {
    return res.status(401).json({
      error: 'you must log in',
    });
  }
  next();
}

【讨论】:

  • 试过了,还是不行!
猜你喜欢
  • 2021-06-11
  • 2018-02-23
  • 1970-01-01
  • 2016-11-06
  • 2016-09-05
  • 2021-04-22
  • 2016-12-13
  • 2020-02-12
  • 2017-12-22
相关资源
最近更新 更多