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