身份验证中间件快速打字稿错误

时间:2019-07-12 17:35:22

标签: node.js typescript express mongoose

我正在使用express,打字稿和猫鼬作为后端编程。

以下是以下错误。我在制作作者博客API管理系统时遇到了这个问题。验证用户身份时,我没有得到用户的ID。为什么呢?我在做什么错。如何以其他方式存储用户ID进行身份验证?

错误:

runc

user.interface.ts

 TypeError: Cannot read property '_id' of undefined
    at PostsController.createPost

auth.middle.ts

interface User {
  _id: string;
  name: string;
  email: string;
  password: string;
}

export default User;

authentication.controller.ts

import { NextFunction, Response,Request } from 'express';
import * as jwt from 'jsonwebtoken';
import AuthenticationTokenMissingException from '../exceptions/AuthenticationTokenMissingException';
import WrongAuthenticationTokenException from '../exceptions/WrongAuthenticationTokenException';
import DataStoredInToken from '../interfaces/dataStoredInToken';
import RequestWithUser from '../interfaces/requestWithUser.interface';
import userModel from '../users/user.model';
import User from 'users/user.interface';

async function authMiddleware(request: RequestWithUser,req:Request, response: Response, next: NextFunction) {
  const cookies = req.cookies;
  if (cookies && cookies.Authorization) {
    const secret = process.env.JWT_SECRET;
    try {
      const verificationResponse = jwt.verify(cookies.Authorization, secret) as DataStoredInToken;
      const id = verificationResponse._id;
      const user = await userModel.findById(id);
      if (user) {
        request.user = user;
//something wrong is here,I guess ????? 
        next();
      } else {
        next(new WrongAuthenticationTokenException());
      }
    } catch (error) {
      next(new WrongAuthenticationTokenException());
    }
  } else {
    next(new AuthenticationTokenMissingException());
  }
}
export default authMiddleware;

0 个答案:

没有答案