当前位置: 首页 > 知识库问答 >
问题:

中间件函数在node.js中不工作

越风史
2023-03-14

我是JS的初学者。我正在尝试使用 jwt 令牌构建身份验证。

我在系统中有3个用户(角色:管理员,医生

我有一个用于身份验证的中间件,它是auth.js

我试图写另一个将限制路由的(路由/api/admin/me)访问只有管理员。同样是在adminguard.js.(我试图提取角色和检查条件)

请求有关第二个中间件功能的帮助或提出更好的解决方案。

routes/api/systemusers。js-(路由文件)

const express = require('express');
const router = express.Router();
const {check,validationResult}=require('express-validator/check');
const SystemUser = require('../../models/SystemUser')
const bcrypt=require('bcryptjs');
const jwt = require('jsonwebtoken');
const config =require('config');

// @ route  POST api/systemuser
// @ desc   Register user
// @ access Public
router.post('/',[
    check('username','please enter username').not().isEmpty(),
    check('role','please enter role').not().isEmpty(),
    check('password','please enter 6 or more characters').isLength({min:6}).not()
],
async (req,res)=>{
    const errors=validationResult(req);
    if(!errors.isEmpty()){
        return res.status(400).json({errors: errors.array()});
    }
    const {username, role, password }=req.body;
    try {
        //check for duplicate username request
        let user = await SystemUser.findOne({ username });

        if (user) {
          return res
            .status(400)
            .json({ errors: [{ msg: 'User already exists' }] });
        }
        systemuser = new SystemUser({
            username,
            role,
            password
          });
          //bcrypt pass word
          const salt = await bcrypt.genSalt(10);

          systemuser.password=await bcrypt.hash(password, salt);

          await systemuser.save();

          //return Jsonwebtoken
          const payload = {
            systemuser: {
              id: systemuser.id,
              role:systemuser.role
            }
          };

          jwt.sign(
            payload,
            config.get('jwtSecret'),
             (err, token) => {
              if (err) throw err;
              res.json({ token });
            }
          );
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
    }

    });

module.exports=router;

auth.js(中间件)

const jwt = require('jsonwebtoken');
const config = require('config');

module.exports = function(req, res, next) {
  // Get token from header
  const token = req.header('x-auth-token');

  // Check if not token
  if (!token) {
    return res.status(401).json({ msg: 'No token, authorization denied' });
  }

  // Verify token
  try {
    const decoded = jwt.verify(token, config.get('jwtSecret'));

    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ msg: 'Token is not valid' });
  }
};

adminguard.js(中间件)

module.exports = function (req, res, next) {
    if(req.user && req.user.role !='admin') {
      next(new Error('You are not an admin'));
    } else {
      console.log();
      next();
    }
}

server.js(主文件)

const express =require("express");
const connectDB = require('./config/db');

const app=express();

//connect databse
connectDB();

//init middleware
app.use(express.json({ extended: false }));

app.get('/',(req,res)=>res.send('API running'));

//Define routes

app.use('/api/systemusers',require('./routes/api/systemusers'));
app.use('/api/auth',require('./routes/api/auth'));
app.use('/api/admin',require('./routes/api/admin'));


const PORT =process.env.PORT|5000;

app.listen(PORT, ()=>console.log(`Server started on PORT ${PORT}`));


型号/系统用户

const mongoose= require('mongoose');
const SystemUserSchema=new mongoose.Schema({
    username:{
        type:String,
        required:true
    },
    role:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    },
    date:{
        type:Date,
        default:Date.now
    }
});

module.exports=SystemUser=mongoose.model('systemuser',SystemUserSchema);

共有1个答案

喻子航
2023-03-14

如果用户不是管理员,我建议返回HTTP 403,而不是使用< code>next:

module.exports = function (req, res, next) {
    if(!req.user || req.user.role !='admin') {
      res.status(403).send('You are not an admin');
      return;
    } else {
      console.log('User is an admin');
      next();
    }
}
 类似资料: