]> git.cworth.org Git - empires-server/blob - lmno.js
Rename the /stats page to /admin
[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
52 class LMNO {
53   constructor() {
54     this.ids = {};
55   }
56
57   generate_id() {
58     return [null,null,null,null].map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
59   }
60
61   create_game(engine) {
62     do {
63       var id = this.generate_id();
64     } while (id in this.ids);
65
66     const game = new empires.Game();
67
68     this.ids[id] = {
69         id: id,
70         engine: engine,
71         game: game
72     };
73
74     return id;
75   }
76 }
77
78 /* Some letters we don't use in our IDs:
79  *
80  * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
81  * 2. Lowercase letters (replace with corresponding capital on input)
82  * 3. N (replace with M on input)
83  * 4. P (replace with B on input)
84  * 5. S (replace with F on input)
85  */
86 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
87
88 const lmno = new LMNO();
89
90 /* Force a game ID into a canonical form as described above. */
91 function lmno_canonize(id) {
92   /* Capitalize */
93   id = id.toUpperCase();
94
95   /* Replace unused letters with nearest phonetic match. */
96   id = id.replace(/N/g, 'M');
97   id = id.replace(/P/g, 'B');
98   id = id.replace(/S/g, 'F');
99
100   /* Replace unused numbers nearest visual match. */
101   id = id.replace(/0/g, 'O');
102   id = id.replace(/1/g, 'I');
103   id = id.replace(/5/g, 'S');
104
105   return id;
106 }
107
108 app.post('/new/:game_engine', (request, response) =>  {
109   const game_engine = request.params.game_engine;
110   const game_id = lmno.create_game(game_engine);
111   response.send(JSON.stringify(game_id));
112 });
113
114 /* Redirect any requests to a game ID at the top-level.
115  *
116  * Specifically, after obtaining the game ID (from the path) we simply
117  * lookup the game engine for the corresponding game and then redirect
118  * to the engine- and game-specific path.
119  */
120 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
121   const game_id = request.path.replace(/\//g, "");
122   const canon_id = lmno_canonize(game_id);
123
124   /* Redirect user to page with the canonical ID in it. */
125   if (game_id !== canon_id) {
126     response.redirect(301, `/${canon_id}/`);
127     return;
128   }
129
130   const game = lmno.ids[game_id];
131   if (game === undefined) {
132       response.sendStatus(404);
133       return;
134   }
135   response.redirect(301, `/${game.engine}/${game.id}/`);
136 });
137
138 /* LMNO middleware to lookup the game. */
139 app.use('/empires/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
140   const game_id = request.params.game_id;
141   const canon_id = lmno_canonize(game_id);
142
143   /* Redirect user to page with the canonical ID in it. */
144   if (game_id !== canon_id) {
145     const new_url = request.originalUrl.replace("/empires/" + game_id,
146                                                 "/empires/" + canon_id);
147     response.redirect(301, new_url);
148     return;
149   }
150
151   /* See if there is any game with this ID. */
152   const game = lmno.ids[game_id];
153   if (game === undefined) {
154     response.sendStatus(404);
155     return;
156   }
157
158   /* Stash the game onto the request to be used by the game-specific code. */
159   request.game = game.game;
160   next();
161 });
162
163 function auth_admin(request, response, next) {
164   /* If there is no user associated with this session, redirect to the login
165    * page (and set a "next" query parameter so we can come back here).
166    */
167   if (! request.session.user) {
168     response.redirect(302, "/login?next=" + request.path);
169     return;
170   }
171
172   /* If the user is logged in but not authorized to view the page then 
173    * we return that error. */
174   if (request.session.user.role !== "admin") {
175     response.status(401).send("Unauthorized");
176     return;
177   }
178   next();
179 }
180
181 app.get('/logout', (request, response) => {
182   request.session.user = undefined;
183
184   response.send("You are now logged out.");
185 });
186
187 app.get('/login', (request, response) => {
188   if (request.session.user) {
189     response.send("Welcome, " + request.session.user + ".");
190     return;
191   }
192
193   response.render('login.html');
194 });
195
196 app.post('/login', async (request, response) => {
197   const username = request.body.username;
198   const password = request.body.password;
199   const user = lmno_config.users[username];
200   if (! user) {
201     response.sendStatus(404);
202     return;
203   }
204   const match = await bcrypt.compare(password, user.password_hash_bcrypt);
205   if (! match) {
206     response.sendStatus(404);
207     return;
208   }
209   request.session.user = { username: user.username, role: user.role };
210   response.sendStatus(200);
211   return;
212 });
213
214 /* An admin page (only available to admin users, of course) */
215 app.get('/admin/', auth_admin, (request, response) => {
216   let active = 0;
217   let idle = 0;
218
219   for (let id in lmno.ids) {
220     if (lmno.ids[id].game.clients.length)
221       active++;
222    else
223       idle++;
224   }
225   response.send(`<html><body>Active games: ${active}.<br>
226 Idle games: ${idle}</body></html>`);
227 });
228
229
230 /* Mount sub apps. only _after_ we have done all the middleware we need. */
231 app.use('/empires/[a-zA-Z0-9]{4}/', empires.app);
232
233 app.listen(4000, function () {
234   console.log('LMNO server listening on localhost:4000');
235 });