juice-shop

Форк
0
/
basketItems.ts 
100 строк · 3.9 Кб
1
/*
2
 * Copyright (c) 2014-2024 Bjoern Kimminich & the OWASP Juice Shop contributors.
3
 * SPDX-License-Identifier: MIT
4
 */
5

6
import { type Request, type Response, type NextFunction } from 'express'
7
import { BasketItemModel } from '../models/basketitem'
8
import { QuantityModel } from '../models/quantity'
9
import challengeUtils = require('../lib/challengeUtils')
10

11
import * as utils from '../lib/utils'
12
import { challenges } from '../data/datacache'
13
const security = require('../lib/insecurity')
14

15
interface RequestWithRawBody extends Request {
16
  rawBody: string
17
}
18

19
module.exports.addBasketItem = function addBasketItem () {
20
  return (req: RequestWithRawBody, res: Response, next: NextFunction) => {
21
    const result = utils.parseJsonCustom(req.rawBody)
22
    const productIds = []
23
    const basketIds = []
24
    const quantities = []
25

26
    for (let i = 0; i < result.length; i++) {
27
      if (result[i].key === 'ProductId') {
28
        productIds.push(result[i].value)
29
      } else if (result[i].key === 'BasketId') {
30
        basketIds.push(result[i].value)
31
      } else if (result[i].key === 'quantity') {
32
        quantities.push(result[i].value)
33
      }
34
    }
35

36
    const user = security.authenticatedUsers.from(req)
37
    if (user && basketIds[0] && basketIds[0] !== 'undefined' && Number(user.bid) != Number(basketIds[0])) { // eslint-disable-line eqeqeq
38
      res.status(401).send('{\'error\' : \'Invalid BasketId\'}')
39
    } else {
40
      const basketItem = {
41
        ProductId: productIds[productIds.length - 1],
42
        BasketId: basketIds[basketIds.length - 1],
43
        quantity: quantities[quantities.length - 1]
44
      }
45
      challengeUtils.solveIf(challenges.basketManipulateChallenge, () => { return user && basketItem.BasketId && basketItem.BasketId !== 'undefined' && user.bid != basketItem.BasketId }) // eslint-disable-line eqeqeq
46

47
      const basketItemInstance = BasketItemModel.build(basketItem)
48
      basketItemInstance.save().then((addedBasketItem: BasketItemModel) => {
49
        res.json({ status: 'success', data: addedBasketItem })
50
      }).catch((error: Error) => {
51
        next(error)
52
      })
53
    }
54
  }
55
}
56

57
module.exports.quantityCheckBeforeBasketItemAddition = function quantityCheckBeforeBasketItemAddition () {
58
  return (req: Request, res: Response, next: NextFunction) => {
59
    void quantityCheck(req, res, next, req.body.ProductId, req.body.quantity).catch((error: Error) => {
60
      next(error)
61
    })
62
  }
63
}
64

65
module.exports.quantityCheckBeforeBasketItemUpdate = function quantityCheckBeforeBasketItemUpdate () {
66
  return (req: Request, res: Response, next: NextFunction) => {
67
    BasketItemModel.findOne({ where: { id: req.params.id } }).then((item: BasketItemModel | null) => {
68
      const user = security.authenticatedUsers.from(req)
69
      challengeUtils.solveIf(challenges.basketManipulateChallenge, () => { return user && req.body.BasketId && user.bid != req.body.BasketId }) // eslint-disable-line eqeqeq
70
      if (req.body.quantity) {
71
        if (item == null) {
72
          throw new Error('No such item found!')
73
        }
74
        void quantityCheck(req, res, next, item.ProductId, req.body.quantity)
75
      } else {
76
        next()
77
      }
78
    }).catch((error: Error) => {
79
      next(error)
80
    })
81
  }
82
}
83

84
async function quantityCheck (req: Request, res: Response, next: NextFunction, id: number, quantity: number) {
85
  const product = await QuantityModel.findOne({ where: { ProductId: id } })
86
  if (product == null) {
87
    throw new Error('No such product found!')
88
  }
89

90
  // is product limited per user and order, except if user is deluxe?
91
  if (!product.limitPerUser || (product.limitPerUser && product.limitPerUser >= quantity) || security.isDeluxe(req)) {
92
    if (product.quantity >= quantity) { // enough in stock?
93
      next()
94
    } else {
95
      res.status(400).json({ error: res.__('We are out of stock! Sorry for the inconvenience.') })
96
    }
97
  } else {
98
    res.status(400).json({ error: res.__('You can order only up to {{quantity}} items of this product.', { quantity: product.limitPerUser.toString() }) })
99
  }
100
}
101

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.