]> git.cworth.org Git - empires-server/blob - lmno.js
lmno: Generalize the support for multiple game engines
[empires-server] / lmno.js
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");
8
9 try {
10   var lmno_config = require("./lmno-config.json");
11 } catch (err) {
12   config_usage();
13   process.exit(1);
14 }
15
16 function config_usage() {
17   console.log(`Error: Refusing to run without configuration.
18
19 Please create a file named lmno-config.json that looks as follows:
20
21 {
22   "session_secret": "<this should be a long string of true-random characters>",
23   "users": {
24     "username": "<username>",
25     "password_hash_bcrypt": "<password_hash_made_by_bcrypt>"
26   }
27 }
28
29 Note: Of course, change all of <these-parts> to actual values desired.
30
31 The "node lmno-passwd.js" command can help generate password hashes.`);
32 }
33
34 const app = express();
35 app.use(cors());
36 app.use(body_parser.urlencoded({ extended: false }));
37 app.use(body_parser.json());
38 app.use(session({
39   secret: lmno_config.session_secret,
40   resave: false,
41   saveUninitialized: false
42 }));
43
44 nunjucks.configure("templates", {
45   autoescape: true,
46   express: app
47 });
48
49 /* Load each of our game mini-apps. */
50 const engines = {
51   empires: require("./empires"),
52   tictactoe: require("./tictactoe")
53 };
54
55 class LMNO {
56   constructor() {
57     this.ids = {};
58   }
59
60   generate_id() {
61     return Array(4).fill(null).map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
62   }
63
64   create_game(engine_name) {
65     do {
66       var id = this.generate_id();
67     } while (id in this.ids);
68
69     const engine = engines[engine_name];
70
71     const game = new engine.Game();
72
73     this.ids[id] = {
74       id: id,
75       engine: engine.name,
76       game: game
77     };
78
79     return id;
80   }
81 }
82
83 /* Some letters we don't use in our IDs:
84  *
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)
90  */
91 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
92
93 const lmno = new LMNO();
94
95 /* Force a game ID into a canonical form as described above. */
96 function lmno_canonize(id) {
97   /* Capitalize */
98   id = id.toUpperCase();
99
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');
104
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');
109
110   return id;
111 }
112
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));
117 });
118
119 /* Redirect any requests to a game ID at the top-level.
120  *
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.
124  */
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);
128
129   /* Redirect user to page with the canonical ID in it. */
130   if (game_id !== canon_id) {
131     response.redirect(301, `/${canon_id}/`);
132     return;
133   }
134
135   const game = lmno.ids[game_id];
136   if (game === undefined) {
137       response.sendStatus(404);
138       return;
139   }
140   response.redirect(301, `/${game.engine}/${game.id}/`);
141 });
142
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);
148
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))
154   {
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     console.log("Redirecting from " + request.originalUrl + " to " + new_url);
159     response.redirect(301, new_url);
160     return;
161   }
162
163   /* See if there is any game with this ID. */
164   const game = lmno.ids[game_id];
165   if (game === undefined) {
166     response.sendStatus(404);
167     return;
168   }
169
170   /* Stash the game onto the request to be used by the game-specific code. */
171   request.game = game.game;
172   next();
173 });
174
175 function auth_admin(request, response, next) {
176   /* If there is no user associated with this session, redirect to the login
177    * page (and set a "next" query parameter so we can come back here).
178    */
179   if (! request.session.user) {
180     response.redirect(302, "/login?next=" + request.path);
181     return;
182   }
183
184   /* If the user is logged in but not authorized to view the page then 
185    * we return that error. */
186   if (request.session.user.role !== "admin") {
187     response.status(401).send("Unauthorized");
188     return;
189   }
190   next();
191 }
192
193 app.get('/logout', (request, response) => {
194   request.session.user = undefined;
195   request.session.destroy();
196
197   response.send("You are now logged out.");
198 });
199
200 app.get('/login', (request, response) => {
201   if (request.session.user) {
202     response.send("Welcome, " + request.session.user + ".");
203     return;
204   }
205
206   response.render('login.html');
207 });
208
209 app.post('/login', async (request, response) => {
210   const username = request.body.username;
211   const password = request.body.password;
212   const user = lmno_config.users[username];
213   if (! user) {
214     response.sendStatus(404);
215     return;
216   }
217   const match = await bcrypt.compare(password, user.password_hash_bcrypt);
218   if (! match) {
219     response.sendStatus(404);
220     return;
221   }
222   request.session.user = { username: user.username, role: user.role };
223   response.sendStatus(200);
224   return;
225 });
226
227 /* API to set uer profile information */
228 app.put('/profile', (request, response) => {
229   const nickname = request.body.nickname;
230   if (nickname) {
231     request.session.nickname = nickname;
232     request.session.save();
233   }
234   response.send();
235 });
236
237 /* An admin page (only available to admin users, of course) */
238 app.get('/admin/', auth_admin, (request, response) => {
239   let active = [];
240   let idle = [];
241
242   for (let id in lmno.ids) {
243     if (lmno.ids[id].game.clients.length)
244       active.push(lmno.ids[id]);
245     else
246       idle.push(lmno.ids[id]);
247   }
248   response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
249 });
250
251
252 /* Mount sub apps. only _after_ we have done all the middleware we need. */
253 for (let key in engines) {
254   const engine = engines[key];
255   app.use(`/${engine.name}/[a-zA-Z0-9]{4}/`, engine.app);
256 }
257
258 app.listen(4000, function () {
259   console.log('LMNO server listening on localhost:4000');
260 });