中间件功能在node.js中不起作用

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (10)

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

我在系统中有3个用户(角色:管理员,医生和病人)。我在有效负载中传递用户ID和用户角色以生成令牌。我将这些作为String传递。

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

我正在尝试编写另一个限制路由(routes / 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}`));


车型/ SystemUser

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);
提问于
用户回答回答于

如果用户不是管理员而不是使用next以下内容,我建议返回HTTP 403 :

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();
    }
}

扫码关注云+社区

领取腾讯云代金券