Add 'display' DB field for nicer variants display. Remove join on Variants table...
[vchess.git] / server / utils / access.js
CommitLineData
625022fd
BA
1var UserModel = require("../models/User");
2
fccaa878 3module.exports = {
937c24ab 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 {
fccaa878
BA
17 UserModel.getOne(
18 "sessionToken", req.cookies.token, "id",
19 (err, user) => {
20 if (!!user) {
21 req.userId = user.id;
22 loggedIn = true;
23 } else {
24 // Token in cookies presumably wrong: erase it
25 res.clearCookie("token");
26 loggedIn = false;
27 }
28 callback();
dac39588 29 }
fccaa878 30 );
dac39588
BA
31 }
32 },
8d7e2786 33
dac39588
BA
34 // Prevent access to "anonymous pages"
35 unlogged: function(req, res, next) {
36 // Just a quick heuristic, which should be enough
37 const loggedIn = !!req.cookies.token;
2c5d7b20 38 if (loggedIn) res.json({ errmsg: "Error: try to delete cookies" });
866842c3 39 else next();
dac39588 40 },
8d7e2786 41
dac39588
BA
42 // Prevent direct access to AJAX results
43 ajax: function(req, res, next) {
2c5d7b20 44 if (!req.xhr) res.json({ errmsg: "Unauthorized access" });
866842c3 45 else next();
dac39588 46 },
8d7e2786 47
2c5d7b20 48 // Check for errors before callback (continue page loading). (TODO: name?)
dac39588 49 checkRequest: function(res, err, out, msg, cb) {
2c5d7b20 50 if (!!err) res.json({ errmsg: err.errmsg || err.toString() });
0234201f
BA
51 else if (
52 !out ||
53 (Array.isArray(out) && out.length == 0) ||
54 (typeof out === "object" && Object.keys(out).length == 0)
55 ) {
2c5d7b20 56 res.json({ errmsg: msg });
0234201f
BA
57 } else cb();
58 }
937c24ab 59
fccaa878 60};