further simplification of server code

This commit is contained in:
Martin McKeaveney 2020-05-07 14:04:32 +01:00
parent 87ad6647df
commit a28322f538
7 changed files with 82 additions and 154 deletions

View File

@ -30,34 +30,9 @@
let selectedCategory = categories[0] let selectedCategory = categories[0]
const onComponentChosen = component => { const onComponentChosen = component => {
if (component.template) { store.addChildComponent(component._component)
// onTemplateChosen(component.template) toggleTab()
} else {
store.addChildComponent(component._component)
toggleTab()
}
} }
// const onTemplateInstanceChosen = () => {
// selectedComponent = null
// const instance = templateInstances.find(
// i => i.name === selectedTemplateInstance
// )
// store.addTemplatedComponent(instance.props)
// toggleTab()
// }
// $: templatesByComponent = groupBy(t => t.component)($store.templates)
// $: standaloneTemplates = pipe(
// templatesByComponent,
// [
// values,
// flatten,
// filter(t => !$store.components.some(c => c.name === t.component)),
// map(t => ({ name: splitName(t.component).componentName, template: t })),
// uniqBy(t => t.name),
// ]
// )
</script> </script>
<div class="root"> <div class="root">
@ -78,25 +53,6 @@
</div> </div>
</div> </div>
<!-- <ConfirmDialog
bind:this={selectTemplateDialog}
title="Choose Template"
onCancel={() => (selectedComponent = null)}
onOk={onTemplateInstanceChosen}>
{#each templateInstances.map(i => i.name) as instance}
<div class="uk-margin uk-grid-small uk-child-width-auto uk-grid">
<label>
<input
class="uk-radio"
type="radio"
bind:group={selectedTemplateInstance}
value={instance} />
<span class="template-instance-label">{instance}</span>
</label>
</div>
{/each}
</ConfirmDialog> -->
<style> <style>
.tabs { .tabs {
display: flex; display: flex;

View File

@ -18,82 +18,79 @@ const {
componentRoutes, componentRoutes,
} = require("./routes") } = require("./routes")
module.exports = app => { const router = new Router()
const router = new Router()
router router
.use( .use(
compress({ compress({
threshold: 2048, threshold: 2048,
gzip: { gzip: {
flush: zlib.Z_SYNC_FLUSH, flush: zlib.Z_SYNC_FLUSH,
}, },
deflate: { deflate: {
flush: zlib.Z_SYNC_FLUSH, flush: zlib.Z_SYNC_FLUSH,
}, },
})
)
.use(async (ctx, next) => {
// TODO: temp dev middleware
ctx.config = {
latestPackagesFolder: resolve(homedir(), ".budibase"),
jwtSecret: "foo",
}
ctx.isDev = process.env.NODE_ENV !== "production"
await next()
}) })
.use(authenticated) )
.use(async (ctx, next) => {
// error handling middleware ctx.config = {
router.use(async (ctx, next) => { latestPackagesFolder: resolve(homedir(), ".budibase"),
try { jwtSecret: process.env.JWT_SECRET,
await next()
} catch (err) {
console.trace(err)
ctx.status = err.status || err.statusCode || 500
ctx.body = {
message: err.message,
status: ctx.status,
}
} }
ctx.isDev = process.env.NODE_ENV !== "production"
await next()
}) })
.use(authenticated)
router.use(authRoutes.routes()) // error handling middleware
router.use(authRoutes.allowedMethods()) router.use(async (ctx, next) => {
try {
await next()
} catch (err) {
console.trace(err)
ctx.status = err.status || err.statusCode || 500
ctx.body = {
message: err.message,
status: ctx.status,
}
}
})
// authenticated routes router.use(authRoutes.routes())
router.use(viewRoutes.routes()) router.use(authRoutes.allowedMethods())
router.use(viewRoutes.allowedMethods())
router.use(modelRoutes.routes()) // authenticated routes
router.use(modelRoutes.allowedMethods()) router.use(viewRoutes.routes())
router.use(viewRoutes.allowedMethods())
router.use(userRoutes.routes()) router.use(modelRoutes.routes())
router.use(userRoutes.allowedMethods()) router.use(modelRoutes.allowedMethods())
router.use(recordRoutes.routes()) router.use(userRoutes.routes())
router.use(recordRoutes.allowedMethods()) router.use(userRoutes.allowedMethods())
router.use(instanceRoutes.routes()) router.use(recordRoutes.routes())
router.use(instanceRoutes.allowedMethods()) router.use(recordRoutes.allowedMethods())
// end auth routes
router.use(pageRoutes.routes()) router.use(instanceRoutes.routes())
router.use(pageRoutes.allowedMethods()) router.use(instanceRoutes.allowedMethods())
// end auth routes
router.use(applicationRoutes.routes()) router.use(pageRoutes.routes())
router.use(applicationRoutes.allowedMethods()) router.use(pageRoutes.allowedMethods())
router.use(componentRoutes.routes()) router.use(applicationRoutes.routes())
router.use(componentRoutes.allowedMethods()) router.use(applicationRoutes.allowedMethods())
router.use(clientRoutes.routes()) router.use(componentRoutes.routes())
router.use(clientRoutes.allowedMethods()) router.use(componentRoutes.allowedMethods())
router.use(staticRoutes.routes()) router.use(clientRoutes.routes())
router.use(staticRoutes.allowedMethods()) router.use(clientRoutes.allowedMethods())
router.redirect("/", "/_builder") router.use(staticRoutes.routes())
router.use(staticRoutes.allowedMethods())
return router router.redirect("/", "/_builder")
}
module.exports = router

View File

@ -1,17 +1,15 @@
const Koa = require("koa") const Koa = require("koa")
const logger = require("koa-logger") const logger = require("koa-logger")
const router = require("./api") const api = require("./api")
const koaBody = require("koa-body") const koaBody = require("koa-body")
const app = new Koa() const app = new Koa()
module.exports = () => { // set up top level koa middleware
app.keys = Object.keys(process.env) app.use(koaBody({ multipart: true }))
.filter(k => k.startsWith("COOKIE_KEY_")) app.use(logger())
.map(k => process.env[k])
app.use(koaBody({ multipart: true })) // api routes
app.use(logger()) app.use(api.routes())
app.use(router(app).routes())
return app.listen(process.env.PORT || 4001) module.exports = app.listen(process.env.PORT || 4001)
}

View File

@ -5,7 +5,7 @@ require("dotenv").config()
const DEV_URL = "http://localhost:4001"; const DEV_URL = "http://localhost:4001";
function createWindow() { function createWindow() {
app.server = require("./app")(); app.server = require("./app");
let win = new BrowserWindow({ width: 1920, height: 1080 }); let win = new BrowserWindow({ width: 1920, height: 1080 });
win.loadURL(DEV_URL); win.loadURL(DEV_URL);
} }

View File

@ -1,11 +1,6 @@
require("dotenv").config() require("dotenv").config()
const app = require("./app") const server = require("./app")
async function startServer() { server.on("listening", () => {
const server = await app() console.log(`Budibase Server listening on port ${process.env.PORT}`)
server.on("listening", () => { });
console.log(`Budibase Server listening on port ${process.env.PORT}`)
})
}
startServer()

View File

@ -1,8 +1,14 @@
const jwt = require("jsonwebtoken") const jwt = require("jsonwebtoken")
const STATUS_CODES = require("../utilities/statusCodes");
module.exports = async (ctx, next) => { module.exports = async (ctx, next) => {
if (ctx.isDev) {
ctx.isAuthenticated = true
await next();
return
}
const token = ctx.cookies.get("budibase:token") const token = ctx.cookies.get("budibase:token")
console.log("TOKEN", token)
if (!token) { if (!token) {
ctx.isAuthenticated = false ctx.isAuthenticated = false
@ -14,7 +20,7 @@ module.exports = async (ctx, next) => {
ctx.jwtPayload = jwt.verify(token, ctx.config.jwtSecret) ctx.jwtPayload = jwt.verify(token, ctx.config.jwtSecret)
ctx.isAuthenticated = true ctx.isAuthenticated = true
} catch (err) { } catch (err) {
ctx.throw(err.status || 403, err.text) ctx.throw(err.status || STATUS_CODES.FORBIDDEN, err.text)
} }
await next() await next()

View File

@ -1,24 +0,0 @@
const session = require("koa-session")
module.exports = app => {
const sessionConfig = {
key: "budi:sess" /** (string) cookie key (default is koa:sess) */,
/** (number || 'session') maxAge in ms (default is 1 days) */
/** 'session' will result in a cookie that expires when session/browser is closed */
/** Warning: If a session cookie is stolen, this cookie will never expire */
maxAge: 86400000,
autoCommit: true /** (boolean) automatically commit headers (default true) */,
overwrite: true /** (boolean) can overwrite or not (default true) */,
httpOnly: true /** (boolean) httpOnly or not (default true) */,
signed: true /** (boolean) signed or not (default true) */,
rolling: false /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */,
renew: false /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/,
store: {
get: async key => ({ key }),
set: async key => ({ key }),
destroy: async () => ({}),
},
}
return session(sessionConfig, app)
}