-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.js
More file actions
84 lines (77 loc) · 2.65 KB
/
validation.js
File metadata and controls
84 lines (77 loc) · 2.65 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"use strict";
var _ = require("lodash");
const isomorphicDomPurify = require("isomorphic-dompurify");
const helper = require('./lib/helper');
var debug = require("debug")("loopback:component-validator:validation");
var beforeSaveValidators = [];
var customValidators = [];
module.exports = (app, options) => {
let customValidation = ["StringValidation", "NumberValidation", "domPurify"];
if (options.disableAll === true) {
return;
}
_.forEach(customValidation, prop => {
if (typeof this[prop] === "function") {
if (options[prop] != false) this[prop](app, options);
} else {
throw new Error(`Function defination for '${prop}' not given`);
}
});
debug(options);
attachBeforeSave(app);
};
this.StringValidation = app => {
var stringValidator = require("./lib/stringValidation").setup(app);
var deb = debug.extend("stringModels");
deb(stringValidator);
customValidators.push(stringValidator);
};
this.NumberValidation = app => {
var numberValidator = require("./lib/numberValidation").setup(app);
var deb = debug.extend("numberModels");
deb(numberValidator);
customValidators.push(numberValidator);
};
this.domPurify = (app, options) => {
let stringModels = helper.populateModels(app, { key: "type", value: "string" });
for (const model in stringModels) {
app.models[model].observe("before save", async ctx => {
const instance = ctx.instance || ctx.data;
const purifyOpts = options.domPurify || {};
for (const property in instance) {
if(purifyOpts.skipProperties?.[model]?.includes?.(property)) continue;
if (instance[property] && typeof instance[property] === 'string') {
try {
instance[property] = isomorphicDomPurify.sanitize(instance[property], {
...(purifyOpts.isomorphicDomPurifyOptions || {})
});
} catch (error) {
console.error(error);
}
}
else if (Array.isArray(instance[property])) {
instance[property] = instance[property].map(item => {
if (typeof item === 'string') {
return isomorphicDomPurify.sanitize(item, {
...(options.domPurify?.isomorphicDomPurifyOptions || {})
});
}
return item;
}
);
}
}
})
}
}
function attachBeforeSave(app) {
_.keys(app.models).forEach(model => {
app.models[model].observe("before save", async ctx => {
for (let validator of customValidators) {
let Model = app.models[model]
if (validator[model] && typeof validator[model].validate === 'function')
validator[model].validate(ctx, Model);
}
});
});
}