Skip to content

Commit

Permalink
fix: got an idea how default model releationships are defined
Browse files Browse the repository at this point in the history
  • Loading branch information
ShubhamPalriwala committed Mar 7, 2022
1 parent d8d07c0 commit 8ad0495
Show file tree
Hide file tree
Showing 14 changed files with 35 additions and 28 deletions.
4 changes: 2 additions & 2 deletions data/datacreator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ async function createBaskets () {
return await Promise.all(
baskets.map(async basket => {
return await BasketModel.create({
UserId: basket.UserId
UserModelId: basket.UserId
}).catch((err: unknown) => {
logger.error(`Could not insert Basket for UserId ${basket.UserId}: ${utils.getErrorMessage(err)}`)
})
Expand Down Expand Up @@ -601,7 +601,7 @@ async function createSecurityQuestions () {
}

async function createSecurityAnswer (UserId: number, SecurityQuestionId: number, answer: string) {
return await SecurityAnswerModel.create({ SecurityQuestionId, UserId, answer }).catch((err: unknown) => {
return await SecurityAnswerModel.create({ SecurityQuestionModelId:SecurityQuestionId, UserModelId:UserId, answer }).catch((err: unknown) => {
logger.error(`Could not insert SecurityAnswer ${answer} mapped to UserId ${UserId}: ${utils.getErrorMessage(err)}`)
})
}
Expand Down
6 changes: 3 additions & 3 deletions models/basket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ class BasketModel extends Model<
InferAttributes<BasketModel>,
InferCreationAttributes<BasketModel>
> {
declare UserId: CreationOptional<number>
declare UserModelId: CreationOptional<number>
declare id: CreationOptional<number>
declare coupon: CreationOptional<string> | null
declare Products?: NonAttribute<ProductModel[]>
declare ProductModels?: NonAttribute<ProductModel[]>
}

const BasketModelInit=(sequelize:Sequelize)=>{
Expand All @@ -35,7 +35,7 @@ BasketModel.init(
autoIncrement: true
},
coupon: DataTypes.STRING,
UserId:{
UserModelId:{
type: DataTypes.INTEGER
}
},
Expand Down
2 changes: 0 additions & 2 deletions models/captcha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ CaptchaModel.init(
{
captchaId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
captcha: DataTypes.STRING,
answer: DataTypes.STRING
Expand Down
4 changes: 3 additions & 1 deletion models/quantity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ InferCreationAttributes<QuantityModel>

const QuantityModelInit=(sequelize:Sequelize)=>{
QuantityModel.init(
// @ts-expect-error
{
ProductId:{
type: DataTypes.INTEGER
},
id: {
type: DataTypes.INTEGER,
primaryKey: true,
Expand Down
11 changes: 6 additions & 5 deletions models/securityAnswer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,20 @@ class SecurityAnswerModel extends Model<
InferAttributes<SecurityAnswerModel>,
InferCreationAttributes<SecurityAnswerModel>
> {
declare SecurityQuestionId: number
declare UserId: number
declare SecurityQuestionModelId: number
declare UserModelId: number
declare id: CreationOptional<number>
declare answer: string
}

const SecurityAnswerModelInit=(sequelize:Sequelize)=>{
SecurityAnswerModel.init(
{
UserId:{
type: DataTypes.INTEGER
UserModelId:{
type: DataTypes.INTEGER,
unique: true
},
SecurityQuestionId:{
SecurityQuestionModelId:{
type: DataTypes.INTEGER
},

Expand Down
2 changes: 1 addition & 1 deletion routes/2fa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ async function verify (req: Request, res: Response) {
}
utils.solveIf(challenges.twoFactorAuthUnsafeSecretStorageChallenge, () => { return user.email === 'wurstbrot@' + config.get('application.domain') })

const [basket] = await BasketModel.findOrCreate({ where: { UserId: userId } })
const [basket] = await BasketModel.findOrCreate({ where: { UserModelId: userId } })

const token = security.authorize(plainUser)
plainUser.bid = basket.id // keep track of original basket for challenge solution check
Expand Down
8 changes: 5 additions & 3 deletions routes/basket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ module.exports = function retrieveBasket () {
const user = security.authenticatedUsers.from(req)
return user && id && id !== 'undefined' && id !== 'null' && id !== 'NaN' && user.bid && user.bid != id // eslint-disable-line eqeqeq
})
if (basket?.Products && basket.Products.length > 0) {
for (let i = 0; i < basket.Products.length; i++) {
basket.Products[i].name = req.__(basket.Products[i].name)
if (basket?.ProductModels && basket.ProductModels.length > 0) {
for (let i = 0; i < basket.ProductModels.length; i++) {
basket.ProductModels[i].name = req.__(basket.ProductModels[i].name)
}
}
// TODO: This works but in response it sends [ProductModels] field but the API and tests
// expect [Products] named field
res.json(utils.queryResultToJson(basket))
}).catch((error: Error) => {
next(error)
Expand Down
10 changes: 7 additions & 3 deletions routes/basketItems.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ const utils = require('../lib/utils')
const challenges = require('../data/datacache').challenges
const security = require('../lib/insecurity')

interface RequestWithRawBody extends Request {
rawBody: string
}

module.exports.addBasketItem = function addBasketItem () {
return (req: Request, res: Response, next: NextFunction) => {
const result = utils.parseJsonCustom(req.body) // Discuss this change once
return (req: RequestWithRawBody, res: Response, next: NextFunction) => {
const result = utils.parseJsonCustom(req.rawBody)
const productIds = []
const basketIds = []
const quantities = []
Expand All @@ -40,7 +44,7 @@ module.exports.addBasketItem = function addBasketItem () {
utils.solveIf(challenges.basketManipulateChallenge, () => { return user && basketItem.BasketId && basketItem.BasketId !== 'undefined' && user.bid != basketItem.BasketId }) // eslint-disable-line eqeqeq

const basketItemInstance = BasketItemModel.build(basketItem)
basketItemInstance.save().then((addedBasketItem: BasketItemModel) => {
basketItemInstance.save().then((addedBasketItem: BasketItemModel) => {
res.json({ status: 'success', data: addedBasketItem })
}).catch((error: Error) => {
next(error)
Expand Down
2 changes: 1 addition & 1 deletion routes/dataErasure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ router.get('/', async (req: Request, res: Response, next: NextFunction): Promise
if (!answer) {
throw new Error('No answer found!')
}
const question = await SecurityQuestionModel.findByPk(answer.SecurityQuestionId)
const question = await SecurityQuestionModel.findByPk(answer.SecurityQuestionModelId)
if (!question) {
throw new Error('No question found!')
}
Expand Down
6 changes: 3 additions & 3 deletions routes/fileUpload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ const vm = require('vm')
const unzipper = require('unzipper')
const path = require('path')

function matchesSystemIniFile (text) {
function matchesSystemIniFile (text: string) {
const match = text.match(/(; for 16-bit app support|drivers|mci|driver32|386enh|keyboard|boot|display)/gi)
return match && match.length >= 2
}

function matchesEtcPasswdFile (text) {
function matchesEtcPasswdFile (text: string) {
const match = text.match(/\w*:\w*:\d*:\d*:\w*:.*/gi)
return match && match.length >= 2
}
Expand Down Expand Up @@ -52,7 +52,7 @@ function handleZipFileUpload ({ file }: Request, res: Response, next: NextFuncti
} else {
entry.autodrain()
}
}).on('error', function (err) { next(err) })
}).on('error', function (err: unknown) { next(err) })
})
})
})
Expand Down
2 changes: 1 addition & 1 deletion routes/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const config = require('config')
module.exports = function login () {
function afterLogin (user: { data: User, bid: number }, res: Response, next: NextFunction) {
verifyPostLoginChallenges(user) // vuln-code-snippet hide-line
BasketModel.findOrCreate({ where: { UserId: user.data.id } })
BasketModel.findOrCreate({ where: { UserModelId: user.data.id } })
.then(([basket]: [BasketModel, boolean]) => {
const token = security.authorize(user)
user.bid = basket.id // keep track of original basket
Expand Down
2 changes: 1 addition & 1 deletion routes/order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ module.exports = function placeOrder () {
let totalPrice = 0
const basketProducts: Product[] = []
let totalPoints = 0
basket.Products?.forEach(({ BasketItem, price, deluxePrice, name, id }) => {
basket.ProductModels?.forEach(({ BasketItem, price, deluxePrice, name, id }) => {
if (BasketItem) {
utils.solveIf(challenges.christmasSpecialChallenge, () => { return BasketItem.ProductId === products.christmasSpecial.id })

Expand Down
2 changes: 1 addition & 1 deletion routes/resetPassword.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ module.exports = function resetPassword () {
}]
}).then((data: SecurityAnswerModel | null) => {
if (data && security.hmac(answer) === data.answer) {
UserModel.findByPk(data.UserId).then((user: UserModel | null) => {
UserModel.findByPk(data.UserModelId).then((user: UserModel | null) => {
user?.update({ password: newPassword }).then((user: UserModel) => {
verifySecurityAnswerChallenges(user, answer)
res.json({ user })
Expand Down
2 changes: 1 addition & 1 deletion routes/securityQuestion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ module.exports = function securityQuestion () {
}]
}).then((answer: SecurityAnswerModel | null) => {
if (answer) {
SecurityQuestionModel.findByPk(answer.SecurityQuestionId).then((question: SecurityQuestionModel | null) => {
SecurityQuestionModel.findByPk(answer.SecurityQuestionModelId).then((question: SecurityQuestionModel | null) => {
res.json({ question })
}).catch((error: Error) => {
next(error)
Expand Down

0 comments on commit 8ad0495

Please sign in to comment.