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

时间:2019-06-12 19:39:30

标签: node.js jwt middleware

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

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

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

我正在尝试编写另一种限制路由(routes / api / admin / me)访问权限仅限于admin的命令。 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}`));


models / 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);

1 个答案:

答案 0 :(得分:0)

如果用户不是管理员而不是使用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();
    }
}