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.ids);
69 const engine = engines[engine_name];
71 const game = new engine.Game();
83 /* Some letters we don't use in our IDs:
85 * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
86 * 2. Lowercase letters (replace with corresponding capital on input)
87 * 3. N (replace with M on input)
88 * 4. P (replace with B on input)
89 * 5. S (replace with F on input)
91 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
93 const lmno = new LMNO();
95 /* Force a game ID into a canonical form as described above. */
96 function lmno_canonize(id) {
98 id = id.toUpperCase();
100 /* Replace unused letters with nearest phonetic match. */
101 id = id.replace(/N/g, 'M');
102 id = id.replace(/P/g, 'B');
103 id = id.replace(/S/g, 'F');
105 /* Replace unused numbers nearest visual match. */
106 id = id.replace(/0/g, 'O');
107 id = id.replace(/1/g, 'I');
108 id = id.replace(/5/g, 'S');
113 app.post('/new/:game_engine', (request, response) => {
114 const game_engine = request.params.game_engine;
115 const game_id = lmno.create_game(game_engine);
116 response.send(JSON.stringify(game_id));
119 /* Redirect any requests to a game ID at the top-level.
121 * Specifically, after obtaining the game ID (from the path) we simply
122 * lookup the game engine for the corresponding game and then redirect
123 * to the engine- and game-specific path.
125 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
126 const game_id = request.path.replace(/\//g, "");
127 const canon_id = lmno_canonize(game_id);
129 /* Redirect user to page with the canonical ID in it. */
130 if (game_id !== canon_id) {
131 response.redirect(301, `/${canon_id}/`);
135 const game = lmno.ids[game_id];
136 if (game === undefined) {
137 response.sendStatus(404);
140 response.redirect(301, `/${game.engine}/${game.id}/`);
143 /* LMNO middleware to lookup the game. */
144 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
145 const engine = request.params.engine;
146 const game_id = request.params.game_id;
147 const canon_id = lmno_canonize(game_id);
149 /* Redirect user to page with the canonical ID in it, also ensuring
150 * that the game ID is _always_ followed by a slash. */
151 const has_slash = new RegExp(`^/${engine}/${game_id}/`);
152 if (game_id !== canon_id ||
153 ! has_slash.test(request.originalUrl))
155 const old_path = new RegExp(`/${engine}/${game_id}/?`);
156 const new_path = `/${engine}/${canon_id}/`;
157 const new_url = request.originalUrl.replace(old_path, new_path);
158 response.redirect(301, new_url);
162 /* See if there is any game with this ID. */
163 const game = lmno.ids[game_id];
164 if (game === undefined) {
165 response.sendStatus(404);
169 /* Stash the game onto the request to be used by the game-specific code. */
170 request.game = game.game;
174 function auth_admin(request, response, next) {
175 /* If there is no user associated with this session, redirect to the login
176 * page (and set a "next" query parameter so we can come back here).
178 if (! request.session.user) {
179 response.redirect(302, "/login?next=" + request.path);
183 /* If the user is logged in but not authorized to view the page then
184 * we return that error. */
185 if (request.session.user.role !== "admin") {
186 response.status(401).send("Unauthorized");
192 app.get('/logout', (request, response) => {
193 request.session.user = undefined;
194 request.session.destroy();
196 response.send("You are now logged out.");
199 app.get('/login', (request, response) => {
200 if (request.session.user) {
201 response.send("Welcome, " + request.session.user + ".");
205 response.render('login.html');
208 app.post('/login', async (request, response) => {
209 const username = request.body.username;
210 const password = request.body.password;
211 const user = lmno_config.users[username];
213 response.sendStatus(404);
216 const match = await bcrypt.compare(password, user.password_hash_bcrypt);
218 response.sendStatus(404);
221 request.session.user = { username: user.username, role: user.role };
222 response.sendStatus(200);
226 /* API to set uer profile information */
227 app.put('/profile', (request, response) => {
228 const nickname = request.body.nickname;
230 request.session.nickname = nickname;
231 request.session.save();
236 /* An admin page (only available to admin users, of course) */
237 app.get('/admin/', auth_admin, (request, response) => {
241 for (let id in lmno.ids) {
242 if (lmno.ids[id].game.clients.length)
243 active.push(lmno.ids[id]);
245 idle.push(lmno.ids[id]);
247 response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
251 /* Mount sub apps. only _after_ we have done all the middleware we need. */
252 for (let key in engines) {
253 const engine = engines[key];
254 app.use(`/${engine.name}/[a-zA-Z0-9]{4}/`, engine.app);
257 app.listen(4000, function () {
258 console.log('LMNO server listening on localhost:4000');