Moved code to /src folder

This commit is contained in:
Alexis
2021-07-18 16:08:03 +02:00
parent fbc38207f7
commit d977ce6551
41 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,206 @@
// Bookshelf
const bookshelf = require('../database/bookshelf').bookshelf;
const model = require('../models/ingredient-model');
// Model validation
const Validator = require('jsonschema').Validator;
const validator = new Validator();
const IngredientValidation = require("../validations/IngredientValidation");
validator.addSchema(IngredientValidation, "/IngredientValidation");
// Validations
const isXSSAttempt = require('../functions').isXSSAttempt;
const isEmptyObject = require('../functions').isEmptyObject;
class IngredientRepository {
constructor() {
}
getAll() {
return new Promise((resolve, reject) => {
new model()
.fetchAll({ withRelated: ['spells'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "Il n'existe aucun ingrédient disponible.",
"code": 404,
});
});
});
}
getOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ withRelated: ['spells'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "L'ingrédient en question n'a pas pu être trouvé.",
"code": 404,
});
});
});
}
getSpellsFromOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ withRelated: ['spells', 'spells.schools', 'spells.variables', 'spells.ingredients', 'spells.schools.meta_schools'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "Les sortilèges liés à cet ingrédient n'ont pas pu être récupérés.",
"code": 404,
});
});
});
}
addOne(igr) {
return new Promise((resolve, reject) => {
// Checks if body exists and if the model fits, and throws errors if it doesn't
if (isEmptyObject(igr)) {
reject({
"message": "Le corps de la requête ne peut pas être vide.",
"code": 403,
});
} else if (!validator.validate(igr, IngredientValidation).valid) {
reject({
"message": `Le modèle d'ingrédient n'est pas respecté : ${validator.validate(s, IngredientValidation).errors}`,
"code": 403,
});
} else if (isXSSAttempt(igr.description)) {
reject({
"message": "Tentative d'injection XSS détectée, requête refusée.",
"code": 403,
});
} else {
bookshelf.transaction(t => {
return new model({
'name': igr.name,
'description': igr.description,
}).save(null, {
transacting: t
})
.catch(err => {
throw err;
});
})
.then(v => {
return v.load(['spells']);
})
.then(v => {
resolve(this.getOne(v.id));
})
.catch(err => {
console.log(err);
reject({
"message": "Une erreur d'insertion s'est produite.",
"code": 500,
});
});
}
});
}
updateOne(id, igr) {
return new Promise((resolve, reject) => {
// Checks if body exists and if the model fits, and throws errors if it doesn't
if (isEmptyObject(igr)) {
reject({
"message": "Le corps de la requête ne peut pas être vide.",
"code": 403,
});
} else if (!validator.validate(igr, IngredientValidation).valid) {
reject({
"message": `Le modèle d'ingrédient n'est pas respecté : ${validator.validate(s, IngredientValidation).errors}`,
"code": 403,
});
} else if (isXSSAttempt(igr.description)) {
reject({
"message": "Tentative d'injection XSS détectée, requête refusée.",
"code": 403,
});
} else {
new model({ id: id })
.fetch({ require: true, withRelated: ['spells'] })
.then(v => {
bookshelf.transaction(t => {
return v.save({
'name': igr.name,
'description': igr.description,
}, {
method: 'update',
transacting: t
})
.catch(err => {
console.log(err);
throw err;
});
})
.then(v => {
return v.load(['spells']);
})
.then(v => {
resolve(this.getOne(v.id));
})
.catch(err => {
console.log(err);
reject({
"message": "Une erreur d'insertion s'est produite.",
"code": 500,
});
});
})
.catch(err => {
console.log(err);
reject({
"message": "L'ingrédient en question n'a pas été trouvé.",
"code": 404,
});
});
}
});
}
deleteOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ require: true, withRelated: ['spells'] })
.then(v => {
v.spells().detach();
v.destroy();
})
.then(() => {
resolve({
'message': 'Ingredient with ID ' + id + ' successfully deleted !'
});
})
.catch(err => {
console.log(err);
reject({
"message": "L'ingrédient en question n'a pas été trouvé.",
"code": 404,
});
});
});
}
}
module.exports = IngredientRepository;

View File

@@ -0,0 +1,51 @@
// Bookshelf
const model = require('../models/meta-school-model')
// Model validation
const Validator = require('jsonschema').Validator
const validator = new Validator()
const MetaSchoolValidation = require("../validations/MetaSchoolValidation")
validator.addSchema(MetaSchoolValidation, "/MetaSchoolValidation")
class MetaSchoolRepository {
constructor() {
}
getAll() {
return new Promise((resolve, reject) => {
new model()
.fetchAll({ withRelated: ['schools'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err)
reject({
"message": "Il n'existe aucune grande école disponible.",
"code": 404
});
})
})
}
getOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ withRelated: ['schools'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err)
reject({
"message": "La grande école en question n'a pas pu être trouvée.",
"code": 404
});
})
})
}
}
module.exports = MetaSchoolRepository

View File

@@ -0,0 +1,207 @@
// Bookshelf
const bookshelf = require('../database/bookshelf').bookshelf;
const model = require('../models/school-model');
// Model validation
const Validator = require('jsonschema').Validator;
const validator = new Validator();
const SchoolValidation = require("../validations/SchoolValidation");
validator.addSchema(SchoolValidation, "/SchoolValidation");
// Validations
const isXSSAttempt = require('../functions').isXSSAttempt;
const isEmptyObject = require('../functions').isEmptyObject;
class SchoolRepository {
constructor() {
}
getAll() {
return new Promise((resolve, reject) => {
new model()
.fetchAll({ withRelated: ['meta_schools'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "Il n'existe aucune école disponible.",
"code": 404,
});
});
});
}
getOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ withRelated: ['meta_schools'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "L'école en question n'a pas pu être trouvée.",
"code": 404,
});
});
});
}
getSpellsFromOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ withRelated: ['spells', 'spells.schools', 'spells.variables', 'spells.ingredients', 'spells.schools.meta_schools'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "Les sortilèges de cette école n'ont pas pu être récupérés.",
"code": 404,
});
});
});
}
addOne(s) {
return new Promise((resolve, reject) => {
// Checks if body exists and if the model fits, and throws errors if it doesn't
if (isEmptyObject(s)) {
reject({
"message": "Le corps de la requête ne peut pas être vide.",
"code": 403,
});
} else if (!validator.validate(s, SchoolValidation).valid) {
reject({
"message": `Le modèle d'école n'est pas respecté : ${validator.validate(s, SchoolValidation).errors}`,
"code": 403,
});
} else if (isXSSAttempt(s.name) || isXSSAttempt(s.description)) {
reject({
"message": "Tentative d'injection XSS détectée, requête refusée.",
"code": 403,
});
} else {
bookshelf.transaction(t => {
return new model({
'name': s.name,
'description': s.description,
'meta_school_id': s.meta_school_id,
}).save(null, {
transacting: t
})
.catch(err => {
throw err;
});
})
.then(v => {
return v.load(['meta_schools']);
})
.then(v => {
resolve(this.getOne(v.id));
})
.catch(err => {
console.log(err);
reject({
"message": "Une erreur d'insertion s'est produite.",
"code": 500,
});
});
}
});
}
updateOne(id, s) {
return new Promise((resolve, reject) => {
// Checks if body exists and if the model fits, and throws errors if it doesn't
if (isEmptyObject(s)) {
reject({
"message": "Le corps de la requête ne peut pas être vide.",
"code": 403,
});
} else if (!validator.validate(s, SchoolValidation).valid) {
reject({
"message": `Le modèle d'école n'est pas respecté : ${validator.validate(s, SchoolValidation).errors}`,
"code": 403,
});
} else if (isXSSAttempt(s.name) || isXSSAttempt(s.description)) {
reject({
"message": "Tentative d'injection XSS détectée, requête refusée.",
"code": 403,
});
} else {
new model({ id: id })
.fetch({ require: true, withRelated: ['meta_schools'] })
.then(v => {
bookshelf.transaction(t => {
return v.save({
'name': s.name,
'description': s.description,
'meta_school_id': s.meta_school_id
}, {
method: 'update',
transacting: t
})
.catch(err => {
console.log(err);
throw err;
});
})
.then(v => {
return v.load(['meta_schools']);
})
.then(v => {
resolve(this.getOne(v.id));
})
.catch(err => {
console.log(err);
reject({
"message": "Une erreur d'insertion s'est produite.",
"code": 500,
});
});
})
.catch(err => {
console.log(err);
reject({
"message": "L'école en question n'a pas été trouvée.",
"code": 404,
});
});
}
});
}
deleteOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ require: true, withRelated: ['spells', 'meta_schools'] })
.then(v => {
v.spells().detach();
v.destroy();
})
.then(() => {
resolve({
'message': 'School with ID ' + id + ' successfully deleted !'
});
})
.catch(err => {
console.log(err);
reject({
"message": "L'école en question n'a pas été trouvée.",
"code": 404,
});
});
});
}
}
module.exports = SchoolRepository;

View File

@@ -0,0 +1,351 @@
'use strict'
// Bookshelf
const bookshelf = require('../database/bookshelf').bookshelf
const model = require('../models/spell-model')
// Model validation
const Validator = require('jsonschema').Validator
const validator = new Validator()
const SpellValidation = require("../validations/SpellValidation")
validator.addSchema(SpellValidation, "/SpellValidation")
// Validations
const isXSSAttempt = require('../functions').isXSSAttempt
const isEmptyObject = require('../functions').isEmptyObject
class SpellRepository {
constructor() {
}
getAll(name, description, level, charge, cost, ritual) {
return new Promise((resolve, reject) => {
let query = new model();
if (name) {
query.where('name', 'like', `%${name}%`)
}
if (description) {
query.where('description', 'like', `%${description}%`)
}
if (level) {
query.where({ 'level': level })
}
if (charge) {
query.where({ 'charge': charge })
}
if (cost) {
query.where({ 'cost': cost })
}
if (ritual) {
query.where({ 'is_ritual': ritual })
}
query.fetchAll({ withRelated: ['schools.meta_schools', 'variables', 'ingredients', 'author'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err);
reject({
"message": "Il n'existe aucun sortilège disponible.",
"code": 404,
});
})
})
}
getAllPublic(name, description, level, charge, cost, ritual) {
return new Promise((resolve, reject) => {
let query = new model().where({ 'public': 1 })
if (name) {
query.where('name', 'like', `%${name}%`)
}
if (description) {
query.where('description', 'like', `%${description}%`)
}
if (level) {
query.where({ 'level': level })
}
if (charge) {
query.where({ 'charge': charge })
}
if (cost) {
query.where({ 'cost': cost })
}
if (ritual) {
query.where({ 'is_ritual': ritual })
}
query.fetchAll({ withRelated: ['schools.meta_schools', 'variables', 'ingredients', 'author'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "Il n'existe aucun sortilège disponible.",
"code": 404,
});
})
})
}
getPage(page) {
return new Promise((resolve, reject) => {
new model()
.where({ 'public': 1 })
.fetchPage({
pageSize: 20,
page: page,
withRelated: ['schools.meta_schools', 'variables', 'ingredients', 'author'],
})
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err);
reject({
"message": "La page de sortilèges n'a pas pu être chargée",
"code": 404,
});
})
})
}
getOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ withRelated: ['schools.meta_schools', 'variables', 'ingredients', 'author'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err);
reject({
"message": "Le sortilège en question n'a pas été trouvé.",
"code": 404,
});
})
})
}
addOne(s) {
return new Promise((resolve, reject) => {
// Checks if body exists and if the model fits, and throws errors if it doesn't
if (isEmptyObject(s)) {
reject({
"message": "Le corps de la requête ne peut pas être vide.",
"code": 403,
});
} else if (!validator.validate(s, SpellValidation).valid) {
reject({
"message": `Le modèle de sortilège n'est pas respecté : ${validator.validate(s, SpellValidation).errors}`,
"code": 403,
});
} else if (isXSSAttempt(s.name) || isXSSAttempt(s.description) || isXSSAttempt(s.cost)) {
reject({
"message": "Tentative d'injection XSS détectée, requête refusée.",
"code": 403,
});
} else {
bookshelf.transaction(t => {
return new model({
'name': s.name,
'description': s.description,
'level': s.level,
'charge': s.charge,
'cost': s.cost,
'is_ritual': s.is_ritual
}).save(null, {
transacting: t
})
.tap(spell => {
return spell
.schools()
.attach(s.schools, {
transacting: t
});
})
.tap(spell => {
return spell
.variables()
.attach(s.variables, {
transacting: t
});
})
.tap(spell => {
return spell
.ingredients()
.attach(s.ingredients, {
transacting: t
});
})
.catch(err => {
console.log(err);
reject({
"message": "Un attributs du sortilège a provoqué une erreur d'insertion.",
"code": 500,
});
})
})
.then(v => {
return v.load(['schools.meta_schools', 'variables', 'ingredients', 'author'])
})
.then(v => {
resolve(this.getOne(v.id))
})
.catch(err => {
console.log(err);
reject({
"message": "Le sortilège n'a pas pu être ajouté.",
"code": 500,
});
})
}
})
}
updateOne(id, s) {
return new Promise((resolve, reject) => {
// Checks if body exists and if the model fits, and throws errors if it doesn't
if (isEmptyObject(s)) {
reject({
"message": "Le corps de la requête ne peut pas être vide.",
"code": 403,
});
} else if (!validator.validate(s, SpellValidation).valid) {
reject({
"message": `Le modèle de sortilège n'est pas respecté : ${validator.validate(s, SpellValidation).errors}`,
"code": 403,
});
} else if (isXSSAttempt(s.name) || isXSSAttempt(s.description) || isXSSAttempt(s.cost)) {
reject({
"message": "Tentative d'injection XSS détectée, requête refusée.",
"code": 403,
});
} else {
new model({ id: id })
.fetch({ require: true, withRelated: ['schools.meta_schools', 'variables', 'ingredients', 'author'] })
.then(v => {
bookshelf.transaction(t => {
return v.save({
'name': s.name,
'description': s.description,
'level': s.level,
'charge': s.charge,
'cost': s.cost,
'is_ritual': s.is_ritual
}, {
method: 'update',
transacting: t
})
// Detaches AND attaches pivot tables, dw about it
.tap(spell => {
if (s.schools) {
let schools = spell.related('school');
return spell.schools().detach(schools, { transacting: t });
}
return spell
})
.tap(spell => {
if (s.variables) {
let variables = spell.related('variable');
return spell.variables().detach(variables, { transacting: t });
}
return spell;
})
.tap(spell => {
if (s.ingredients) {
let ingredients = spell.related('ingredient');
return spell.ingredients().detach(ingredients, { transacting: t });
}
return spell;
})
.tap(spell => {
return spell
.schools()
.attach(s.schools, {
transacting: t
});
})
.tap(spell => {
return spell
.variables()
.attach(s.variables, {
transacting: t
});
})
.tap(spell => {
return spell
.ingredients()
.attach(s.ingredients, {
transacting: t
});
})
.catch(err => {
console.log(err);
reject({
"message": "Un attributs du sortilège a provoqué une erreur d'insertion.",
"code": 500,
})
})
})
.then(v => {
return v.load(['schools.meta_schools', 'variables', 'ingredients', 'author']);
})
.then(v => {
resolve(this.getOne(v.id));
})
.catch(err => {
console.log(err);
reject({
"message": "Une erreur de chargement est survenue.",
"code": 500,
});
})
})
.catch(err => {
console.log(err);
reject({
"message": "Le sortilège en question n'a pas été trouvé.",
"code": 404,
});
})
}
})
}
deleteOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ require: true, withRelated: ['schools.meta_schools', 'variables', 'ingredients', 'author'] })
.then(v => {
v.schools().detach();
v.variables().detach();
v.ingredients().detach();
v.destroy();
})
.then(() => {
resolve({
"message": `Le sortilège #${id} a été supprimé avec succès.`,
"code": 200,
});
})
.catch(err => {
console.log(err);
reject({
"message": "Le sortilège en question n'a pas été trouvé.",
"code": 404,
});
})
})
}
}
module.exports = SpellRepository

View File

@@ -0,0 +1,562 @@
'use strict'
// Bookshelf
const bookshelf = require('../database/bookshelf').bookshelf;
const model = require('../models/user-model');
const token_model = require('../models/api-token-model');
// Hashing and passwords
const bcrypt = require('bcrypt');
const { v4: uuidv4 } = require('uuid');
// Mailing methods
const mails = require('../smtp/mails');
// Model validation
const Validator = require('jsonschema').Validator;
const validator = new Validator();
const UserValidation = require("../validations/UserValidation");
validator.addSchema(UserValidation, "/UserValidation");
// Validations
const isXSSAttempt = require('../functions').isXSSAttempt;
const isEmptyObject = require('../functions').isEmptyObject;
class UserRepository {
constructor() {
}
/**
* Fetches all users in the dabatase.
*
* @returns { Promise }
* Fulfilled data: Array of user objects.
*/
getAll() {
return new Promise((resolve, reject) => {
new model()
.fetchAll({ withRelated: ['role.permissions'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err)
reject({
"message": "Erreur de base de données, les utilisateurs n'ont pas pu être récupérés.",
"code": 500,
});
})
})
}
/**
* Fetches a user object associated with the uuid.
*
* @param { string } uuid
* @param { boolean } full
* Whether the password should also be fetched. (should never be true unless you want to log the user)
*
* @returns { Promise }
* Fulfilled data: Queried user object.
*/
getOneByUUID(uuid, full) {
return new Promise((resolve, reject) => {
if (!(uuid)) {
reject({
"message": "La requête doit renseigner un uuid.",
"code": 400,
})
}
new model()
.where({ 'uuid': uuid })
.fetch({ withRelated: ['role.permissions'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true, visibility: !full }));
})
.catch(() => {
reject({
"message": "L'utilisateur avec cet UUID n'a pas été trouvé.",
"code": 404,
});
})
})
}
/**
* Fetches a user object associated with the mail address.
*
* @param { string } mail
* @param { boolean } full
* Whether the password should also be fetched. (should never be true unless you want to log the user)
*
* @returns { Promise }
* Fulfilled data: Queried user object.
*/
getOneByEmail(mail, full) {
return new Promise((resolve, reject) => {
if (!(mail)) {
reject({
"message": "La requête doit renseigner un email.",
"code": 400,
})
}
new model()
.where({ 'mail': mail })
.fetch({ withRelated: ['role'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true, visibility: !full }));
})
.catch(() => {
reject({
"message": "L'utilisateur avec cet email n'a pas été trouvé.",
"code": 404,
});
});
})
}
/**
* Fetches all spells linked to a user's uuid
*
* @param { string } uuid
*
* @returns
*/
getSpellsFromOne(uuid) {
return new Promise((resolve, reject) => {
if (!(uuid)) {
reject({
"message": "La requête doit renseigner un uuid.",
"code": 400,
})
}
new model()
.where({ 'uuid': uuid })
.fetch({ withRelated: ['role', 'spells.schools.meta_schools', 'spells.variables', 'spells.ingredients'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(() => {
reject({
"message": "Les sorts liés à cet utilisateur n'ont pas été trouvés.",
"code": 404,
});
});
})
}
/**
* Registers a user based on the model at ./models/user-model.js.
*
* @param { object} u
* User object
*
* @returns { Promise }
* Fulfilled data: Queried user object.
*/
addOne(u) {
return new Promise(async (resolve, reject) => {
// Checks if body exists and if the model fits, and throws errors if it doesn't
if (isEmptyObject(u)) {
reject({
"message": "Le corps de requête ne peut être vide.",
"code": 403,
})
} else if (!validator.validate(u, UserValidation).valid) {
reject({
"message": "Structure de la requête invalide - " + validator.validate(u, UserValidation).errors,
"code": 403,
})
} else if (isXSSAttempt(u.name) || isXSSAttempt(u.password) || isXSSAttempt(u.mail)) {
reject({
"message": "Essai d'injection détecté, avortement de la requête.",
"code": 403,
})
} else {
let hash = await bcrypt.hash(u.password, 10);
let uuid = uuidv4();
let verification_token = uuidv4();
this.checkIfEmailAvailable(u.mail)
.then(() => {
bookshelf.transaction(t => {
return new model({
'uuid': uuid,
'name': u.name,
'mail': u.mail,
'password': hash,
'verification_token': verification_token,
})
.save(null, {
transacting: t
})
.catch(err => {
console.log(err);
reject({
"message": "Un attribut de l'utilisateur a provoqué une erreur d'insertion.",
"code": 500,
});
})
})
.then(() => {
return this.getOneByUUID(uuid, false)
})
.then(newUser => {
// Send a mail to the new user's email with a link to verification url
mails.sendRegistrationMail({
user: {
name: newUser.name,
mail: newUser.mail,
token: verification_token,
}
});
// Then resolves the api call
resolve({
"message": `Compte utilisateur #${newUser.id} créé avec succès.`,
"code": 201,
"user": newUser,
});
})
.catch(err => {
console.log(err);
resolve({
"message": "Une erreur s'est produite en créant votre compte. Veuillez réessayer ultérieurement ou contactez l'administrateur.",
"code": 500,
})
})
})
.catch(err => {
reject(err)
})
}
})
}
/**
* Verifies an account based on a private UUID token
*
* @param { string } token
* A UUID v4 identification token provided at registration and on special demands
*
* @returns Redirects to login page
*/
verifyUser(token) {
return new Promise((resolve, reject) => {
new model()
.where({ 'verification_token': token })
.fetch()
.then(v => {
bookshelf.transaction(t => {
return v.save({
'verification_token': null,
'verified': 1,
}, {
method: 'update',
transacting: t
})
})
.then(() => {
resolve({
"message": "Insérez ici une future redirection vers le client.",
"code": 202,
})
})
})
.catch(() => {
reject({
"message": "Le lien de vérification ne semble pas correct.",
"code": 404,
})
})
});
}
/**
* Logs a user by comparing the dual mail/password inputs
*
* @param { string } mail
* @param { string } password
*
* @return { Promise }
* Fulfilled data: Queried user object.
*/
logUser(mail, password) {
return new Promise((resolve, reject) => {
this.getOneByEmail(mail, true)
.then(async fetchedUser => {
let match = await bcrypt.compare(password, fetchedUser.password);
// Makes sure no hash gets out
delete fetchedUser.password;
// If you found a user...
if (match) {
// If they're banned...
if (fetchedUser.banned) {
reject({
"message": `L'utilisateur #${fetchedUser.name} a été banni, la connexion est impossible.`,
"code": 403,
});
// If they're not verified...
} else if (!fetchedUser.verified) {
reject({
"message": `L'utilisateur #${fetchedUser.name} n'as pas été vérifié, le compte doit être activé avant la connexion.`,
"code": 401,
});
} else {
resolve({
"message": `L'utilisateur #${fetchedUser.name} s'est connecté.`,
"code": 200,
"user": fetchedUser,
});
}
} else {
reject({
"message": "Les informations de connexions sont erronées.",
"code": 400,
});
}
})
.catch(err => {
reject(err);
})
})
}
/**
* Generate a token for the user to use the API
* Requires mail and password for verifying the user
*
* @param { string } mail
* @param { string } password
*
* @returns { Promise }
* Fulfilled data: A unique UUID token string.
*/
genAPIToken(mail, password) {
return new Promise((resolve, reject) => {
this.logUser(mail, password)
.then(v => {
let user = v.user;
let new_token = uuidv4();
bookshelf.transaction(t => {
return new token_model({
'value': new_token,
'user_uuid': user.uuid,
})
.save(null, {
transacting: t
})
.catch(err => {
// If the account already has an API key linked...
if (err.errno === 1062) {
this.fetchAPIKey(user.uuid)
.then(old_api_key => {
reject({
"message": "Votre compte a déjà généré une clé d'API.",
"code": 409,
"API_key": old_api_key.value,
});
});
// Default errors
} else {
throw err
}
});
})
.then(api_key => {
resolve({
"message": "La clé d'API a été généré.",
"code": 201,
"API_key": api_key,
})
})
.catch(err => {
console.log(err);
reject({
"message": "La génération de jeton d'API n'a pas pu être conclue.",
"code": 500,
});
})
})
.catch(err => {
reject(err);
})
})
}
checkAPITokenPerms(token, permissions) {
return new Promise(async (resolve, reject) => {
// If the request doesn't have a token, reject it.
if (!token) {
reject({
"message": "Vous devez utiliser un jeton d'API dans l'en-tête de votre requête.",
"code": 401,
})
}
// Fetches user from token
new token_model()
.where({ 'value': token })
.fetch({ withRelated: 'user.role.permissions' })
// Catches not found errors
.catch(err => {
if (err instanceof token_model.NotFoundError) {
reject({
"message": "Ce jeton n'est affilié à aucun compte.",
"code": 404,
});
} else {
reject({
"message": "Le jeton ou l'utilisateur n'a pas pu être récupéré.",
"code": 500,
});
}
})
.then(fullToken => {
token = fullToken.toJSON({ omitPivot: true });
// If the token is associated with a banned user...
if (token.user.banned) {
reject({
"message": "Le jeton est lié à un utilisateur banni, il n'est donc plus utilisable.",
"code": 401,
});
}
// If the token is associated with a non-verified user...
if (!token.user.verified) {
reject({
"message": "Le jeton est lié à un utilisateur non-vérifié, il n'est donc pas utilisable.",
"code": 401,
});
}
let user_permissions = token.user.role.permissions;
// Convert user_perm to array
user_permissions.forEach((user_perm, i) => {
user_permissions[i] = user_perm.slug;
});
// Loops to check if the person has all the permissions required...
permissions.forEach(perm => {
// If not, reject...
if (!user_permissions.includes(perm)) {
reject({
"message": "Permissions insuffisantes.",
"code": 401
})
}
});
// If everything went well, resolve the promise.
resolve({
"message": "Credentials accepted.",
"code": 200
});
})
// Unhandled errors
.catch(() => {
reject({
"message": "Une erreur inconnue est survenue.",
"code": 500,
});
});
})
}
/**
* Check if the email that was input is available for account creation.
*
* @param {string} mail
*
* @returns { Promise }
* Fulfilled: HTTP 200 if email is available.
* Rejected: HTTP 400-409 if email is already used.
*/
checkIfEmailAvailable(mail) {
return new Promise((resolve, reject) => {
if (!(mail)) {
reject({
"message": "La requête doit renseigner un email.",
"code": 400,
})
}
if (!this.validateMail(mail)) {
reject({
"message": "La requête n'est pas un email valide.",
"code": 400,
})
}
this.getOneByEmail(mail, false)
.then(() => {
reject({
"message": "Cet email est déjà lié à un compte.",
"code": 409,
})
})
.catch(() => {
resolve({
"message": "Cet email est disponible.",
"code": 200,
})
})
})
}
/**
* Fetches the associated api_token from a user uuid.
*
* @param { string } uuid
*
* @returns { Promise }
* Fulfilled data: Queried API token object
*/
fetchAPIKey(uuid) {
return new Promise((resolve, reject) => {
new token_model()
.where({ 'user_uuid': uuid })
.fetch()
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
reject(err);
})
})
}
/**
* Whether a mail is correctly formed and ripe for receiving, ie: xxx@yyy.zzz.
*
* @param { string } mail
*
* @returns { boolean }
*/
validateMail(mail) {
const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regex.test(String(mail).toLowerCase());
}
}
module.exports = UserRepository

View File

@@ -0,0 +1,204 @@
// Bookshelf
const bookshelf = require('../database/bookshelf').bookshelf;
const model = require('../models/variable-model');
// Model validation
const Validator = require('jsonschema').Validator;
const validator = new Validator();
const VariableValidation = require("../validations/VariableValidation");
validator.addSchema(VariableValidation, "/VariableValidation");
// Validations
const isXSSAttempt = require('../functions').isXSSAttempt;
const isEmptyObject = require('../functions').isEmptyObject;
class VariableRepository {
constructor() {
}
getAll() {
return new Promise((resolve, reject) => {
new model()
.fetchAll({ withRelated: ['spells'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "Il n'existe aucune variable disponible.",
"code": 404,
});
});
});
}
getOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ withRelated: ['spells'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "La variable en question n'a pas pu être trouvée.",
"code": 404,
});
});
});
}
getSpellsFromOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ withRelated: ['spells', 'spells.schools', 'spells.variables', 'spells.ingredients', 'spells.schools.meta_schools'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }));
})
.catch(err => {
console.log(err);
reject({
"message": "Les sortilèges liés à cette variable n'ont pas pu être récupérés.",
"code": 404,
});
});
});
}
addOne(vr) {
return new Promise((resolve, reject) => {
// Checks if body exists and if the model fits, and throws errors if it doesn't
if (isEmptyObject(vr)) {
reject({
"message": "Le corps de la requête ne peut pas être vide.",
"code": 403,
});
} else if (!validator.validate(vr, VariableValidation).valid) {
reject({
"message": `Le modèle de variable n'est pas respecté : ${validator.validate(s, VariableValidation).errors}`,
"code": 403,
});
} else if (isXSSAttempt(vr.description)) {
reject({
"message": "Tentative d'injection XSS détectée, requête refusée.",
"code": 403,
});
} else {
bookshelf.transaction(t => {
return new model({
'description': vr.description,
}).save(null, {
transacting: t
})
.catch(err => {
throw err;
});
})
.then(v => {
return v.load(['spells']);
})
.then(v => {
resolve(this.getOne(v.id));
})
.catch(err => {
console.log(err);
reject({
"message": "Une erreur d'insertion s'est produite.",
"code": 500,
});
});
}
});
}
updateOne(id, vr) {
return new Promise((resolve, reject) => {
// Checks if body exists and if the model fits, and throws errors if it doesn't
if (isEmptyObject(vr)) {
reject({
"message": "Le corps de la requête ne peut pas être vide.",
"code": 403,
});
} else if (!validator.validate(vr, VariableValidation).valid) {
reject({
"message": `Le modèle de variable n'est pas respecté : ${validator.validate(s, VariableValidation).errors}`,
"code": 403,
});
} else if (isXSSAttempt(vr.description)) {
reject({
"message": "Tentative d'injection XSS détectée, requête refusée.",
"code": 403,
});
} else {
new model({ id: id })
.fetch({ require: true, withRelated: ['spells'] })
.then(v => {
bookshelf.transaction(t => {
return v.save({
'description': vr.description,
}, {
method: 'update',
transacting: t
})
.catch(err => {
console.log(err);
throw err;
});
})
.then(v => {
return v.load(['spells']);
})
.then(v => {
resolve(this.getOne(v.id));
})
.catch(err => {
console.log(err);
reject({
"message": "Une erreur d'insertion s'est produite.",
"code": 500,
});
});
})
.catch(err => {
console.log(err);
reject({
"message": "La variable en question n'a pas été trouvée.",
"code": 404,
});
});
}
});
}
deleteOne(id) {
return new Promise((resolve, reject) => {
new model()
.where({ 'id': id })
.fetch({ require: true, withRelated: ['spells'] })
.then(v => {
v.spells().detach();
v.destroy();
})
.then(() => {
resolve({
'message': 'Variable with ID ' + id + ' successfully deleted !'
});
})
.catch(err => {
console.log(err);
reject({
"message": "La variable en question n'a pas été trouvée.",
"code": 404,
});
});
});
}
}
module.exports = VariableRepository;