diff --git a/striker-ui-api/src/routes/static.ts b/striker-ui-api/src/routes/static.ts index c06579e2..12585606 100644 --- a/striker-ui-api/src/routes/static.ts +++ b/striker-ui-api/src/routes/static.ts @@ -1,11 +1,48 @@ import express from 'express'; +import { existsSync } from 'fs'; +import path from 'path'; import { SERVER_PATHS } from '../lib/consts'; +import { assertAuthentication } from '../lib/assertAuthentication'; +import { stdout } from '../lib/shell'; + const router = express.Router(); +const htmlDir = SERVER_PATHS.var.www.html.self; + router.use( - express.static(SERVER_PATHS.var.www.html.self, { + (...args) => { + const { 0: request, 2: next } = args; + const { originalUrl } = request; + + if (/^[/]login/.test(originalUrl)) { + stdout(`Static:login requested`); + + return assertAuthentication({ fail: (rq, rs, nx) => nx(), succeed: '/' })( + ...args, + ); + } + + const parts = originalUrl.replace(/[/]$/, '').split('/'); + const tail = parts.pop() || 'index'; + + parts.push(`${tail}.html`); + + const htmlPath = path.posix.join(htmlDir, ...parts); + const isHtmlExists = existsSync(htmlPath); + + if (isHtmlExists) { + stdout(`Static:[${htmlPath}] requested`); + + return assertAuthentication({ fail: '/login', failReturnTo: true })( + ...args, + ); + } + + return next(); + }, + express.static(htmlDir, { extensions: ['htm', 'html'], }), );