2020-05-04 15:06:07 +00:00
|
|
|
const constants = require("../../lib/constants")
|
|
|
|
const {render, redirect} = require("pinski/plugins")
|
2020-05-05 13:45:56 +00:00
|
|
|
const {getSettings} = require("./utils/getsettings")
|
2020-05-04 15:06:07 +00:00
|
|
|
const crypto = require("crypto")
|
|
|
|
const db = require("../../lib/db")
|
|
|
|
|
|
|
|
module.exports = [
|
|
|
|
{
|
2020-05-05 13:45:56 +00:00
|
|
|
route: "/settings", methods: ["GET"], code: async ({req, url}) => {
|
|
|
|
const settings = getSettings(req)
|
|
|
|
// console.log(settings)
|
2020-05-04 15:06:07 +00:00
|
|
|
const saved = url.searchParams.has("saved")
|
2020-05-05 13:45:56 +00:00
|
|
|
return render(200, "pug/settings.pug", {saved, settings})
|
2020-05-04 15:06:07 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
{
|
|
|
|
route: "/settings", methods: ["POST"], upload: true, code: async ({body}) => {
|
|
|
|
const params = new URLSearchParams(body.toString())
|
|
|
|
const prepared = {}
|
|
|
|
for (const setting of constants.user_settings) {
|
|
|
|
let valueOrDefault
|
|
|
|
if (params.has(setting.name) && params.get(setting.name) !== "") {
|
|
|
|
valueOrDefault = params.get(setting.name)
|
|
|
|
} else if (setting.replaceEmptyWithDefault) {
|
|
|
|
valueOrDefault = setting.default
|
|
|
|
} else {
|
|
|
|
valueOrDefault = ""
|
|
|
|
}
|
|
|
|
let valueCorrectType
|
|
|
|
if (setting.boolean) {
|
|
|
|
valueCorrectType = +(valueOrDefault !== "")
|
|
|
|
} else {
|
|
|
|
valueCorrectType = valueOrDefault
|
|
|
|
}
|
|
|
|
prepared[setting.name] = valueCorrectType
|
|
|
|
}
|
2020-05-05 13:45:56 +00:00
|
|
|
// console.log(prepared)
|
2020-05-04 15:06:07 +00:00
|
|
|
const checkPrepared = db.prepare("SELECT token FROM UserSettings WHERE token = ?")
|
|
|
|
do {
|
|
|
|
prepared.token = crypto.randomBytes(16).toString("hex")
|
|
|
|
} while (checkPrepared.get(prepared.token))
|
|
|
|
prepared.created = Date.now()
|
|
|
|
db.prepare(
|
|
|
|
"INSERT INTO UserSettings (token, created, language, show_comments, link_hashtags, spa, theme, caption_side, display_alt)"
|
|
|
|
+" VALUES (@token, @created, @language, @show_comments, @link_hashtags, @spa, @theme, @caption_side, @display_alt)"
|
|
|
|
).run(prepared)
|
|
|
|
const expires = new Date(Date.now() + 4000*24*60*60*1000).toUTCString()
|
|
|
|
return {
|
|
|
|
statusCode: 303,
|
|
|
|
headers: {
|
|
|
|
"Location": "/settings?saved=1",
|
|
|
|
"Set-Cookie": `settings=${prepared.token}; Path=/; Expires=${expires}; SameSite=Strict`
|
|
|
|
},
|
|
|
|
contentType: "text/html",
|
|
|
|
content: "Redirecting..."
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
]
|