Remove unused variable. TODO: userModel.getOne() with selected fields in arg
[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 19 req.userId = user.id;
dac39588 20 loggedIn = true;
0234201f 21 } else {
dac39588
BA
22 // Token in cookies presumably wrong: erase it
23 res.clearCookie("token");
24 loggedIn = false;
25 }
26 callback();
27 });
28 }
29 },
8d7e2786 30
dac39588
BA
31 // Prevent access to "anonymous pages"
32 unlogged: function(req, res, next) {
33 // Just a quick heuristic, which should be enough
34 const loggedIn = !!req.cookies.token;
2c5d7b20 35 if (loggedIn) res.json({ errmsg: "Error: try to delete cookies" });
866842c3 36 else next();
dac39588 37 },
8d7e2786 38
dac39588
BA
39 // Prevent direct access to AJAX results
40 ajax: function(req, res, next) {
2c5d7b20 41 if (!req.xhr) res.json({ errmsg: "Unauthorized access" });
866842c3 42 else next();
dac39588 43 },
8d7e2786 44
2c5d7b20 45 // Check for errors before callback (continue page loading). (TODO: name?)
dac39588 46 checkRequest: function(res, err, out, msg, cb) {
2c5d7b20 47 if (!!err) res.json({ errmsg: err.errmsg || err.toString() });
0234201f
BA
48 else if (
49 !out ||
50 (Array.isArray(out) && out.length == 0) ||
51 (typeof out === "object" && Object.keys(out).length == 0)
52 ) {
2c5d7b20 53 res.json({ errmsg: msg });
0234201f
BA
54 } else cb();
55 }
8d7e2786 56}