mirror of
https://git.sr.ht/~cadence/bibliogram
synced 2025-12-16 03:08:47 +00:00
Settings can now save
This commit is contained in:
55
src/site/api/settings.js
Normal file
55
src/site/api/settings.js
Normal file
@@ -0,0 +1,55 @@
|
||||
const constants = require("../../lib/constants")
|
||||
const {render, redirect} = require("pinski/plugins")
|
||||
const crypto = require("crypto")
|
||||
const db = require("../../lib/db")
|
||||
|
||||
module.exports = [
|
||||
{
|
||||
route: "/settings", methods: ["GET"], code: async ({url}) => {
|
||||
const saved = url.searchParams.has("saved")
|
||||
return render(200, "pug/settings.pug", {saved})
|
||||
}
|
||||
},
|
||||
{
|
||||
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
|
||||
}
|
||||
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..."
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
Reference in New Issue
Block a user