Skip to content

Commit

Permalink
getLocale; role checks; remove clone; logout msg; xhr resolution;
Browse files Browse the repository at this point in the history
  • Loading branch information
dbauszus-glx committed Nov 2, 2023
1 parent 11e3951 commit d894f18
Show file tree
Hide file tree
Showing 15 changed files with 242 additions and 258 deletions.
2 changes: 1 addition & 1 deletion api/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ module.exports = async (req, res) => {
res.setHeader('Set-Cookie', `${process.env.TITLE}=null;HttpOnly;Max-Age=0;Path=${process.env.DIR || '/'}`)

// Remove logout parameter.
res.setHeader('location', `${process.env.DIR || '/'}`)
res.setHeader('location', (process.env.DIR || '/') + (req.params.msg && `?msg=${req.params.msg}`||''))

return res.status(302).send()
}
Expand Down
39 changes: 23 additions & 16 deletions lib/utils/xhr.mjs
Original file line number Diff line number Diff line change
@@ -1,51 +1,58 @@
const requestMap = new Map()

export default params => new Promise((resolve, reject) => {
export default params => new Promise(resolve => {

if (!params) return reject()
// Return if params are falsy.
if (!params) {
console.error(`xhr params are falsy.`)
return;
}

// Set params as object with url from string.
params = typeof params === 'string' ? { url: params } : params

// A request url must be provided.
if (!params.url) {
console.error(`no xhr request url has been provided.`)
return;
};

// Check whether a request with the same params has already been resolved.
if (params.cache && requestMap.has(params)) return resolve(requestMap.get(params))

// Assign 'GET' as default method.
params.method ??= 'GET'

const xhr = new XMLHttpRequest()

xhr.open(params.method || 'GET', params.url)
xhr.open(params.method, params.url)

// Use requestHeader: null to prevent assignment of requestHeader.
if (params.requestHeader !== null) {

// Butter (spread) over requestHeader.
const requestHeader = {
'Content-Type': 'application/json'
'Content-Type': 'application/json',
...params.requestHeader
}

Object.assign(requestHeader, params.requestHeader || {})

Object.entries(requestHeader).forEach(entry=>xhr.setRequestHeader(...entry))

Object.entries(requestHeader).forEach(entry => xhr.setRequestHeader(...entry))
}

xhr.responseType = params.responseType || 'json'

xhr.onload = e => {

if (e.target.status >= 400) {
reject(new Error(e.target.status))
resolve(new Error(e.target.status))
return;
}

// Cache the response in the requestMap
params.cache && requestMap.set(params, e.target.response)

resolve(params.resolveTarget ? e.target : e.target.response)

}

// xhr.onerror = err => {
// console.error(err)
// reject(err);
// };

xhr.send(params.body)

})
33 changes: 13 additions & 20 deletions mod/location/_location.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,27 @@ const methods = {
delete: require('./delete'),
}

const workspaceCache = require('../workspace/cache')
const Roles = require('../utils/roles')

module.exports = async (req, res) => {
const getLayer = require('../workspace/getLayer')

const workspace = await workspaceCache()
module.exports = async (req, res) => {

if (!Object.hasOwn(methods, req.params.method)) {
return res.send(`Failed to evaluate 'method' param.<br><br>
<a href="https://geolytix.github.io/xyz/docs/develop/api/location/">Location API</a>`)
return res.send(`Failed to evaluate 'method' param.`)
}

const method = methods[req.params.method]

if (typeof method !== 'function') return;

const locale = req.params.locale && workspace.locales[req.params.locale]

const layer = locale?.layers[req.params.layer] || workspace.templates[req.params.layer]
const layer = await getLayer(req.params)

if (!layer) return res.status(400).send('Layer not found.')

req.params.layer = layer
if (layer instanceof Error) {
return res.status(400).send('Failed to access layer.')
}

if (!req.params.layer) {
return res.status(400).send(`Failed to evaluate 'layer' param.<br><br>
<a href="https://geolytix.github.io/xyz/docs/develop/api/location/">Location API</a>`)
if (!Roles.check(layer, req.params.user?.roles)) {
return res.status(403).send('Role access denied for layer.')
}

return method(req, res)

req.params.layer = layer

return methods[req.params.method](req, res)
}
4 changes: 2 additions & 2 deletions mod/location/get.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const dbs = require('../utils/dbs')()

const sqlFilter = require('../utils/sqlFilter.js')
const sqlFilter = require('../utils/sqlFilter')

const Roles = require('../utils/roles.js')
const Roles = require('../utils/roles')

const workspaceCache = require('../workspace/cache')

Expand Down
2 changes: 1 addition & 1 deletion mod/mvt.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const sqlFilter = require('./utils/sqlFilter')

const validateRequestParams = require('./utils/validateRequestParams')

const Roles = require('./utils/roles.js')
const Roles = require('./utils/roles')

const logger = require('./utils/logger')

Expand Down
15 changes: 4 additions & 11 deletions mod/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const dbs_connections = require('./utils/dbs')()

const sqlFilter = require('./utils/sqlFilter')

const Roles = require('./utils/roles.js')
const Roles = require('./utils/roles')

const logger = require('./utils/logger');

Expand Down Expand Up @@ -50,19 +50,12 @@ module.exports = async (req, res) => {
// Assign role filter and viewport params from layer object.
if (req.params.layer) {

// Get locale for layer.
const locale = workspace.locales[req.params.locale]

// A layer must be found if the layer param is set.
if (!locale) return res.status(400).send('Locale not found.')

if (!Object.hasOwn(locale.layers, req.params.layer)) {
const layer = await getLayer(req.params)

return res.status(400).send('Layer not found.')
if (layer instanceof Error) {
return res.status(400).send('Failed to access layer.')
}

const layer = await getLayer(req.params)

if (!Roles.check(layer, req.params.user?.roles)) {
return res.status(403).send('Role access denied for layer.')
}
Expand Down
3 changes: 1 addition & 2 deletions mod/user/_user.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ module.exports = (req, res) => {
const method = methods[req.params.method]

if (!method) {
return res.send(`Failed to evaluate 'method' param.<br><br>
<a href="https://geolytix.github.io/xyz/docs/develop/api/user/">User API</a>`)
return res.send(`Failed to evaluate 'method' param.`)
}

if (!req.params.user && (method.login || method.admin)) {
Expand Down
24 changes: 0 additions & 24 deletions mod/utils/clone.js

This file was deleted.

27 changes: 0 additions & 27 deletions mod/view.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
const Roles = require('./utils/roles.js')

const login = require('./user/login')

const logger = require('./utils/logger')

const languageTemplates = require('./utils/languageTemplates')

const workspaceCache = require('./workspace/cache')

module.exports = async (req, res) => {

const workspace = await workspaceCache()

logger(req.url, 'view-req-url')

const params = {}
Expand All @@ -37,21 +29,6 @@ module.exports = async (req, res) => {

params.language ??= req.params.user.language

const roles = req.params.user?.roles || []

const locales = Object.values(workspace.locales)
.filter(locale => !!Roles.check(locale, roles))
.map(locale => ({
key: locale.key,
name: locale.name
}))

if (!locales.length) {

req.params.msg = 'no_locales'
return login(req, res)
}

// Encode stringified user for template.
params.user ??= encodeURI(JSON.stringify({
email: req.params.user.email,
Expand All @@ -61,10 +38,6 @@ module.exports = async (req, res) => {
}));
}

// Object.entries(process.env)
// .filter(entry => entry[0].match(/^SRC_/))
// .forEach(entry => params[entry[0].replace(/^SRC_/, '')]=entry[1])

const template = await languageTemplates(params)

const view = template.replace(/{{2}([A-Za-z][A-Za-z0-9]*)}{2}/g, matched => {
Expand Down
26 changes: 18 additions & 8 deletions mod/workspace/_workspace.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const clone = require('../utils/clone.js')
const Roles = require('../utils/roles')

const Roles = require('../utils/roles.js')
const workspaceCache = require('./cache')

const getLayer = require('./getLayer')
const getLocale = require('./getLocale')

const workspaceCache = require('./cache')
const getLayer = require('./getLayer')

let workspace;

Expand Down Expand Up @@ -69,21 +69,25 @@ function locales(req, res) {
res.send(locales)
}

function locale(req, res) {
async function locale(req, res) {

if (req.params.locale && !Object.hasOwn(workspace.locales, req.params.locale)) {
return res.status(400).send(`Unable to validate locale param.`)
}

let locale = {};
let locale;

if (Object.hasOwn(workspace.locales, req.params.locale)) {

locale = clone(workspace.locales?.[req.params.locale])
locale = await getLocale(req.params)

} else if (typeof workspace.locale === 'object') {

locale = clone(workspace.locale)
locale = workspace.locale
}

if (locale instanceof Error) {
return res.status(400).send('Failed to access locale.')
}

const roles = req.params.user?.roles || []
Expand All @@ -92,6 +96,12 @@ function locale(req, res) {
return res.status(403).send('Role access denied.')
}

// Subtitutes ${*} in locale with process.env.SRC_* values.
locale = JSON.parse(
JSON.stringify(locale).replace(/\$\{(.*?)\}/g,
matched => process.env[`SRC_${matched.replace(/\$|\{|\}/g, '')}`] || matched)
)

// Check layer access.
locale.layers = locale.layers && Object.entries(locale.layers)
.filter(layer => !!Roles.check(layer[1], roles))
Expand Down
23 changes: 3 additions & 20 deletions mod/workspace/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,38 +82,21 @@ async function cacheWorkspace() {
// Get locale object from key.
const locale = workspace.locales[locale_key]

// A default locale has been defined in the workspace.
if (typeof workspace.locale === 'object') {

// Merge the workspace template into workspace.
merge(locale, workspace.locale)
}

// A template exists for the locale key.
if (Object.hasOwn(workspace.templates, locale_key) && typeof workspace.templates[locale_key] === 'object') {

// Merge the workspace template into workspace.
merge(locale, workspace.templates[locale_key])
}
// Merge the workspace template into workspace.
merge(locale, workspace.locale)

// Assign key value as key on locale object.
locale.key = locale_key

// Assign locale key as name with no existing name on locale object.
locale.name = locale.name || locale_key
locale.name ??= locale_key
})

if (workspace.plugins) {

console.warn(`Default plugins should be defined in the default workspace.locale{}`)
}

// Substitute all SRC_* variables in locales.
workspace.locales = JSON.parse(
JSON.stringify(workspace.locales).replace(/\$\{(.*?)\}/g,
matched => process.env[`SRC_${matched.replace(/\$|\{|\}/g, '')}`] || matched)
)

timestamp = Date.now()

cache = workspace
Expand Down
Loading

0 comments on commit d894f18

Please sign in to comment.