forked from juice-shop/juice-shop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coupon.ts
35 lines (32 loc) · 1.13 KB
/
coupon.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
* Copyright (c) 2014-2023 Bjoern Kimminich & the OWASP Juice Shop contributors.
* SPDX-License-Identifier: MIT
*/
import { type Request, type Response, type NextFunction } from 'express'
import { BasketModel } from '../models/basket'
const security = require('../lib/insecurity')
module.exports = function applyCoupon () {
return ({ params }: Request, res: Response, next: NextFunction) => {
const id = params.id
let coupon: string | undefined | null = params.coupon ? decodeURIComponent(params.coupon) : undefined
const discount = security.discountFromCoupon(coupon)
coupon = discount ? coupon : null
BasketModel.findByPk(id).then((basket: BasketModel | null) => {
if (basket != null) {
basket.update({ coupon: coupon?.toString() }).then(() => {
if (discount) {
res.json({ discount })
} else {
res.status(404).send('Invalid coupon.')
}
}).catch((error: Error) => {
next(error)
})
} else {
next(new Error('Basket with id=' + id + ' does not exist.'))
}
}).catch((error: Error) => {
next(error)
})
}
}