Initial commit
This commit is contained in:
10
api/hooks/config-client.js
Normal file
10
api/hooks/config-client.js
Normal file
@@ -0,0 +1,10 @@
|
||||
const release = "tibi-docs.dirty"
|
||||
|
||||
// @ts-ignore
|
||||
if (release && typeof context !== "undefined") {
|
||||
context.response.header("X-Release", release)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
release,
|
||||
}
|
||||
27
api/hooks/config.js
Normal file
27
api/hooks/config.js
Normal file
@@ -0,0 +1,27 @@
|
||||
module.exports = {
|
||||
ssrValidatePath: function (path) {
|
||||
// validate if path ssr rendering is ok, -1 = NOTFOUND, 0 = NO SSR, 1 = SSR
|
||||
// pe. use context.readCollection("product", {filter: {path: path}}) ... to validate dynamic urls
|
||||
|
||||
// / is de home
|
||||
if (path == "/") return 1
|
||||
|
||||
// all other sites are in db
|
||||
path = path?.replace(/^\//, "")
|
||||
|
||||
// filter for path or alternativePaths
|
||||
const resp = context.db.find("content", {
|
||||
filter: {
|
||||
$or: [{ path }, { "alternativePaths.path": path }],
|
||||
},
|
||||
selector: { _id: 1 },
|
||||
})
|
||||
if (resp && resp.length) {
|
||||
return 1
|
||||
}
|
||||
|
||||
// not found
|
||||
return -1
|
||||
},
|
||||
ssrAllowedAPIEndpoints: ["content", "medialib"],
|
||||
}
|
||||
14
api/hooks/forms/post_create.js
Normal file
14
api/hooks/forms/post_create.js
Normal file
@@ -0,0 +1,14 @@
|
||||
const { validateFields } = require("./validateFields")
|
||||
;(function () {
|
||||
if (context.data.formular.honey) {
|
||||
throw { status: 400, error: "Bot detection" }
|
||||
}
|
||||
delete context.data.formular.honey
|
||||
let values = Object.entries(context.data.formular)
|
||||
|
||||
let validation = validateFields(values)
|
||||
console.log(validation)
|
||||
if (validation.length) {
|
||||
throw { status: 400, error: validation }
|
||||
}
|
||||
})()
|
||||
60
api/hooks/forms/post_return.js
Normal file
60
api/hooks/forms/post_return.js
Normal file
@@ -0,0 +1,60 @@
|
||||
var utils = require("../lib/utils")
|
||||
var config = require("../config")
|
||||
|
||||
;(function () {
|
||||
let formular = context.data.formular
|
||||
let tempForm = {}
|
||||
let formTitle = `${formular.formTitle}`
|
||||
delete formular.formTitle
|
||||
delete formular["agreement"]
|
||||
delete formular["honey"]
|
||||
formular.formRows.forEach((rowName, i) => {
|
||||
tempForm[rowName] = {}
|
||||
})
|
||||
let getValue = (e) => {
|
||||
if (e[0].includes("numberLabel")) return e[1][0]
|
||||
return e[1]
|
||||
}
|
||||
|
||||
let indices = {}
|
||||
|
||||
Object.entries(formular).forEach((e) => {
|
||||
if (e[0] == "formRows") return
|
||||
let key = e[0].split("_")
|
||||
let newKey = key[key.length - 1]
|
||||
let rowName = formular.formRows[Number(key[key.length - 2])]
|
||||
let index = isNaN(Number(key[key.length - 3])) ? 100 : Number(key[key.length - 3])
|
||||
if (!rowName) return
|
||||
if (!tempForm[rowName]) tempForm[rowName] = {}
|
||||
if (tempForm[rowName][newKey]) {
|
||||
tempForm[rowName][newKey][0] += "\\" + getValue(e)
|
||||
} else {
|
||||
tempForm[rowName][newKey] = [getValue(e), newKey[0] == "n", newKey.includes("invalid")]
|
||||
indices[rowName] = { ...indices[rowName], [newKey]: index }
|
||||
}
|
||||
})
|
||||
|
||||
// Now iterate over tempForm to sort fields in each row
|
||||
Object.entries(tempForm).forEach(([rowName, fields]) => {
|
||||
tempForm[rowName] = Object.entries(fields)
|
||||
.sort((a, b) => indices[rowName][a[0]] - indices[rowName][b[0]])
|
||||
.reduce((acc, [key, val]) => ({ ...acc, [key]: val }), {})
|
||||
})
|
||||
console.log(JSON.stringify(tempForm), JSON.stringify(indices))
|
||||
|
||||
Object.keys(tempForm).forEach((row) => {
|
||||
tempForm[row] = Object.entries(tempForm[row])
|
||||
})
|
||||
|
||||
delete tempForm[undefined]
|
||||
context.smtp.sendMail({
|
||||
to: "info@wasserski-erfurt.de",
|
||||
from: "mail@webmakers.de",
|
||||
subject: "Wasserski " + formTitle,
|
||||
html: context.tpl.execute(context.fs.readFile("templates/form_mail.html"), {
|
||||
context: context,
|
||||
formularRows: Object.entries(tempForm),
|
||||
formTitle: formTitle,
|
||||
}),
|
||||
})
|
||||
})()
|
||||
67
api/hooks/forms/validateFields.js
Normal file
67
api/hooks/forms/validateFields.js
Normal file
@@ -0,0 +1,67 @@
|
||||
function validateFields(fieldsArray) {
|
||||
const errors = []
|
||||
let selectedGroup
|
||||
|
||||
const numberRegex = /^[+]?([.]\d+|\d+([.]\d+)?)$/
|
||||
const emailRegex =
|
||||
/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/
|
||||
const dateRegex = /^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$/
|
||||
const timeRegex = /^\d{1,2}:\d{2}-\d{1,2}:\d{2}$/
|
||||
const phoneRegex = /^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$/
|
||||
|
||||
const wholeBlockInvalid = () => {
|
||||
const blockContainer = document.getElementsByClassName("blockContainer")[0]
|
||||
blockContainer.classList.add("invalidBlocks")
|
||||
}
|
||||
|
||||
const validateNumber = (value, field, element) => {
|
||||
if (!numberRegex.test(`${value}`)) {
|
||||
errors.push(["block", () => element.classList.add("border-red")])
|
||||
}
|
||||
}
|
||||
|
||||
fieldsArray.forEach(([field, value]) => {
|
||||
if (field === "blockGroups" || field.includes("numberLabel")) {
|
||||
if (!field.includes("numberLabel")) return
|
||||
const [elementValue, element, group] = value
|
||||
|
||||
if (!elementValue) return
|
||||
|
||||
if (selectedGroup !== undefined) {
|
||||
if (group !== selectedGroup) {
|
||||
errors.push(["block", wholeBlockInvalid])
|
||||
} else {
|
||||
validateNumber(elementValue, field, element)
|
||||
}
|
||||
} else {
|
||||
selectedGroup = group
|
||||
validateNumber(elementValue, field, element)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
errors.push(["Eingabe ist erforderlich.", field])
|
||||
} else if (field.includes("number_")) {
|
||||
if (!numberRegex.test(`${value}`)) {
|
||||
errors.push(["Ungültiger numerischer Wert.", field])
|
||||
}
|
||||
} else if (field.includes("agreement_")) {
|
||||
if (value !== true) errors.push(["Bitte das Kontrollkästchen anklicken.", field])
|
||||
} else if (field.includes("Email_")) {
|
||||
if (!emailRegex.test(value)) errors.push(["Ungültiges E-Mail-Format.", field])
|
||||
} else if (field.includes("date_")) {
|
||||
if (!dateRegex.test(value)) errors.push(["Ungültiges Datumsformat.", field])
|
||||
} else if (field.includes("times_")) {
|
||||
if (!timeRegex.test(value)) errors.push(["Ungültiges Zeitformat.", field])
|
||||
} else if (field.includes("Telefon_")) {
|
||||
if (!phoneRegex.test(value)) errors.push(["Ungültiges Telefonnummernformat.", field])
|
||||
}
|
||||
})
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
validateFields,
|
||||
}
|
||||
55
api/hooks/lib/utils.js
Normal file
55
api/hooks/lib/utils.js
Normal file
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
*
|
||||
* @param {any} str
|
||||
*/
|
||||
function log(str) {
|
||||
console.log(JSON.stringify(str, undefined, 4))
|
||||
}
|
||||
|
||||
/**
|
||||
* convert object to string
|
||||
* @param {any} obj object
|
||||
*/
|
||||
function obj2str(obj) {
|
||||
if (Array.isArray(obj)) {
|
||||
return JSON.stringify(
|
||||
obj.map(function (idx) {
|
||||
return obj2str(idx)
|
||||
})
|
||||
)
|
||||
} else if (typeof obj === "object" && obj !== null) {
|
||||
var elements = Object.keys(obj)
|
||||
.sort()
|
||||
.map(function (key) {
|
||||
var val = obj2str(obj[key])
|
||||
if (val) {
|
||||
return key + ":" + val
|
||||
}
|
||||
})
|
||||
|
||||
var elementsCleaned = []
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
if (elements[i]) elementsCleaned.push(elements[i])
|
||||
}
|
||||
|
||||
return "{" + elementsCleaned.join("|") + "}"
|
||||
}
|
||||
|
||||
if (obj) return obj
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* clear SSR cache
|
||||
*/
|
||||
function clearSSRCache() {
|
||||
var info = context.db.deleteMany("ssr", {})
|
||||
context.response.header("X-SSR-Cleared", info.removed)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
log,
|
||||
clearSSRCache,
|
||||
obj2str,
|
||||
}
|
||||
183
api/hooks/ssr/get_read.js
Normal file
183
api/hooks/ssr/get_read.js
Normal file
@@ -0,0 +1,183 @@
|
||||
const { ssrValidatePath, ssrAllowedAPIEndpoints } = require("../config")
|
||||
|
||||
const { obj2str, log } = require("../lib/utils")
|
||||
;(function () {
|
||||
/** @type {HookResponse} */
|
||||
var response = null
|
||||
|
||||
var request = context.request()
|
||||
var url = request.query("url")
|
||||
var noCache = request.query("noCache")
|
||||
|
||||
// add sentry trace id to head
|
||||
var trace_id = context.debug.sentryTraceId()
|
||||
function addSentryTrace(content) {
|
||||
return content.replace("</head>", '<meta name="sentry-trace" content="' + trace_id + '" /></head>')
|
||||
}
|
||||
context.response.header("sentry-trace", trace_id)
|
||||
|
||||
if (url) {
|
||||
// comment will be printed to html later
|
||||
var comment = ""
|
||||
|
||||
url = url.split("?")[0]
|
||||
comment += "url: " + url
|
||||
|
||||
if (url && url.length > 1) {
|
||||
url = url.replace(/\/$/, "")
|
||||
}
|
||||
if (url == "/noindex" || !url) {
|
||||
url = "/" // see .htaccess
|
||||
}
|
||||
|
||||
// check if url is in cache
|
||||
var cache =
|
||||
!noCache &&
|
||||
context.db.find("ssr", {
|
||||
filter: {
|
||||
path: url,
|
||||
},
|
||||
})
|
||||
if (cache && cache.length) {
|
||||
// use cache
|
||||
throw {
|
||||
status: 200,
|
||||
log: false,
|
||||
html: addSentryTrace(cache[0].content),
|
||||
}
|
||||
}
|
||||
|
||||
// validate url
|
||||
var status = 200
|
||||
|
||||
var pNorender = false
|
||||
var pNotfound = false
|
||||
|
||||
var pR = ssrValidatePath(url)
|
||||
if (pR < 0) {
|
||||
pNotfound = true
|
||||
} else if (!pR) {
|
||||
pNorender = true
|
||||
}
|
||||
|
||||
var head = ""
|
||||
var html = ""
|
||||
var error = ""
|
||||
|
||||
comment += ", path: " + url
|
||||
|
||||
var cacheIt = false
|
||||
if (pNorender) {
|
||||
html = "<!-- NO SSR RENDERING -->"
|
||||
} else if (pNotfound) {
|
||||
status = 404
|
||||
html = "404 NOT FOUND"
|
||||
} else {
|
||||
// try rendering, if error output plain html
|
||||
try {
|
||||
// @ts-ignore
|
||||
context.ssrCache = {}
|
||||
// @ts-ignore
|
||||
context.ssrFetch = function (endpoint, options) {
|
||||
var data
|
||||
if (ssrAllowedAPIEndpoints.indexOf(endpoint) > -1) {
|
||||
var _options = Object.assign({}, options)
|
||||
|
||||
if (_options.sort) _options.sort = [_options.sort]
|
||||
|
||||
try {
|
||||
/*console.log(
|
||||
"SSR",
|
||||
endpoint,
|
||||
JSON.stringify(_options)
|
||||
)*/
|
||||
var goSlice = context.db.find(endpoint, _options || {})
|
||||
// need to deep copy, so shift and delete on pure js is possible
|
||||
data = JSON.parse(JSON.stringify(goSlice))
|
||||
} catch (e) {
|
||||
console.log("ERROR", JSON.stringify(e))
|
||||
data = []
|
||||
}
|
||||
} else {
|
||||
console.log("SSR forbidden", endpoint)
|
||||
data = []
|
||||
}
|
||||
|
||||
var count = (data && data.length) || 0
|
||||
if (options && count == options.limit) {
|
||||
// read count from db
|
||||
count = context.db.count(endpoint, _options || {})
|
||||
}
|
||||
var r = { data: data, count: count }
|
||||
|
||||
// @ts-ignore
|
||||
context.ssrCache[obj2str({ endpoint: endpoint, options: options })] = r
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// include App.svelte and render it
|
||||
// @ts-ignore
|
||||
var app = require("../lib/app.server")
|
||||
var rendered = app.default.render({
|
||||
url: url,
|
||||
})
|
||||
head = rendered.head
|
||||
html = rendered.html
|
||||
|
||||
// add ssrCache to head
|
||||
head +=
|
||||
"\n\n" +
|
||||
"<script>window.__SSR_CACHE__ = " +
|
||||
// @ts-ignore
|
||||
JSON.stringify(context.ssrCache) +
|
||||
"</script>"
|
||||
|
||||
// status from webapp
|
||||
// @ts-ignore
|
||||
if (context.is404) {
|
||||
status = 404
|
||||
} else {
|
||||
cacheIt = true
|
||||
}
|
||||
} catch (e) {
|
||||
// save error for later insert into html
|
||||
log(e.message)
|
||||
log(e.stack)
|
||||
error = "error: " + e.message + "\n\n" + e.stack
|
||||
}
|
||||
}
|
||||
|
||||
// read html template and replace placeholders
|
||||
var tpl = context.fs.readFile("templates/spa.html")
|
||||
tpl = tpl.replace("<!--HEAD-->", head)
|
||||
tpl = tpl.replace("<!--HTML-->", html)
|
||||
tpl = tpl.replace("<!--SSR.ERROR-->", error ? "<!--" + error + "-->" : "")
|
||||
tpl = tpl.replace("<!--SSR.COMMENT-->", comment ? "<!--" + comment + "-->" : "")
|
||||
|
||||
// save cache if adviced
|
||||
if (cacheIt && !noCache) {
|
||||
context.db.create("ssr", {
|
||||
path: url,
|
||||
content: tpl,
|
||||
})
|
||||
}
|
||||
|
||||
// return html
|
||||
throw {
|
||||
status: status,
|
||||
log: false,
|
||||
html: addSentryTrace(tpl),
|
||||
}
|
||||
} else {
|
||||
// only admins are allowed to get without url parameter
|
||||
var auth = context.user.auth()
|
||||
if (!auth || auth.role !== 0) {
|
||||
throw {
|
||||
status: 403,
|
||||
message: "invalid auth",
|
||||
auth: auth,
|
||||
}
|
||||
}
|
||||
}
|
||||
})()
|
||||
16
api/hooks/ssr/post_bind.js
Normal file
16
api/hooks/ssr/post_bind.js
Normal file
@@ -0,0 +1,16 @@
|
||||
const utils = require("../lib/utils")
|
||||
|
||||
;(function () {
|
||||
if (context.request().query("clear")) {
|
||||
utils.clearSSRCache()
|
||||
throw {
|
||||
status: 200,
|
||||
message: "cache cleared",
|
||||
}
|
||||
}
|
||||
|
||||
throw {
|
||||
status: 500,
|
||||
message: "ssr is only a dummy collection",
|
||||
}
|
||||
})()
|
||||
Reference in New Issue
Block a user