无法将中间件添加到Express中的路由

时间:2018-12-15 06:17:24

标签: node.js express passport.js

我一直在遵循关于chatApp的系列教程,其中使用NodeJ,Express和Passport进行身份验证,而不是使用app.get(),他使用了一种完全不同的方式来存储和访问路线。

'use strict';
const h = require('../helpers');
const passport = require('passport');

module.exports=()=>{
    let routes = {
        'get':{
            '/':(req,res,next)=>{
                res.render('login');
            },
            '/rooms':[h.isAuthenticated,(req,res,next)=>{
                res.render('rooms',{
                    user:req.user
                });
            }],
            '/chat':(req,res,next)=>{
                res.render('chatroom');
            },
            '/auth/facebook': passport.authenticate('facebook'),
            '/auth/facebook/callback': passport.authenticate('facebook',{
                successRedirect:'/rooms',
                failureRedirect:'/'
            }),
            '/auth/google': passport.authenticate('google', {
                scope:[
                    'profile'
                ]
            }),
            '/auth/google/callback': passport.authenticate('google',{
                successRedirect:'/rooms',
                failureRedirect:'/'
            }),
            '/logout':(req,res,next)=>{
                req.logout();
                res.redirect('/');
            }
        },
        'post':{

        },
        'NA':(req,res,next)=>{
            res.status(404).sendFile(process.cwd()+'/views/404.htm');
        }
    }

    return h.route(routes);
}

护照用于Facebook身份验证。 每当用户单击Facebook登录时,获取请求都会发送到url / auth / facebook,然后回叫,然后重定向到/ rooms页面

'/auth/facebook': passport.authenticate('facebook'),
'/auth/facebook/callback': passport.authenticate('facebook',{
    successRedirect:'/rooms',
    failureRedirect:'/'
}),

到目前为止,一切正常。但是我想添加安全的路由。如果用户通过了身份验证,则可以访问localhost / rooms URL,否则我们将被重定向到主页。 因此,我添加了h.isAuthenticated(这是另一个导入的函数)

'/rooms':[h.isAuthenticated,(req,res,next)=>{
                res.render('rooms',{
                    user:req.user
                });
            }],

现在,当我单击“使用Facebook登录”按钮时,它转到/ auth / facebook,但未进行身份验证,而是显示了房间页面,并且无法加载个人资料名称,图片之类的变量,因此它发送并出错。

我的问题是,我如何在此处添加此中间件,以便首先进行身份验证并呈现房间页面。

要检查的中间件是用户已登录或已通过身份验证

let isAuthenticated = (req,res,next)=>{
    console.log(req.isAuthenticated());
    if(req.isAuthenticated()){
        next();
    }else{
        res.redirect('/');
    }
}

0 个答案:

没有答案