Update TODO + cosmetics
[vchess.git] / server / utils / access.js
1 var UserModel = require("../models/User");
2
3 module.exports = {
4
5 // Prevent access to "users pages"
6 logged: function(req, res, next) {
7 const callback = () => {
8 if (!loggedIn)
9 res.json({ errmsg: "Error: try to delete cookies" });
10 else next();
11 };
12 let loggedIn = undefined;
13 if (!req.cookies.token) {
14 loggedIn = false;
15 callback();
16 } else {
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();
29 }
30 );
31 }
32 },
33
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;
38 if (loggedIn) res.json({ errmsg: "Error: try to delete cookies" });
39 else next();
40 },
41
42 // Prevent direct access to AJAX results
43 ajax: function(req, res, next) {
44 if (!req.xhr) res.json({ errmsg: "Unauthorized access" });
45 else next();
46 },
47
48 // Check for errors before callback (continue page loading). (TODO: name?)
49 checkRequest: function(res, err, out, msg, cb) {
50 if (!!err) res.json({ errmsg: err.errmsg || err.toString() });
51 else if (
52 !out ||
53 (Array.isArray(out) && out.length == 0) ||
54 (typeof out === "object" && Object.keys(out).length == 0)
55 ) {
56 res.json({ errmsg: msg });
57 } else cb();
58 }
59
60 };