]> git.cworth.org Git - empires-server/blob - lmno.js
Ensure path ending with game ID always has a trailing slash
[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 var empires = require("./empires");
51 var tictactoe = require("./tictactoe");
52
53 class LMNO {
54   constructor() {
55     this.ids = {};
56   }
57
58   generate_id() {
59     return Array(4).fill(null).map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
60   }
61
62   create_game(engine) {
63     do {
64       var id = this.generate_id();
65     } while (id in this.ids);
66
67     const game = new empires.Game();
68
69     this.ids[id] = {
70         id: id,
71         engine: engine,
72         game: game
73     };
74
75     return id;
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_id = 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.ids[game_id];
132   if (game === undefined) {
133       response.sendStatus(404);
134       return;
135   }
136   response.redirect(301, `/${game.engine}/${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     console.log("Redirecting from " + request.originalUrl + " to " + new_url);
155     response.redirect(301, new_url);
156     return;
157   }
158
159   /* See if there is any game with this ID. */
160   const game = lmno.ids[game_id];
161   if (game === undefined) {
162     response.sendStatus(404);
163     return;
164   }
165
166   /* Stash the game onto the request to be used by the game-specific code. */
167   request.game = game.game;
168   next();
169 });
170
171 function auth_admin(request, response, next) {
172   /* If there is no user associated with this session, redirect to the login
173    * page (and set a "next" query parameter so we can come back here).
174    */
175   if (! request.session.user) {
176     response.redirect(302, "/login?next=" + request.path);
177     return;
178   }
179
180   /* If the user is logged in but not authorized to view the page then 
181    * we return that error. */
182   if (request.session.user.role !== "admin") {
183     response.status(401).send("Unauthorized");
184     return;
185   }
186   next();
187 }
188
189 app.get('/logout', (request, response) => {
190   request.session.user = undefined;
191   request.session.destroy();
192
193   response.send("You are now logged out.");
194 });
195
196 app.get('/login', (request, response) => {
197   if (request.session.user) {
198     response.send("Welcome, " + request.session.user + ".");
199     return;
200   }
201
202   response.render('login.html');
203 });
204
205 app.post('/login', async (request, response) => {
206   const username = request.body.username;
207   const password = request.body.password;
208   const user = lmno_config.users[username];
209   if (! user) {
210     response.sendStatus(404);
211     return;
212   }
213   const match = await bcrypt.compare(password, user.password_hash_bcrypt);
214   if (! match) {
215     response.sendStatus(404);
216     return;
217   }
218   request.session.user = { username: user.username, role: user.role };
219   response.sendStatus(200);
220   return;
221 });
222
223 /* API to set uer profile information */
224 app.put('/profile', (request, response) => {
225   const nickname = request.body.nickname;
226   if (nickname) {
227     request.session.nickname = nickname;
228     request.session.save();
229   }
230   response.send();
231 });
232
233 /* An admin page (only available to admin users, of course) */
234 app.get('/admin/', auth_admin, (request, response) => {
235   let active = [];
236   let idle = [];
237
238   for (let id in lmno.ids) {
239     if (lmno.ids[id].game.clients.length)
240       active.push(lmno.ids[id]);
241     else
242       idle.push(lmno.ids[id]);
243   }
244   response.render('admin.html', { test: "foobar", games: { active: active, idle: idle}});
245 });
246
247
248 /* Mount sub apps. only _after_ we have done all the middleware we need. */
249 app.use('/empires/[a-zA-Z0-9]{4}/', empires.app);
250 app.use('/tictactoe/[a-zA-Z0-9]{4}/', tictactoe.app);
251
252 app.listen(4000, function () {
253   console.log('LMNO server listening on localhost:4000');
254 });