From 071e253b31f318a4abd12ad23365af18d4fc3409 Mon Sep 17 00:00:00 2001 From: bnematzadeh Date: Sun, 10 Nov 2024 06:09:09 -0700 Subject: [PATCH] Add RangeValidator for take paramater --- server/lib/user/user.get.js | 5 +++++ server/test/controllers/user/user.get.test.js | 14 ++++++++++++++ server/utils/coreErrors.js | 8 ++++++++ 3 files changed, 27 insertions(+) diff --git a/server/lib/user/user.get.js b/server/lib/user/user.get.js index e99cb844d7..0375fb270b 100644 --- a/server/lib/user/user.get.js +++ b/server/lib/user/user.get.js @@ -1,11 +1,13 @@ const { Op } = require('sequelize'); const Sequelize = require('sequelize'); +const { RangeError } = require('../../utils/coreErrors'); const db = require('../../models'); const DEFAULT_OPTIONS = { fields: ['id', 'firstname', 'lastname', 'selector', 'email'], expand: [], skip: 0, + limit: 20, order_dir: 'ASC', order_by: 'firstname', }; @@ -40,6 +42,9 @@ async function get(options) { }; if (optionsWithDefault.take) { + if (optionsWithDefault.take > DEFAULT_OPTIONS.limit) { + throw new RangeError('The value of the limit parameter is out of range'); + } queryParams.limit = optionsWithDefault.take; } diff --git a/server/test/controllers/user/user.get.test.js b/server/test/controllers/user/user.get.test.js index 951c93d818..3994f68f20 100644 --- a/server/test/controllers/user/user.get.test.js +++ b/server/test/controllers/user/user.get.test.js @@ -70,4 +70,18 @@ describe('GET /api/v1/user', () => { .expect('Content-Type', /json/) .expect(401); }); + + it('should return 500 for an out-of-range limit value', async () => { + await authenticatedRequest + .get('/api/v1/user?take=30') + .expect('Content-Type', /json/) + .expect(500); + }); + + it('should return 200 for a limit value within the valid range.', async () => { + await authenticatedRequest + .get('/api/v1/user?take=15') + .expect('Content-Type', /json/) + .expect(200); + }); }); diff --git a/server/utils/coreErrors.js b/server/utils/coreErrors.js index 74b3c3ff73..f3c4ef41a3 100644 --- a/server/utils/coreErrors.js +++ b/server/utils/coreErrors.js @@ -12,6 +12,13 @@ class NotFoundError extends Error { } } +class RangeError extends Error { + constructor(message) { + super(); + this.message = message; + } +} + class NoValuesFoundError extends Error { constructor(message) { super(); @@ -80,4 +87,5 @@ module.exports = { ConflictError, ForbiddenError, TooManyRequests, + RangeError, };