Я хочу аутентифицировать 3 типа пользователей (администратор, продавец и клиент), поэтому я делюсь на каждую часть, как
main folder
____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
но после этого req.user
равно undefined
. это работает, когда я не разделяю его и не аутентифицирую одного пользователя (например, администратора или продавца).
index.js // основной файл
//load routes
const adminRoutes = require('./routes/admin/index');
const sellerRoutes = require('./routes/seller/index');
//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 продавца
const express = require('express')
const router = express.Router()
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
//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) {
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;
seller.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.get('/test', async function (req, res) {
console.log(req.user) //prints undefined
return res.json({
success: false
})
})