1 const express = require("express");
2 const cors = require("cors");
3 const body_parser = require("body-parser");
4 const session = require("express-session");
5 const bcrypt = require("bcrypt");
6 const path = require("path");
7 const nunjucks = require("nunjucks");
10 var lmno_config = require("./lmno-config.json");
16 function config_usage() {
17 console.log(`Error: Refusing to run without configuration.
19 Please create a file named lmno-config.json that looks as follows:
22 "session_secret": "<this should be a long string of true-random characters>",
24 "username": "<username>",
25 "password_hash_bcrypt": "<password_hash_made_by_bcrypt>"
29 Note: Of course, change all of <these-parts> to actual values desired.
31 The "node lmno-passwd.js" command can help generate password hashes.`);
34 const app = express();
36 app.use(body_parser.urlencoded({ extended: false }));
37 app.use(body_parser.json());
39 secret: lmno_config.session_secret,
41 saveUninitialized: false
44 nunjucks.configure("templates", {
49 /* Load each of our game mini-apps. */
51 empires: require("./empires"),
52 tictactoe: require("./tictactoe")
61 return Array(4).fill(null).map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
64 create_game(engine_name) {
66 var id = this.generate_id();
67 } while (id in this.games);
69 const engine = engines[engine_name];
71 const game = new engine.Game();
82 /* Some letters we don't use in our IDs:
84 * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
85 * 2. Lowercase letters (replace with corresponding capital on input)
86 * 3. N (replace with M on input)
87 * 4. P (replace with B on input)
88 * 5. S (replace with F on input)
90 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
92 const lmno = new LMNO();
94 /* Force a game ID into a canonical form as described above. */
95 function lmno_canonize(id) {
97 id = id.toUpperCase();
99 /* Replace unused letters with nearest phonetic match. */
100 id = id.replace(/N/g, 'M');
101 id = id.replace(/P/g, 'B');
102 id = id.replace(/S/g, 'F');
104 /* Replace unused numbers nearest visual match. */
105 id = id.replace(/0/g, 'O');
106 id = id.replace(/1/g, 'I');
107 id = id.replace(/5/g, 'S');
112 app.post('/new/:game_engine', (request, response) => {
113 const game_engine = request.params.game_engine;
114 const game_id = lmno.create_game(game_engine);
115 response.send(JSON.stringify(game_id));
118 /* Redirect any requests to a game ID at the top-level.
120 * Specifically, after obtaining the game ID (from the path) we simply
121 * lookup the game engine for the corresponding game and then redirect
122 * to the engine- and game-specific path.
124 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
125 const game_id = request.path.replace(/\//g, "");
126 const canon_id = lmno_canonize(game_id);
128 /* Redirect user to page with the canonical ID in it. */
129 if (game_id !== canon_id) {
130 response.redirect(301, `/${canon_id}/`);
134 const game = lmno.games[game_id];
135 if (game === undefined) {
136 response.sendStatus(404);
139 response.redirect(301, `/${game.game.meta.identifier}/${game.id}/`);
142 /* LMNO middleware to lookup the game. */
143 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
144 const engine = request.params.engine;
145 const game_id = request.params.game_id;
146 const canon_id = lmno_canonize(game_id);
148 /* Redirect user to page with the canonical ID in it, also ensuring
149 * that the game ID is _always_ followed by a slash. */
150 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
151 if (game_id !== canon_id ||
152 ! has_slash.test(request.originalUrl))
154 const old_path = new RegExp(`/${engine}/${game_id}/?`);
155 const new_path = `/${engine}/${canon_id}/`;
156 const new_url = request.originalUrl.replace(old_path, new_path);
157 response.redirect(301, new_url);
161 /* See if there is any game with this ID. */
162 const game = lmno.games[game_id];
163 if (game === undefined) {
164 response.sendStatus(404);
168 /* Stash the game onto the request to be used by the game-specific code. */
169 request.game = game.game;
173 function auth_admin(request, response, next) {
174 /* If there is no user associated with this session, redirect to the login
175 * page (and set a "next" query parameter so we can come back here).
177 if (! request.session.user) {
178 response.redirect(302, "/login?next=" + request.path);
182 /* If the user is logged in but not authorized to view the page then
183 * we return that error. */
184 if (request.session.user.role !== "admin") {
185 response.status(401).send("Unauthorized");
191 app.get('/logout', (request, response) => {
192 request.session.user = undefined;
193 request.session.destroy();
195 response.send("You are now logged out.");
198 app.get('/login', (request, response) => {
199 if (request.session.user) {
200 response.send("Welcome, " + request.session.user + ".");
204 response.render('login.html');
207 app.post('/login', async (request, response) => {
208 const username = request.body.username;
209 const password = request.body.password;
210 const user = lmno_config.users[username];
212 response.sendStatus(404);
215 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
217 response.sendStatus(404);
220 request.session.user = { username: user.username, role: user.role };
221 response.sendStatus(200);
225 /* API to set uer profile information */
226 app.put('/profile', (request, response) => {
227 const nickname = request.body.nickname;
229 request.session.nickname = nickname;
230 request.session.save();
235 /* An admin page (only available to admin users, of course) */
236 app.get('/admin/', auth_admin, (request, response) => {
240 for (let id in lmno.games) {
241 if (lmno.games[id].game.clients.length)
242 active.push(lmno.games[id]);
244 idle.push(lmno.games[id]);
246 response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
250 /* Mount sub apps. only _after_ we have done all the middleware we need. */
251 for (let key in engines) {
252 const engine = engines[key];
254 /* Add routes that are common to all games. */
255 engine.router.get('/', (request, response) => {
256 const game = request.game;
258 if (! request.session.nickname)
259 response.render('choose-nickname.html', { game_name: game.meta.name });
261 response.render(`${game.meta.identifier}-game.html`);
264 /* And mount the whole router at the path for the game. */
265 app.use(`/${engine.Game.meta.identifier}/[a-zA-Z0-9]{4}/`, engine.router);
268 app.listen(4000, function () {
269 console.log('LMNO server listening on localhost:4000');