简体   繁体   English

Passport + Express + Typescript req.user.email 未定义

[英]Passport + Express + Typescript req.user.email undefined

Well, I have this a similar question to this one (I know that is similar to another one).好了,我这有一个类似的问题这一个(我知道这是类似于另一个)。 But req.user was undefined until I installed @types/passport .但是req.user在我安装@types/passport之前是未定义的。

Now I get this problem in VS Code despites I have my session instantiation on my server.现在我在 VS Code 中遇到了这个问题,尽管我的服务器上有我的会话实例。

The problem问题

问题

The instantiation实例化

// Middlewares
app.use(bodyParser.urlencoded({ extended: false }));
app.use(logger(process.env.NODE_ENV === 'development' ? 'dev' : 'combined'));
app.use(express.json());
app.use(session({
    secret: process.env.NODE_ENV === 'development' ? process.env.SESSION_SECRET : 'secret',
    resave: false,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

No errors above.上面没有错误。 Therefore... the app in fact works... but I get this "error color" on my VSC file that would be great to avoid.因此......该应用程序实际上可以工作......但我在我的 VSC 文件中得到了这种“错误颜色”,这是很好的避免。 Any suggestions?有什么建议?

Just in case, I will include the whole router file:以防万一,我将包含整个路由器文件:

// POST - Crear usuario
router.post('/', async (req: Request, res: Response) => {
    const resultado: IResultado = {
        data: null,
        ok: false
    };
    const messages: Array<object> = [];
    const datos: IUsuario = req.body;

    // Validación de campos
    if (!validator.isEmail(datos.email)) {
        messages.push({ email: 'El correo electrónico es inválido'});
    }

    if (validator.isLength(datos.password, { max: 5})) {
        messages.push({ password: 'La contraseña debe tener como mínimo seis caracteres' });
    }

    if (!validator.isMobilePhone(datos.telefono, ['es-UY'])) {
        messages.push({ telefono: 'El número de teléfono es inválido' });
    }

    if (!empty(messages)) {
        resultado.message = 'No se pudo crear el usuario';
        resultado.messages = messages;
        return res.json(resultado);
    }

    datos.password = await bcrypt.hash(datos.password, 10);
    datos.fechaCreacion = Date.now();
    datos.fechaActualizacion = Date.now();

    if (req.user && req.user) {
        datos.propietario = req.user.email;
    }

    const ref: any = db.collection('usuarios').doc(datos.email);

    const doc = await ref.get();

    if (doc.exists) {
        // Usuario ya existe
        resultado.message = 'El correo electrónico ya está en uso';
        return res.json(resultado);
    }
    try {
        await ref.set(datos);
        delete datos.password;
        resultado.message = 'Usuario creado correctamente';
        resultado.data = datos;
        resultado.ok = true;
        return res.json(resultado);
    } catch(error) {
        resultado.message = 'No se pudo crear el usuario';
        resultado.error = error;
        console.log(error);
        return res.status(500).json(resultado);
    }
});

The User interface ( @types/passport module) User界面( @types/passport模块)

// tslint:disable-next-line:no-empty-interface
        interface AuthInfo {}
        // tslint:disable-next-line:no-empty-interface
        interface User {}

        interface Request {
            authInfo?: AuthInfo;
            user?: User;
...

You need to extend the Express.User type:您需要扩展Express.User类型:

declare global {
  namespace Express {
    interface User {
      email: string;
    }
  }
}

I think all you need to do is extend basic User type interface.我认为您需要做的就是扩展基本的User类型界面。 That already was asked on GitHub .这已经在GitHub 上问过了。

interface User extends SomeOtherUserTypeYouHaveDefined {
      email?: string;
      alsoAnyOtherPropertyYourCodeSetsOnUser: number;
    }

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

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