通过passport-jwt进行身份验证时,它使用了diff目录中的策略

时间:2019-06-08 17:27:05

标签: express authentication passport-jwt

我想对三种类型的用户(管理员,卖方和客户)进行身份验证,因此我将每个部分划分为

main folder
index.js
____index.js //main index.js
____admin //admin dir
______index.js //index.js for admin
______admin.js //admin routes
____seller //seller dir
______index.js //index.js for seller
______seller.js //seller routes

登录/注册过程工作正常,但是当我对admin部分进行身份验证时,它将执行/seller/index.js而不是admin / index.js的查询。

当我最初登录(代码在/admin/admin.js时)时,它工作正常。另外,卖方部分工作正常。

index.js

//load routes  
const adminRoutes = require('./routes/admin/index'); //should go to admin
const sellerRoutes = require('./routes/seller/index'); //should go to seller

//mongoose and bodyparser config

//session config
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false
}));

app.use('/admin', adminRoutes); 
app.use('/seller', sellerRoutes);

app.listen(process.env.PORT || 3000, process.env.IP, function () {
    console.log(`amtica server is running on port: ${process.env.PORT}`);
});

卖家的index.js


//load models
const Seller = require("../../models/seller");

// load routes
const sellerRoute = require('./seller');

//passport config
router.use(passport.initialize());
router.use(passport.session());

let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;
passport.use(new JwtStrategy(opts, function (jwt_payload, done) {
    console.log(jwt_payload, 1111) //will print this, while authenticating admin
    Seller.findOne({ username: jwt_payload.data.username }, { password: 0 }, function (err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            req.user = user;
            return done(null, user);
        }
        else {
            return done(null, false);
            // or you could create a new account
        }
    });
}));

router.use(sellerRoute);

module.exports = router;

卖家的eller.js

router.post('/signup', (req, res) => {
    let { email, password, name, username, contact, address } = req.body
    let newSeller = new Seller({
        email,
        password,
        name, username, contact, address
    });
    Seller.addSeller(newSeller, (err, user) => {
        if (err) {
            console.log(err)
            return res.json({
                success: false,
                message: `${err.message}`
            });
        }
        else {
            return res.json({
                success: true,
                message: `successfully registered. please signin at /seller/signin`
            });
        }
    });
});


//auth 
router.post('/signin', (req, res) => {
    const { username, password } = req.body;
    Seller.getSellerByUsername(username, (err, user) => {
        if (err) throw err;
        if (!user) {
            return res.json({ success: false, message: 'User not found' });
        }
        // console.log(req.user, 323);
        Seller.comparePassword(password, user.password, (err, isMatch) => {
            if (err) throw err;
            if (isMatch) {
                user.password = null;
                const token = jwt.sign({ data: user }, process.env.JWT_SECRET, {
                    expiresIn: 604800 // 1 week
                });
                res.json({
                    success: true,
                    token: `Bearer ${token}`,
                    user: {
                        id: user._id,
                        username: user.username,
                        roles: 'seller',
                    },
                    message: `welcome back!! ${user.username}`
                });
            }
            else {
                return res.json({ success: false, message: 'Wrong password' });
            }
        });
    });
});

router.use(passport.authenticate('jwt', { session: false })) //working properly

router.get('/test', async function (req, res) {
    console.log(req.user) //prints undefined
    return res.json({
        success: false
    })
})

admin的index.js

//load models
const Admin = require("../../models/admin");

// load routes
const adminRoute = require('./admin');

//passport config
router.use(passport.initialize());
router.use(passport.session());

let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;
passport.use(new JwtStrategy(opts, function (jwt_payload, done) {
    console.log(jwt_payload, 2222) //will not print this when authenticating
    Admin.findOne({ username: jwt_payload.data.username }, { password: 0 }, function (err, user) {
        console.log('here') // not print this one
        if (err) {
            return done(err, false);
        }
        if (user) {
            return done(null, user);
        }
        else {
            return done(null, false);
            // or you could create a new account
        }
    });
}));

router.use(adminRoute);

module.exports = router;

admin的admin.js

// the signin route works but not the another one.
router.post('/signin', (req, res) => {
    const { username, password } = req.body;
    Admin.getAdminByUsername(username, (err, user) => {
        if (err) throw err;
        if (!user) {
            return res.json({ success: false, message: 'User not found' });
        }

        Admin.comparePassword(password, user.password, (err, isMatch) => {
            if (err) throw err;
            if (isMatch) {
                const token = jwt.sign({ data: user }, process.env.JWT_SECRET, {
                    expiresIn: 604800// 1 week
                });

                res.json({
                    success: true,
                    token: `Bearer ${token}`,
                    user: {
                        id: user._id,
                        username: user.username,
                        roles: 'admin',
                    },
                    message: `welcome back!! ${user.username}`
                });
            }
            else {
                return res.json({ success: false, message: 'Wrong password' });
            }
        });
    });
});



router.use(passport.authenticate('jwt', { session: false }))

//test
router.get('/test', async function (req, res) { // not work 401 error
    try {
        return res.json({ product: 'asdsf' });
    }
    catch (err) {
        return res.json({
            msg: err.message
        })
    }
} )

0 个答案:

没有答案