How to use the express-validator/check.param function in express-validator

To help you get started, we’ve selected a few express-validator examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github librewiki / liberty-engine / lib / routes / v1 / media-files.js View on Github external
filename(req, file, cb) {
    cb(null, `${uuidV4()}.${file.mimetype.split('/')[1]}`);
  },
});

const upload = multer({
  storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10 MiB
  },
});

router.get(
  '/:descriptionArticleTitle',
  [
    param('descriptionArticleTitle')
      .trim()
      .custom(v => Article.validateTitle(v)),
  ],
  [
    sanitizeParam('descriptionArticleTitle').trim(),
  ],
  middlewares.validate(),
  async (req, res, next) => {
    try {
      const mediaFile = await MediaFile.findOne({
        include: [{
          association: MediaFile.associations.descriptionArticle,
          where: {
            namespaceId: Namespace.Known.FILE.id,
            title: req.params.descriptionArticleTitle,
          },
github pietrzakadrian / bank / backend / src / controllers / users.controller.ts View on Github external
}
  );

/**
 * Checks whether the email already exists
 *
 * @Method GET
 * @URL /api/users/:email/isEmail
 *
 */
usersRouter
  .route("/:email/isEmail")

  .get(
    [
      param("email")
        .exists()
        .isEmail()
        .isLength({ min: 1, max: 255 })
    ],

    async (req: Request, res: Response, next: NextFunction) => {
      const userService = new UserService();
      const validationErrors = validationResult(req);
      const email: string = req.params.email;

      if (!validationErrors.isEmpty()) {
        const err: IResponseError = {
          success: false,
          code: HttpStatus.BAD_REQUEST,
          error: validationErrors.array()
        };
github pietrzakadrian / bank / backend / src / controllers / transactions.controller.ts View on Github external
}
  );

/**
 * Returns authorization key for the last
 *
 * @Method GET
 * @URL /api/transactions/:id/key
 *
 */
transactionsRouter
  .route("/:id/key")

  .get(
    [
      param("id")
        .exists()
        .isNumeric()
    ],

    async (req: Request, res: Response, next: NextFunction) => {
      const transactionService = new TransactionService();
      const userService = new UserService();
      const validationErrors = validationResult(req);
      const sender: User = await userService.getById(req.user.id);
      const recipient: User = await userService.getById(req.params.id);

      try {
        const authorizationKey: string = await transactionService.getAuthorizationKey(
          sender,
          recipient
        );
github librewiki / liberty-engine / lib / routes / v1 / blocks.js View on Github external
}
      if (userId) {
        scopes.push({ method: ['user', userId] });
      }
      const blocks = await Block.scope(scopes).findAll();
      return new Response.Success({ blocks }).send(res);
    } catch (err) {
      return next(err);
    }
  },
);

router.delete(
  '/:id',
  [
    param('id')
      .trim()
      .isInt(),
  ],
  [
    sanitizeParam('id').trim().toInt(),
  ],
  middlewares.validate(),
  async (req, res, next) => {
    try {
      const block = await Block.findByPk(req.params.id);
      await block.destroy();
      return new Response.Success().send(res);
    } catch (err) {
      return next(err);
    }
  },
github pietrzakadrian / bank / backend / src / controllers / messages.controller.ts View on Github external
}
  });

/**
 * Returns user messages
 *
 * @Method GET
 * @URL /api/additionals/messages
 *
 */
messagesRouter
  .route("/messages/:code")

  .get(
    [
      param("code")
        .exists()
        .isLength({ min: 2, max: 2 })
    ],
    async (req: Request, res: Response, next: NextFunction) => {
      const additionalService = new AdditionalService();
      const languageService = new LanguageService();
      const userService = new UserService();

      try {
        const language: Language = await languageService.getByCode(
          req.params.code
        );
        const user: User = await userService.getById(req.user.id);
        const messages = await additionalService.getMessages(user, language);

        res.status(HttpStatus.OK).json({
github weseek / growi / src / server / routes / apiv3 / user-group.js View on Github external
const userGroupRelation = await UserGroupRelation.createRelation(userGroup, user);
      await userGroupRelation.populate('relatedUser', User.USER_PUBLIC_FIELDS).execPopulate();

      return res.apiv3({ user, userGroup, userGroupRelation });
    }
    catch (err) {
      const msg = `Error occurred in adding the user "${username}" to group "${id}"`;
      logger.error(msg, err);
      return res.apiv3Err(new ErrorV3(msg, 'user-group-add-user-failed'));
    }
  });

  validator.users.delete = [
    param('id').trim().exists({ checkFalsy: true }),
    param('username').trim().exists({ checkFalsy: true }),
  ];

  /**
   * @swagger
   *
   *  paths:
   *    /user-groups/{id}/users:
   *      delete:
   *        tags: [UserGroup]
   *        description: remove a user from the userGroup
   *        parameters:
   *          - name: id
   *            in: path
   *            required: true
   *            description: id of userGroup
   *            schema:
github weseek / growi / src / server / routes / apiv3 / external-account.js View on Github external
module.exports = (crowi) => {
  const loginRequiredStrictly = require('../../middleware/login-required')(crowi);
  const adminRequired = require('../../middleware/admin-required')(crowi);
  const csrf = require('../../middleware/csrf')(crowi);

  const { ErrorV3, ExternalAccount } = crowi.models;

  validator.delete = [
    param('id').trim().exists({ checkFalsy: true }),
  ];
  const { ApiV3FormValidator } = crowi.middlewares;

  /**
   * @swagger
   *
   *  paths:
   *    /_api/v3/users/external-accounts/{id}/remove:
   *      delete:
   *        tags: [ExternalAccount]
   *        description: Delete ExternalAccount
   *        parameters:
   *          - name: id
   *            in: path
   *            required: true
   *            description: id of userGroup
github librewiki / liberty-engine / lib / routes / v1 / categories.js View on Github external
const express = require('express');
const { param } = require('express-validator/check');
const { sanitizeParam } = require('express-validator/filter');
const {
  Namespace, CategoryLink, Article,
} = require('../../models');
const middlewares = require('../../middlewares');
const Response = require('../../responses');

const router = express.Router({ mergeParams: true });

router.get(
  '/:categoryTitle',
  [
    param('categoryTitle')
      .trim()
      .custom(v => Article.validateTitle(v)),
  ],
  [
    sanitizeParam('categoryTitle').trim(),
  ],
  middlewares.validate(),
  async (req, res, next) => {
    try {
      const categoryLinks = await CategoryLink.findLinks(req.params.categoryTitle);
      const subcategories = [];
      const members = [];
      for (const link of categoryLinks) {
        if (link.sourceArticle.namespaceId === Namespace.Known.CATEGORY.id) {
          subcategories.push(link.sourceArticle.title);
        } else {
github thedevs-network / tgdr / server / utils / validators.ts View on Github external
.exists()
    .custom(value => categories.some(cat => cat.slug === value)),
  body('title', 'Title is not valid')
    .exists()
    .trim()
    .isLength({ min: 3, max: 54 })
    .withMessage('Title must be between 3 and 54 chars.'),
  body('description', 'Description is not valid')
    .exists()
    .trim()
    .isLength({ min: 20, max: 800 })
    .withMessage('Description must be between 20 and 800 chars.'),
];

export const entryValidator = [
  param('username', 'Username is not valid.')
    .exists()
    .trim()
    .isLength({ min: 5 })
    .withMessage('Username must have at least 5 chars.')
    .matches(/^[a-z]\w+$/i)
    .withMessage('Username is not valid. It must only contain A-Z, 0-9, _.'),
];

export const entriesValidator = [
  query('category')
    .optional()
    .custom(value => categories.some(cat => cat.slug === value))
    .withMessage('Category does not exist.'),
  query('limit')
    .optional()
    .custom(value => Number(value) < 50)
github librewiki / liberty-engine / lib / routes / v1 / roles.js View on Github external
);
        await NamespacePermission.destroy({ where: { roleId }, transaction: t });
        await NamespacePermission.bulkCreate(permissionsToInsert, { transaction: t });
        return new Response.Success().send(res);
      });
    } catch (err) {
      return next(err);
    }
  },
);

router.put(
  '/:roleId/special-permissions',
  middlewares.permission(SET_PERMISSION_OF_ROLE),
  [
    param('roleId')
      .trim()
      .isInt(),
    body('specialPermissions.*')
      .trim()
      .custom(v => SpecialPermissions[v] !== undefined),
  ],
  [
    sanitizeParam('roleId').trim().toInt(),
    sanitizeBody('specialPermissions.*').trim(),
  ],
  middlewares.validate(),
  async ({ params: { roleId }, body: { specialPermissions } }, res, next) => {
    try {
      const toSet = specialPermissions.map(p => SpecialPermission.nameKeyMap.get(p));
      const role = await Role.findByPk(roleId);
      await role.setSpecialPermissions(toSet);