- [API] Finished White Box tests, passed all of them, spell API considered finished

This commit is contained in:
Alexis
2020-05-23 01:02:45 +02:00
parent acd380e084
commit 473f8f44c1
2 changed files with 343 additions and 252 deletions

View File

@@ -19,7 +19,7 @@ const routes = require('./routes')
// Builds app w/ express // Builds app w/ express
let app = express() let app = express()
app.use(bodyParser.json()) app.use(bodyParser.json({ limit: '10kb' }))
app.use(cors()) app.use(cors())
app.use(morgan('tiny')) app.use(morgan('tiny'))
app.use(helmet()) app.use(helmet())

View File

@@ -8,8 +8,9 @@ let router = express.Router()
const connection = require('../database/connection') const connection = require('../database/connection')
const db = connection.db const db = connection.db
// ID validation // Validations
const regexInt = RegExp(/^[1-9]\d*$/); const regexInt = RegExp(/^[1-9]\d*$/)
const regexXSS = RegExp(/<[^>]*script/)
// Model validation // Model validation
const Validator = require('jsonschema').Validator const Validator = require('jsonschema').Validator
@@ -29,9 +30,9 @@ const getSpells = () => {
db.query(query, async (err, result) => { db.query(query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error')) reject(new HttpError(500, 'Database error'))
} else if (result.length == 0) { } else if (result.length == 0) {
reject(new HttpError(404, 'Error: No spells were found')) reject(new HttpError(404, 'No spells were found'))
} }
// Loops over the results to fetch the associated tables // Loops over the results to fetch the associated tables
@@ -56,7 +57,12 @@ router.get('/', async (req, res) => {
res.end(JSON.stringify(v)) res.end(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
res.status(err.code).send(err.message) res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
}) })
}) })
@@ -69,7 +75,7 @@ const getSpell = (id) => {
db.query(query, async (err, result) => { db.query(query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error')) reject(new HttpError(500, 'Database error'))
} }
try { try {
result = buildSpell(result[0]) result = buildSpell(result[0])
@@ -90,7 +96,12 @@ router.get('/:id/', async (req, res) => {
res.end(JSON.stringify(v)) res.end(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
res.status(err.code).send(err.message) res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
}) })
}) })
@@ -104,8 +115,9 @@ const addSpell = (s) => {
reject(new HttpError(403, "Error: Spell cannot be nothing !")) reject(new HttpError(403, "Error: Spell cannot be nothing !"))
} else if (!v.validate(s, Spell).valid) { } else if (!v.validate(s, Spell).valid) {
reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, Spell).errors)) reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, Spell).errors))
} } else if (isXSSAttempt(s.name) || isXSSAttempt(s.description) || isXSSAttempt(s.cost)) {
reject(new HttpError(403, 'Injection attempt detected, aborting the request.'))
} else {
let query = let query =
'INSERT INTO spell (name, description' 'INSERT INTO spell (name, description'
@@ -125,7 +137,7 @@ const addSpell = (s) => {
db.query(query, async (err, result) => { db.query(query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error')) reject(new HttpError(500, 'Database error'))
} }
console.log(`Inserted "${s.name}" with ID ${result.insertId}, affecting ${result.affectedRows} row(s)`) console.log(`Inserted "${s.name}" with ID ${result.insertId}, affecting ${result.affectedRows} row(s)`)
@@ -137,14 +149,14 @@ const addSpell = (s) => {
if (s.schools.length > 0) { if (s.schools.length > 0) {
for (let i = 0; i < s.schools.length; i++) { for (let i = 0; i < s.schools.length; i++) {
if (!regexInt.test(s.schools[i].id)) { if (!regexInt.test(s.schools[i].id)) {
reject(new HttpError(403, 'Error: Query error - School ID should be an integer !')) reject(new HttpError(403, 'Query error - School ID should be an integer !'))
} }
let insert_schools_query = `INSERT INTO spells_schools (id_spell, id_school) VALUES (${new_spell_id}, ${s.schools[i].id})` let insert_schools_query = `INSERT INTO spells_schools (id_spell, id_school) VALUES (${new_spell_id}, ${s.schools[i].id})`
db.query(insert_schools_query, async (err, result) => { db.query(insert_schools_query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - No schools matching this ID')) reject(new HttpError(500, 'Database error - No schools matching this ID'))
} else { } else {
console.log(`Associated school ID ${s.schools[i].id} to spell ID ${new_spell_id}, affecting ${result.affectedRows} row(s)`) console.log(`Associated school ID ${s.schools[i].id} to spell ID ${new_spell_id}, affecting ${result.affectedRows} row(s)`)
resolve() resolve()
@@ -166,13 +178,13 @@ const addSpell = (s) => {
if (s.variables.length > 0) { if (s.variables.length > 0) {
for (let i = 0; i < s.variables.length; i++) { for (let i = 0; i < s.variables.length; i++) {
if (!regexInt.test(s.variables[i].id)) { if (!regexInt.test(s.variables[i].id)) {
reject(new HttpError(403, 'Error: Query error - Variable ID should be an integer !')) reject(new HttpError(403, 'Query error - Variable ID should be an integer !'))
} }
let insert_variables_query = `INSERT INTO spells_variables (id_spell, id_variable) VALUES (${new_spell_id}, ${s.variables[i].id})` let insert_variables_query = `INSERT INTO spells_variables (id_spell, id_variable) VALUES (${new_spell_id}, ${s.variables[i].id})`
db.query(insert_variables_query, async (err, result) => { db.query(insert_variables_query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - No variables matching this ID')) reject(new HttpError(500, 'Database error - No variables matching this ID'))
} else { } else {
console.log(`Associated variable ID ${s.variables[i].id} to spell ID ${new_spell_id}, affecting ${result.affectedRows} row(s)`) console.log(`Associated variable ID ${s.variables[i].id} to spell ID ${new_spell_id}, affecting ${result.affectedRows} row(s)`)
resolve() resolve()
@@ -194,13 +206,13 @@ const addSpell = (s) => {
if (s.ingredients.length > 0) { if (s.ingredients.length > 0) {
for (let i = 0; i < s.ingredients.length; i++) { for (let i = 0; i < s.ingredients.length; i++) {
if (!regexInt.test(s.ingredients[i].id)) { if (!regexInt.test(s.ingredients[i].id)) {
reject(new HttpError(403, 'Error: Query error - Ingredient ID should be an integer !')) reject(new HttpError(403, 'Query error - Ingredient ID should be an integer !'))
} }
let insert_ingredients_query = `INSERT INTO spells_ingredients (id_spell, id_ingredient) VALUES (${new_spell_id}, ${s.ingredients[i].id})` let insert_ingredients_query = `INSERT INTO spells_ingredients (id_spell, id_ingredient) VALUES (${new_spell_id}, ${s.ingredients[i].id})`
db.query(insert_ingredients_query, async (err, result) => { db.query(insert_ingredients_query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - No ingredients matching this ID')) reject(new HttpError(500, 'Database error - No ingredients matching this ID'))
} else { } else {
console.log(`Associated ingredient ID ${s.ingredients[i].id} to spell ID ${new_spell_id}, affecting ${result.affectedRows} row(s)`) console.log(`Associated ingredient ID ${s.ingredients[i].id} to spell ID ${new_spell_id}, affecting ${result.affectedRows} row(s)`)
resolve() resolve()
@@ -224,6 +236,7 @@ const addSpell = (s) => {
reject(err) reject(err)
}) })
}) })
}
}).catch(err => { }).catch(err => {
throw err throw err
}) })
@@ -235,7 +248,12 @@ router.post('/', async (req, res) => {
res.send(JSON.stringify(v)) res.send(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
res.status(err.code).send(err.message) res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
}) })
}) })
@@ -255,8 +273,9 @@ const updateSpell = (s, id) => {
reject(new HttpError(403, "Error: Spell cannot be nothing !")) reject(new HttpError(403, "Error: Spell cannot be nothing !"))
} else if (!v.validate(s, Spell).valid) { } else if (!v.validate(s, Spell).valid) {
reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, Spell).errors)) reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, Spell).errors))
} } else if (isXSSAttempt(s.name) || isXSSAttempt(s.description) || isXSSAttempt(s.cost)) {
reject(new HttpError(403, 'Injection attempt detected, aborting the request.'))
} else {
let query = let query =
'UPDATE spell SET ' 'UPDATE spell SET '
@@ -271,7 +290,7 @@ const updateSpell = (s, id) => {
db.query(query, async (err, result) => { db.query(query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - Spell update failed')) reject(new HttpError(500, 'Database error - Spell update failed'))
} }
console.log(`Updated "${s.name}" on ID ${old_spell.id}, affecting ${result.affectedRows} row(s)`) console.log(`Updated "${s.name}" on ID ${old_spell.id}, affecting ${result.affectedRows} row(s)`)
@@ -284,21 +303,21 @@ const updateSpell = (s, id) => {
db.query(delete_schools_query, async (err, result) => { db.query(delete_schools_query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - Spell school deletion failed.')) reject(new HttpError(500, 'Database error - Spell school deletion failed.'))
} }
}) })
for (let i = 0; i < s.schools.length; i++) { for (let i = 0; i < s.schools.length; i++) {
if (!regexInt.test(s.schools[i].id)) { if (!regexInt.test(s.schools[i].id)) {
reject(new HttpError(403, 'Error: Query error - School ID should be an integer !')) reject(new HttpError(403, 'Query error - School ID should be an integer !'))
} else {} } else {}
let update_schools_query = `INSERT INTO spells_schools (id_spell, id_school) VALUES (${old_spell.id}, ${s.schools[i].id})` let update_schools_query = `INSERT INTO spells_schools (id_spell, id_school) VALUES (${old_spell.id}, ${s.schools[i].id})`
db.query(update_schools_query, async (err, result) => { db.query(update_schools_query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - No schools matching this ID')) reject(new HttpError(500, 'Database error - No schools matching this ID'))
} else { } else {
console.log(`Updated association "${s.schools[i].name}" to spell ID ${old_spell.id}`) console.log(`Updated association school ID ${s.schools[i].id} to spell ID ${old_spell.id}`)
resolve() resolve()
} }
}) })
@@ -321,21 +340,21 @@ const updateSpell = (s, id) => {
db.query(delete_variables_query, async (err, result) => { db.query(delete_variables_query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - Spell variable deletion failed.')) reject(new HttpError(500, 'Database error - Spell variable deletion failed.'))
} }
}) })
for (let i = 0; i < s.variables.length; i++) { for (let i = 0; i < s.variables.length; i++) {
if (!regexInt.test(s.variables[i].id)) { if (!regexInt.test(s.variables[i].id)) {
reject(new HttpError(403, 'Error: Query error - Variable ID should be an integer !')) reject(new HttpError(403, 'Query error - Variable ID should be an integer !'))
} }
let update_variables_query = `INSERT INTO spells_variables (id_spell, id_variable) VALUES (${old_spell.id}, ${s.variables[i].id})` let update_variables_query = `INSERT INTO spells_variables (id_spell, id_variable) VALUES (${old_spell.id}, ${s.variables[i].id})`
db.query(update_variables_query, async (err, result) => { db.query(update_variables_query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - No variables matching this ID')) reject(new HttpError(500, 'Database error - No variables matching this ID'))
} else { } else {
console.log(`Updated association "${s.variables[i].name}" to spell ID ${old_spell.id}`) console.log(`Updated variable ID "${s.variables[i].id}" to spell ID ${old_spell.id}`)
resolve() resolve()
} }
}) })
@@ -358,7 +377,7 @@ const updateSpell = (s, id) => {
db.query(delete_ingredients_query, async (err, result) => { db.query(delete_ingredients_query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - Spell ingredients deletion failed.')) reject(new HttpError(500, 'Database error - Spell ingredients deletion failed.'))
} }
console.log(result) console.log(result)
}) })
@@ -366,15 +385,15 @@ const updateSpell = (s, id) => {
// Loops over ingredients query // Loops over ingredients query
for (let i = 0; i < s.ingredients.length; i++) { for (let i = 0; i < s.ingredients.length; i++) {
if (!regexInt.test(s.ingredients[i].id)) { if (!regexInt.test(s.ingredients[i].id)) {
reject(new HttpError(403, 'Error: Query error - Ingredient ID should be an integer !')) reject(new HttpError(403, 'Query error - Ingredient ID should be an integer !'))
} }
let update_ingredients_query = `INSERT INTO spells_ingredients (id_spell, id_ingredient) VALUES (${old_spell.id}, ${s.ingredients[i].id})` let update_ingredients_query = `INSERT INTO spells_ingredients (id_spell, id_ingredient) VALUES (${old_spell.id}, ${s.ingredients[i].id})`
db.query(update_ingredients_query, async (err, result) => { db.query(update_ingredients_query, async (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error - No ingredients matching this ID')) reject(new HttpError(500, 'Database error - No ingredients matching this ID'))
} else { } else {
console.log(`Updated association "${s.ingredients[i].name}" to spell ID ${old_spell.id}`) console.log(`Updated ingredient ID "${s.ingredients[i].id}" to spell ID ${old_spell.id}`)
resolve() resolve()
} }
}) })
@@ -395,17 +414,17 @@ const updateSpell = (s, id) => {
] ]
Promise.all(promises) Promise.all(promises)
.then(data => { .then(() => {
console.log(data) resolve(getSpell(old_spell.id))
resolve(data)
}) })
.catch(err => { .catch(err => {
reject(err) reject(err)
}) })
}) })
}
}) })
.catch(err => { .catch(err => {
console.log(err) throw err
}) })
} }
router.put('/:id/', async (req, res) => { router.put('/:id/', async (req, res) => {
@@ -415,52 +434,106 @@ router.put('/:id/', async (req, res) => {
res.send(JSON.stringify(v)) res.send(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
res.status(err.code).send(err.message) res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
}) })
}) })
// DELETE ONE ------------------ // DELETE ONE ------------------
const deleteSpell = (id) => { const deleteSpell = (id) => {
return new Promise((resolve, reject) => { return new Promise(async (resolve, reject) => {
let delete_schools_query = `DELETE FROM spells_schools WHERE id_spell = ${db.escape(id)}` // Check if spell exists
let delete_variables_query = `DELETE FROM spells_variables WHERE id_spell = ${db.escape(id)}` let old_spell = await getSpell(id)
let delete_ingredients_query = `DELETE FROM spells_ingredients WHERE id_spell = ${db.escape(id)}` .catch(err => {
let delete_spell_query = `DELETE FROM spell WHERE id = ${db.escape(id)}` reject(err)
db.query(delete_schools_query, async (err, result) => {
if (err) {
console.log(err)
reject(new HttpError(500, 'Error: Spell schools deletion failed'))
}
console.log(`Deleted schools associated to spell ID ${db.escape(id)}`)
}) })
if (old_spell == undefined) {
reject((new HttpError(404, 'No spells matching this ID')))
} else {
let deleteSchoolsData = () => {
return new Promise((resolve, reject) => {
let delete_schools_query = `DELETE FROM spells_schools WHERE id_spell = ${db.escape(id)}`
db.query(delete_schools_query, async (err, result) => {
if (err) {
reject(new HttpError(500, 'Spell schools deletion failed'))
} else {
console.log(`Deleted schools associated to spell ID ${db.escape(id)}`)
resolve()
}
})
})
}
let deleteVariablesData = () => {
return new Promise((resolve, reject) => {
let delete_variables_query = `DELETE FROM spells_variables WHERE id_spell = ${db.escape(id)}`
db.query(delete_variables_query, async (err, result) => { db.query(delete_variables_query, async (err, result) => {
if (err) { if (err) {
console.log(err) console.log(err)
reject(new HttpError(500, 'Error: Spell variables deletion failed')) reject(new HttpError(500, 'Spell variables deletion failed'))
} } else {
console.log(`Deleted variables associated to spell ID ${db.escape(id)}`) console.log(`Deleted variables associated to spell ID ${db.escape(id)}`)
resolve()
}
}) })
})
}
let deleteIngredientsData = () => {
return new Promise((resolve, reject) => {
let delete_ingredients_query = `DELETE FROM spells_ingredients WHERE id_spell = ${db.escape(id)}`
db.query(delete_ingredients_query, async (err, result) => { db.query(delete_ingredients_query, async (err, result) => {
if (err) { if (err) {
console.log(err) console.log(err)
reject(new HttpError(500, 'Error: Spell ingredients deletion failed')) reject(new HttpError(500, 'Spell ingredients deletion failed'))
} } else {
console.log(`Deleted ingredients associated to spell ID ${db.escape(id)}`) console.log(`Deleted ingredients associated to spell ID ${db.escape(id)}`)
resolve()
}
}) })
})
}
let deleteSpellData = () => {
return new Promise((resolve, reject) => {
let delete_spell_query = `DELETE FROM spell WHERE id = ${db.escape(id)}`
db.query(delete_spell_query, async (err, result) => { db.query(delete_spell_query, async (err, result) => {
if (err) { if (err) {
console.log(err) console.log(err)
reject(new HttpError(500, 'Error: Spell deletion failed')) reject(new HttpError(500, 'Spell deletion failed'))
} } else {
console.log(`Deleted spell ID ${db.escape(id)}, affecting ${result.affectedRows} rows`) console.log(`Deleted spell ID ${db.escape(id)}, affecting ${result.affectedRows} rows`)
resolve()
}
}) })
})
}
const promises = [
deleteSchoolsData(),
deleteVariablesData(),
deleteIngredientsData()
]
Promise.all(promises)
.then(() => {
deleteSpellData()
let response = {
message: `Spell ID ${id} was successfully deleted.`
}
resolve(response)
})
.catch(err => {
reject(err)
})
}
}) })
.catch(err => { .catch(err => {
throw err throw err
@@ -473,7 +546,12 @@ router.delete('/:id/', async (req, res) => {
res.send(JSON.stringify(v)) res.send(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
res.status(err.code).send(err.message) res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
}) })
}) })
@@ -485,10 +563,15 @@ router.param('id', (req, res, next, id) => {
if (regexInt.test(id)) { if (regexInt.test(id)) {
next() next()
} else { } else {
throw new HttpError(403, 'Error: Provided ID must be an integer and not zero') throw new HttpError(403, 'Provided ID must be an integer and not zero')
} }
} catch (err) { } catch (err) {
res.status(err.code).send(err.message) res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
} }
}) })
@@ -511,7 +594,7 @@ const buildSpell = async (spell) => {
db.query(query, (err, result) => { db.query(query, (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error')) reject(new HttpError(500, 'Database error'))
} else { } else {
s.schools = result s.schools = result
resolve(s) resolve(s)
@@ -534,7 +617,7 @@ const buildSpell = async (spell) => {
db.query(query, (err, result) => { db.query(query, (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error')) reject(new HttpError(500, 'Database error'))
} else { } else {
s.variables = result s.variables = result
resolve(s) resolve(s)
@@ -557,7 +640,7 @@ const buildSpell = async (spell) => {
db.query(query, (err, result) => { db.query(query, (err, result) => {
if (err) { if (err) {
reject(new HttpError(500, 'Error: Database error')) reject(new HttpError(500, 'Database error'))
} else { } else {
s.ingredients = result s.ingredients = result
resolve(s) resolve(s)
@@ -586,4 +669,12 @@ const isEmptyObject = (obj) => {
} }
} }
const isXSSAttempt = (string) => {
if (regexXSS.test(string)) {
return true
} else {
return false
}
}
module.exports = router module.exports = router