import { Flaska, QueryHandler, JsonHandler, FormidableHandler } from 'flaska' import formidable from 'formidable' import { initPool } from './db.mjs' import config from './config.mjs' import PageRoutes from './page/routes.mjs' import ServeHandler from './serve.mjs' import ArticleRoutes from './article/routes.mjs' import AuthenticationRoutes from './authentication/routes.mjs' import { authenticate } from './authentication/security.mjs' export function run(http, port, core) { let localUtil = new core.sc.Util(import.meta.url) // Create our server const flaska = new Flaska({ appendHeaders: { 'Content-Security-Policy': `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src * data: blob:; font-src 'self' data:; object-src 'none'; frame-ancestors 'none'`, }, log: core.log, nonce: ['script-src'], nonceCacheLength: 50, }, http) // Create our database pool let pool = initPool(core, config.get('mssql')) // configure our server if (config.get('NODE_ENV') === 'development') { flaska.devMode() } flaska.before(function(ctx) { ctx.state.started = new Date().getTime() ctx.db = pool }) flaska.before(QueryHandler()) flaska.after(function(ctx) { let ended = new Date().getTime() var requestTime = ended - ctx.state.started let status = '' let level = 'info' if (ctx.status >= 400) { status = ctx.status + ' ' level = 'warn' } if (ctx.status >= 500) { level = 'error' } ctx.log[level]({ duration: requestTime, status: ctx.status, }, `<-- ${status}${ctx.method} ${ctx.url}`) }) const page = new PageRoutes() flaska.get('/api/pagetree', page.getPageTree.bind(page)) flaska.get('/api/frontpage', page.getPage.bind(page)) flaska.get('/api/pages/:path', page.getPage.bind(page)) // flaska.get('/api/pages/:pageId', page.getSinglePage.bind(page)) const article = new ArticleRoutes() flaska.get('/api/articles/:path', article.getArticle.bind(article)) flaska.get('/api/auth/articles', authenticate(), article.auth_getAllArticles.bind(article)) flaska.get('/api/auth/articles/:path', authenticate(), article.auth_getSingleArticle.bind(article)) flaska.put('/api/auth/articles/:path', [authenticate(), FormidableHandler(formidable) ], article.auth_updateCreateSingleArticle.bind(article)) // flaska.get('/api/pages/:pageId/articles/public', article.getPublicAllPageArticles.bind(article)) const authentication = new AuthenticationRoutes() flaska.post('/api/authentication/login', JsonHandler(), authentication.login.bind(authentication)) const serve = new ServeHandler({ root: localUtil.getPathFromRoot('../public'), version: core.app.running, frontend: config.get('frontend:url'), }) flaska.get('/::file', serve.serve.bind(serve)) return flaska.listenAsync(port).then(function() { core.log.info('Server is listening on port ' + port) }) }