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