-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
323 lines (281 loc) · 10.8 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
///<reference path="typings\main.d.ts"/>
var config = require('config');
import _ = require('underscore');
import http = require('http');
import express = require('express');
import session = require('express-session');
import bodyParser = require('body-parser');
import cookieParser = require('cookie-parser');
var lessMiddleware = require('less-middleware');
import passport = require('passport');
import entities = require('./scripts/shared/entities');
import literki = require('./scripts/shared/literki');
import literki_server = require('./scripts/literki_server');
import db = require('./scripts/db');
import util = require('./scripts/util');
var app = express();
app.use(cookieParser());
app.use(session({ secret: '1234567890qwerty' }));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
app.use(lessMiddleware(__dirname, {
dest: __dirname + '/./public'
}));
app.use(express.static(__dirname + '/./public'));
app.use((err: Error, req, res, next) => {
console.error(err);
res.status(500).send('Something broke!');
});
app.set('view engine', 'jade');
app.locals.pretty = true;
var uri = config.MongoDb.uri;
var repo = new db.GameRepository();
repo.open(uri);
var strategy = config.Passport.strategy;
switch (strategy) {
case 'Google': {
console.log(`GoogleAuthorization.callbackURL: ${config.GoogleAuthorization.callbackURL}`);
var GoogleStrategy = require('passport-google-openidconnect').Strategy;
passport.use(
new GoogleStrategy({
clientID: config.GoogleAuthorization.clientID,
clientSecret: config.GoogleAuthorization.clientSecret,
callbackURL: config.GoogleAuthorization.callbackURL
}, (iss, sub, profile, accessToken, refreshToken, done) => {
repo.loadOrCreateUser(profile.id, profile.displayName, (err, user) => {
return done(err, user)
});
})
);
passport.serializeUser((user, done) => {
done(null, user.id)
});
passport.deserializeUser((id, done) => {
repo.loadUser(id, (err, user) => done(err, user));
});
app.get('/auth/google', passport.authenticate('google-openidconnect'));
app.get('/auth/google/return',
passport.authenticate('google-openidconnect', {
successRedirect: '/main.html',
failureRedirect: '/login.html'
})
);
app.get('/auth/google/signout', (req, res) => {
req.logout();
res.redirect('/login.html');
});
break;
}
case 'Http': {
var users = new Array<{ id: number, userName: string }>();
var HttpStrategy = require('passport-http').BasicStrategy;
passport.use(
new HttpStrategy({}, (userName, password, done) => {
//hack for mocha tests, never use Http strategy in the production
var id = password;
users.push({
id: id,
userName: userName
});
var user = _.last(users);
done(null, user);
})
);
passport.serializeUser((user, done) => {
done(null, user.id)
});
passport.deserializeUser((id, done) => {
var user = _.find(users, (user) => user.id == id);
done(null, user);
});
app.get('/auth/http', passport.authenticate('basic'), (req, res) => {
res.end('Authentifaction successfull');
});
break;
}
default: {
throw new Error(`Unknown passport strategy: ${strategy}`);
}
}
var auth = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.json({ errorMessage: "Błąd uwierzytelnienia użytkownika." });
};
app.get('/login.html', (req, res) => {
res.render('login', { title: 'login' });
});
//app.get('/main.html', auth, (req, res) => {
// repo.allGames((err, games) => {
// var errorMessages = '';
// if (err != null) {
// errorMessages = util.formatError(err);
// }
// res.render('main', { title: 'main', games: games });
// });
//});
app.get('/:pageName.html', auth, (req, res) => {
res.render(req.params.pageName, { title: req.params.pageName });
});
app.post('/game/new', auth, (req, res) => {
repo.loadUser(req.user.id, (err, user) => {
if (err != null) {
var errorMessages = util.formatError(err);
res.json({ errorMessage: errorMessages });
} else {
var request = <entities.NewGameRequest>req.body;
var game = new literki_server.GameRun_Server(req.user.profileId);
game.newGame(user.id, user.userName, request.playerCount, request.timeLimit);
var state: literki.IGameState = game.state;
repo.newState(state, (err, gameId) => {
var errorMessages;
if (err != null) {
errorMessages = util.formatError(err);
}
repo.loadState(gameId, (err, state) => {
if (err != null) {
errorMessages = errorMessages.concat(util.formatError(err));
}
res.json({ state: state, userId: req.user.id, errorMessage: errorMessages });
});
});
}
});
});
app.get('/game/join', auth, (req, res) => {
repo.loadUser(req.user.id, (err, user) => {
if (err != null) {
var errorMessages = util.formatError(err);
res.json({ errorMessage: errorMessages });
} else {
simpleGameMethodCall(req, res, (game, req, call) => call(game.join(user.userName)));
}
});
});
app.get('/game/list', auth, (req, res) => {
repo.allGames((err, games) => {
var errorMessages = '';
if (err != null) {
errorMessages = util.formatError(err);
}
res.json({ games: games, errorMessage: errorMessages });
});
});
app.get('/game/get', auth, (req, res) => {
var gameId: number = req.query.gameId;
repo.loadState(gameId,(err, state) => {
var errorMessages;
if (err != null) {
errorMessages = util.formatError(err);
}
res.json({ state: state, userId: req.user.id, errorMessage: errorMessages });
});
});
app.get('/game/start', auth, (req, res) => simpleGameMethodCall(req, res, (game, req, call) => call(game.start())));
app.get('/game/pause', auth, (req, res) => simpleGameMethodCall(req, res, (game, req, call) => call(game.pause())));
app.get('/game/fold', auth, (req, res) => simpleGameMethodCall(req, res, (game, req, call) => call(game.fold())));
app.get('/game/exchange', auth,(req, res) => simpleGameMethodCall(req, res, (game, req, call) => call(game.exchange(req.query.exchangeLetters))));
app.post('/game/approve', auth, (req, res) => {
var approve = req.body.approve;
simpleGameMethodCall(req, res, (game, req, call) => {
game.renderMove();
repo.existWords(game.getNewWords().map(w => w.word), "pl", (err, exists) => {
call(game.approveMove(approve, exists));
});
}, req.body.gameId);
});
app.post('/game/move', auth, (req, res) => {
var move = <literki.GameMove> req.body;
simpleGameMethodCall(req, res, (game, req, call) => call(game.makeMove(move)), move.gameId);
});
app.get('/player/get', auth, (req, res) => {
repo.loadUser(req.user.id, (err, userProfile) => {
if (err != null) {
var errorMessage = util.formatError(err);
}
res.json({ userProfile: userProfile, errorMessage: errorMessage });
});
});
app.post('/player/update', auth, (req, res) => {
var userProfile = req.body;
repo.saveUser(userProfile, (err) => {
if (err != null) {
var errorMessage = util.formatError(err);
res.json({ errorMessage: errorMessage });
} else {
repo.loadUser(req.user.id, (err, userProfile) => {
if (err != null) {
var errorMessage = util.formatError(err);
}
res.json({ userProfile: userProfile, errorMessage: errorMessage });
});
}
});
});
app.post('/player/alive', auth, (req, res) => simpleGameMethodCall(req, res, (game, req, call) => {
var result = game.alive();
var forceRefresh =
game.getCurrentPlayer().userId != req.body.currentPlayerId ||
game.state.playState != req.body.playState ||
game.getPlayers().length != req.body.playersCount;
result.forceRefresh = forceRefresh;
return call(result);
}, req.body.gameId));
app.get('/server/alive', auth, (req, res) => {
res.json({ errorMessage: undefined });
});
type gameMethodCallback = (game: literki_server.GameRun_Server, req: express.Request, call: (result: literki_server.GameMethodResult) => any) => void;
function simpleGameMethodCall(req: express.Request, res: express.Response, call: gameMethodCallback, gameId: number = req.query.gameId): void {
repo.loadState(gameId, (err, state) => {
var errorMessages;
if (err || !state) {
if (err) {
errorMessages = util.formatError(err);
}
res.json({ state: state, userId: req.user.id, errorMessage: errorMessages });
} else {
var game = new literki_server.GameRun_Server(req.user.id);
state = literki.GameState.fromJSON(state);
game.runState(state);
call(game, req, (result) => {
var errMsg = result.errorMessage;
if (errMsg) {
//to discard any changes to current game state
repo.loadState(gameId, (err, unchangedState) => {
unchangedState = literki.GameState.fromJSON(unchangedState);
res.json({ state: unchangedState, userId: req.user.id, errorMessage: errMsg });
});
} else {
state = game.state;
repo.saveState(state, (err) => {
if (err) {
errorMessages = errorMessages.concat(util.formatError(err));
}
res.json({ state: state, userId: req.user.id, forceRefresh: result.forceRefresh, errorMessage: errorMessages });
});
}
});
}
});
}
var server: http.Server;
export function start() {
if (!server) {
var port = process.env.port || config.Server.port;
console.log('Literki start');
console.log('Literki port: ' + port);
server = app.listen(port, '0.0.0.0');
}
}
export function stop() {
if (server) {
console.log('Literki shutdown');
server.close();
server = null;
}
}
export function getGameRepository() {
return repo;
}