Faster game start for accepted live challenges
[vchess.git] / server / utils / access.js
CommitLineData
625022fd
BA
1var UserModel = require("../models/User");
2
fd08ab2c 3module.exports =
8d7e2786 4{
dac39588
BA
5 // Prevent access to "users pages"
6 logged: function(req, res, next) {
7 const callback = () => {
8 if (!loggedIn)
2c5d7b20 9 res.json({ errmsg: "Error: try to delete cookies" });
866842c3 10 else next();
dac39588
BA
11 };
12 let loggedIn = undefined;
0234201f 13 if (!req.cookies.token) {
dac39588
BA
14 loggedIn = false;
15 callback();
0234201f 16 } else {
2c5d7b20 17 UserModel.getOne("sessionToken", req.cookies.token, (err, user) => {
0234201f 18 if (!!user) {
dac39588
BA
19 req.userId = user.id;
20 req.userName = user.name;
21 loggedIn = true;
0234201f 22 } else {
dac39588
BA
23 // Token in cookies presumably wrong: erase it
24 res.clearCookie("token");
25 loggedIn = false;
26 }
27 callback();
28 });
29 }
30 },
8d7e2786 31
dac39588
BA
32 // Prevent access to "anonymous pages"
33 unlogged: function(req, res, next) {
34 // Just a quick heuristic, which should be enough
35 const loggedIn = !!req.cookies.token;
2c5d7b20 36 if (loggedIn) res.json({ errmsg: "Error: try to delete cookies" });
866842c3 37 else next();
dac39588 38 },
8d7e2786 39
dac39588
BA
40 // Prevent direct access to AJAX results
41 ajax: function(req, res, next) {
2c5d7b20 42 if (!req.xhr) res.json({ errmsg: "Unauthorized access" });
866842c3 43 else next();
dac39588 44 },
8d7e2786 45
2c5d7b20 46 // Check for errors before callback (continue page loading). (TODO: name?)
dac39588 47 checkRequest: function(res, err, out, msg, cb) {
2c5d7b20 48 if (!!err) res.json({ errmsg: err.errmsg || err.toString() });
0234201f
BA
49 else if (
50 !out ||
51 (Array.isArray(out) && out.length == 0) ||
52 (typeof out === "object" && Object.keys(out).length == 0)
53 ) {
2c5d7b20 54 res.json({ errmsg: msg });
0234201f
BA
55 } else cb();
56 }
8d7e2786 57}