]> git.cworth.org Git - empires-server/blob - lmno.js
Rename "app" to "router" within each game engine
[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     response.redirect(301, new_url);
159     return;
160   }
161
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);
166     return;
167   }
168
169   /* Stash the game onto the request to be used by the game-specific code. */
170   request.game = game.game;
171   next();
172 });
173
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).
177    */
178   if (! request.session.user) {
179     response.redirect(302, "/login?next=" + request.path);
180     return;
181   }
182
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");
187     return;
188   }
189   next();
190 }
191
192 app.get('/logout', (request, response) => {
193   request.session.user = undefined;
194   request.session.destroy();
195
196   response.send("You are now logged out.");
197 });
198
199 app.get('/login', (request, response) => {
200   if (request.session.user) {
201     response.send("Welcome, " + request.session.user + ".");
202     return;
203   }
204
205   response.render('login.html');
206 });
207
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];
212   if (! user) {
213     response.sendStatus(404);
214     return;
215   }
216   const match = await bcrypt.compare(password, user.password_hash_bcrypt);
217   if (! match) {
218     response.sendStatus(404);
219     return;
220   }
221   request.session.user = { username: user.username, role: user.role };
222   response.sendStatus(200);
223   return;
224 });
225
226 /* API to set uer profile information */
227 app.put('/profile', (request, response) => {
228   const nickname = request.body.nickname;
229   if (nickname) {
230     request.session.nickname = nickname;
231     request.session.save();
232   }
233   response.send();
234 });
235
236 /* An admin page (only available to admin users, of course) */
237 app.get('/admin/', auth_admin, (request, response) => {
238   let active = [];
239   let idle = [];
240
241   for (let id in lmno.ids) {
242     if (lmno.ids[id].game.clients.length)
243       active.push(lmno.ids[id]);
244     else
245       idle.push(lmno.ids[id]);
246   }
247   response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
248 });
249
250
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.router);
255 }
256
257 app.listen(4000, function () {
258   console.log('LMNO server listening on localhost:4000');
259 });