]> git.cworth.org Git - empires-server/blob - lmno.js
Return the actual game object from create_game, not just the ID
[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.games = {};
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.games);
68
69     const engine = engines[engine_name];
70
71     const game = new engine.Game(id);
72
73     this.games[id] = game;
74
75     return game;
76   }
77 }
78
79 /* Some letters we don't use in our IDs:
80  *
81  * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
82  * 2. Lowercase letters (replace with corresponding capital on input)
83  * 3. N (replace with M on input)
84  * 4. P (replace with B on input)
85  * 5. S (replace with F on input)
86  */
87 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
88
89 const lmno = new LMNO();
90
91 /* Force a game ID into a canonical form as described above. */
92 function lmno_canonize(id) {
93   /* Capitalize */
94   id = id.toUpperCase();
95
96   /* Replace unused letters with nearest phonetic match. */
97   id = id.replace(/N/g, 'M');
98   id = id.replace(/P/g, 'B');
99   id = id.replace(/S/g, 'F');
100
101   /* Replace unused numbers nearest visual match. */
102   id = id.replace(/0/g, 'O');
103   id = id.replace(/1/g, 'I');
104   id = id.replace(/5/g, 'S');
105
106   return id;
107 }
108
109 app.post('/new/:game_engine', (request, response) =>  {
110   const game_engine = request.params.game_engine;
111   const game = lmno.create_game(game_engine);
112   response.send(JSON.stringify(game.id));
113 });
114
115 /* Redirect any requests to a game ID at the top-level.
116  *
117  * Specifically, after obtaining the game ID (from the path) we simply
118  * lookup the game engine for the corresponding game and then redirect
119  * to the engine- and game-specific path.
120  */
121 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
122   const game_id = request.path.replace(/\//g, "");
123   const canon_id = lmno_canonize(game_id);
124
125   /* Redirect user to page with the canonical ID in it. */
126   if (game_id !== canon_id) {
127     response.redirect(301, `/${canon_id}/`);
128     return;
129   }
130
131   const game = lmno.games[game_id];
132   if (game === undefined) {
133       response.sendStatus(404);
134       return;
135   }
136   response.redirect(301, `/${game.meta.identifier}/${game.id}/`);
137 });
138
139 /* LMNO middleware to lookup the game. */
140 app.use('/:engine([^/]+)/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
141   const engine = request.params.engine;
142   const game_id = request.params.game_id;
143   const canon_id = lmno_canonize(game_id);
144
145   /* Redirect user to page with the canonical ID in it, also ensuring
146    * that the game ID is _always_ followed by a slash. */
147   const has_slash = new RegExp(`^/${engine}/${game_id}/`);
148   if (game_id !== canon_id ||
149       ! has_slash.test(request.originalUrl))
150   {
151     const old_path = new RegExp(`/${engine}/${game_id}/?`);
152     const new_path = `/${engine}/${canon_id}/`;
153     const new_url = request.originalUrl.replace(old_path, new_path);
154     response.redirect(301, new_url);
155     return;
156   }
157
158   /* See if there is any game with this ID. */
159   const game = lmno.games[game_id];
160   if (game === undefined) {
161     response.sendStatus(404);
162     return;
163   }
164
165   /* Stash the game onto the request to be used by the game-specific code. */
166   request.game = game;
167   next();
168 });
169
170 function auth_admin(request, response, next) {
171   /* If there is no user associated with this session, redirect to the login
172    * page (and set a "next" query parameter so we can come back here).
173    */
174   if (! request.session.user) {
175     response.redirect(302, "/login?next=" + request.path);
176     return;
177   }
178
179   /* If the user is logged in but not authorized to view the page then 
180    * we return that error. */
181   if (request.session.user.role !== "admin") {
182     response.status(401).send("Unauthorized");
183     return;
184   }
185   next();
186 }
187
188 app.get('/logout', (request, response) => {
189   request.session.user = undefined;
190   request.session.destroy();
191
192   response.send("You are now logged out.");
193 });
194
195 app.get('/login', (request, response) => {
196   if (request.session.user) {
197     response.send("Welcome, " + request.session.user + ".");
198     return;
199   }
200
201   response.render('login.html');
202 });
203
204 app.post('/login', async (request, response) => {
205   const username = request.body.username;
206   const password = request.body.password;
207   const user = lmno_config.users[username];
208   if (! user) {
209     response.sendStatus(404);
210     return;
211   }
212   const match = await bcrypt.compare(password, user.password_hash_bcrypt);
213   if (! match) {
214     response.sendStatus(404);
215     return;
216   }
217   request.session.user = { username: user.username, role: user.role };
218   response.sendStatus(200);
219   return;
220 });
221
222 /* API to set uer profile information */
223 app.put('/profile', (request, response) => {
224   const nickname = request.body.nickname;
225   if (nickname) {
226     request.session.nickname = nickname;
227     request.session.save();
228   }
229   response.send();
230 });
231
232 /* An admin page (only available to admin users, of course) */
233 app.get('/admin/', auth_admin, (request, response) => {
234   let active = [];
235   let idle = [];
236
237   for (let id in lmno.games) {
238     if (lmno.games[id].clients.length)
239       active.push(lmno.games[id]);
240     else
241       idle.push(lmno.games[id]);
242   }
243   response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
244 });
245
246
247 /* Mount sub apps. only _after_ we have done all the middleware we need. */
248 for (let key in engines) {
249   const engine = engines[key];
250
251   /* Add routes that are common to all games. */
252   engine.router.get('/', (request, response) => {
253     const game = request.game;
254
255     if (! request.session.nickname)
256       response.render('choose-nickname.html', { game_name: game.meta.name });
257     else
258       response.render(`${game.meta.identifier}-game.html`);
259   });
260
261   /* And mount the whole router at the path for the game. */
262   app.use(`/${engine.Game.meta.identifier}/[a-zA-Z0-9]{4}/`, engine.router);
263 }
264
265 app.listen(4000, function () {
266   console.log('LMNO server listening on localhost:4000');
267 });