节点mocha测试具有多个用户的JWT保护路由

时间:2017-05-16 11:13:32

标签: node.js mocha jwt

我正在尝试测试多个用户的受保护路由(我将检查以后的资源授权) 它&#39;当我开始与一个用户进行测试时,设置&amp;将用户保存在before()挂钩中,但是一旦我在此挂钩中设置并保存第二个用户,那么我的所有测试都没有通过......似乎第二个用户设置正在改变JWT的内容..?< / p>

const rootUser = new User({
  username: config.mongo.user,
  password: config.mongo.pwd,
  email: 'johndoe@example.com',
  mobileNumber: 123456789
});
let rootJwtToken = '';

/**
 * root level hooks
 */

before(() =>
  rootUser.save({})
    .then((savedRootUser) => {
      const rootToken = jwt.sign({ username: savedRootUser.username }, config.jwtSecret);
      rootJwtToken = `Bearer ${rootToken}`;
    })
);

after(() => {
  User.remove(() => {});
  Group.remove(() => {});
  // required because https://github.com/Automattic/mongoose/issues/1251#issuecomment-65793092
  mongoose.models = {};
  mongoose.modelSchemas = {};
  mongoose.connection.close();
});

describe('## root user w Group APIs', () => {
  let group = {
    name: 'Admin',
    description: 'Administration group'
  };

  describe('# POST /api/v1/groups', () => {
    it('should allow root user to create a new group', () =>
      request(app)
        .post('/api/v1/groups')
        .set('Authorization', rootJwtToken)
        .send(group)
        .expect(httpStatus.OK)
        .then((res) => {
          // check group
          expect(res.body.name).to.equal(group.name);
          expect(res.body.description).to.equal(group.description);
          group = res.body;
        })
    );
  });
  describe('# DELETE /api/v1/groups/:groupId', () => {
    it('should allow root user to delete a group', () =>
      request(app)
        .delete(`/api/v1/groups/${group._id}`)
        .set('Authorization', rootJwtToken)
        .expect(httpStatus.OK)
        .then((res) => {
          expect(res.body.name).to.equal('Administrator');
        })
    );
  });
});

然后我在添加其他用户后进行测试

const rootUser = new User({
  username: config.mongo.user,
  password: config.mongo.pwd,
  email: 'johndoe@example.com',
  mobileNumber: 123456789
});
let rootJwtToken = '';

const adminUser = new User({
  username: cadminuser',
  password: '999999999,
  email: 'william@example.com',
  mobileNumber: 97654321
});
let adminwtToken = '';


/**
 * root level hooks
 */

before(() => {
  rootUser.save({})
    .then((savedRootUser) => {
      const rootToken = jwt.sign({ username: savedRootUser.username }, config.jwtSecret);
      rootJwtToken = `Bearer ${rootToken}`;
    });
  adminUser.save({})
    .then((savedAdminUser) => {
      const adminToken = jwt.sign({ username: savedAdminUser.username }, config.jwtSecret);
      adminJwtToken = `Bearer ${adminToken}`;
    });
});

....
describe('## root user w Group APIs', () => {
...using rootJwtToken
}
describe('## admin user w Group APIs', () => {
...using adminJwtToken
}

感谢您的反馈

1 个答案:

答案 0 :(得分:1)

我重构了我的代码,在before()钩子中定义了不同的测试用户,并在每个用户特定的测试组中插入了一个jet签名测试

let rootJwtToken = '';
let rootUser = new User({});

let adminJwtToken = '';
let adminUser = new User({});

let employeeJwtToken = '';
let employeeUser = new User({});

before(() => {
  rootUser = new User({
    username: config.mongo.user,
    password: config.mongo.pwd,
    email: 'johndoe@example.com',
    mobileNumber: 123456789
  });
  rootUser.save(() => {});
  adminUser = new User({
    username: 'adminUser',
    password: '123456789',
    email: 'admin.user@example.com',
    mobileNumber: 999999999
  });
  adminUser.save(() => {});
  employeeUser = new User({
    username: 'employeeUser',
    password: '123456789',
    email: 'employee.user@example.com',
    mobileNumber: 888888888
  });
  employeeUser.save(() => {});
});

after(() => {
  User.remove(() => {});
  Group.remove(() => {});
  // required because https://github.com/Automattic/mongoose/issues/1251#issuecomment-65793092
  mongoose.models = {};
  mongoose.modelSchemas = {};
  mongoose.connection.close();
});

describe('## root user w Group APIs', () => {
  it('should get valid JWT token', () =>
    request(app)
      .post('/api/v1/auth/login')
      .send({ username: rootUser.username, password: rootUser.password })
      .expect(httpStatus.OK)
      .then((res) => {
        expect(res.body).to.have.property('token');
        rootJwtToken = `Bearer ${res.body.token}`;
      })
  );

  let group = {
    name: 'Admin',
    description: 'Administration group'
  };

  describe('# POST /api/v1/groups', () => {
    ...
 });
});

describe('## admin user w Group APIs', () => {
  it('should get valid JWT token', () =>
    request(app)
      .post('/api/v1/auth/login')
      .send({ username: adminUser.username, password: adminUser.password })
      .expect(httpStatus.OK)
      .then((res) => {
        expect(res.body).to.have.property('token');
        adminJwtToken = `Bearer ${res.body.token}`;
      })
  );

  let group = {
    name: 'Marketing',
    description: 'Marketing group'
  };

  describe('# POST /api/v1/groups', () => {
  });
 });

describe('## employee user w Group APIs', () => {
  it('should get valid JWT token', () =>
    request(app)
      .post('/api/v1/auth/login')
      .send({ username: employeeUser.username, password: employeeUser.password })
      .expect(httpStatus.OK)
      .then((res) => {
        expect(res.body).to.have.property('token');
        employeeJwtToken = `Bearer ${res.body.token}`;
      })
  );

  let group = {
    name: 'Union',
    description: 'Union group'
  };

 describe('# POST /api/v1/groups', () => {
   ...
  });
});

这种方式运行良好...现在我可以将我的工作集中在授权()快速中间件上,以检查用户的权限与资源权限

    const router = express.Router(); // eslint-disable-line new-cap

router.route('/')
   /** GET /api/groups - Get list of groups */
  .get(expressJwt({ secret: config.jwtSecret }), authorize('group'), groupCtrl.list)

  /** POST /api/groups - Create new group */
  .post(expressJwt({ secret: config.jwtSecret }), validate(paramValidation.createGroup), groupCtrl.create);