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