Cosmetics, mostly, and a few small bugs fixes
[vchess.git] / server / utils / access.js
... / ...
CommitLineData
1var UserModel = require("../models/User");
2
3module.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 req.userName = user.name;
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 // Prevent access to "anonymous pages"
33 unlogged: function(req, res, next) {
34 // Just a quick heuristic, which should be enough
35 const loggedIn = !!req.cookies.token;
36 if (loggedIn) res.json({ errmsg: "Error: try to delete cookies" });
37 else next();
38 },
39
40 // Prevent direct access to AJAX results
41 ajax: function(req, res, next) {
42 if (!req.xhr) res.json({ errmsg: "Unauthorized access" });
43 else next();
44 },
45
46 // Check for errors before callback (continue page loading). (TODO: name?)
47 checkRequest: function(res, err, out, msg, cb) {
48 if (!!err) res.json({ errmsg: err.errmsg || err.toString() });
49 else if (
50 !out ||
51 (Array.isArray(out) && out.length == 0) ||
52 (typeof out === "object" && Object.keys(out).length == 0)
53 ) {
54 res.json({ errmsg: msg });
55 } else cb();
56 }
57}