diff --git a/src/server/http.js b/src/server/http.js index 59873ef..ceed1d0 100644 --- a/src/server/http.js +++ b/src/server/http.js @@ -1,7 +1,7 @@ /* eslint-disable import/no-extraneous-dependencies */ import {createReadStream} from 'fs'; import http, {ServerResponse} from 'http'; -import {join} from 'path'; +import {join, resolve} from 'path'; import concat from 'concat-stream-p'; import express from 'express'; @@ -11,18 +11,19 @@ import {invokeHookFlat} from 'scwp'; import passport from './passport'; import session from './session'; -const hydration = async (req, buffer) => { - const hydration = JSON.stringify( - (await Promise.all(invokeHookFlat('hydration', req))) - .reduce((hydration, result) => ({...hydration, ...result}), {}), - ); - return buffer +const hydrate = async (req, res) => ( + (await Promise.all(invokeHookFlat('hydrators', req, res))) + .reduce((r, hydration) => ({...r, ...hydration}), {}) +); + +const deliver = async (buffer, req, res) => ( + buffer .toString() .replace( 'window.__HYDRATION__ = {};', - `window.__HYDRATION__ = ${hydration};`, - ); -}; + `window.__HYDRATION__ = ${JSON.stringify(await hydrate(req, res))};`, + ) +); export async function createHttpServer() { const app = express(); @@ -41,7 +42,7 @@ export async function createHttpServer() { proxy.on('proxyRes', async (proxyRes, req, res) => { const buffer = await proxyRes.pipe(concat()); if ('text/html; charset=UTF-8' === proxyRes.headers['content-type']) { - res.end(await hydration(req, buffer)); + res.end(await deliver(buffer, req, res)); } else { res.setHeader('Content-Type', proxyRes.headers['content-type']); @@ -60,7 +61,7 @@ export async function createHttpServer() { app.use(express.static(join(__dirname, '..', 'client'))); const stream = createReadStream(join(__dirname, '..', 'client', 'index.html')); const buffer = await stream.pipe(concat()); - app.get('*', async (req, res) => res.end(await hydration(req, buffer))); + app.get('*', async (req, res) => res.end(await deliver(buffer, req, res))); } }; httpServer.listen(31344, '0.0.0.0'); diff --git a/src/server/session.js b/src/server/session.js index 6cf87c5..3e4aaef 100644 --- a/src/server/session.js +++ b/src/server/session.js @@ -19,9 +19,18 @@ export default (options = {}) => ( ); registerHooks({ - hydration: async (req) => ({ - chat: await appChatState(req), - user: await appUserState(req), - usernames: await appUsernamesState(req), - }), + hydrators: async (req, res) => { + if (req.channel && !req.user) { + const {name, type} = req.channel; + if (name !== 'anonymous' || type !== 'r') { + res.redirect('/'); + return new Promise(() => {}); + } + } + return { + chat: await appChatState(req, res), + user: await appUserState(req, res), + usernames: await appUsernamesState(req, res), + }; + }, }, module.id);