Fixes
[vchess.git] / server / utils / access.js
CommitLineData
625022fd
BA
1var UserModel = require("../models/User");
2
fd08ab2c 3module.exports =
8d7e2786 4{
dac39588
BA
5 // Prevent access to "users pages"
6 logged: function(req, res, next) {
7 const callback = () => {
8 if (!loggedIn)
09d37571 9 res.json({errmsg: "Error: please delete cookies and cross fingers"});
866842c3 10 else next();
dac39588
BA
11 };
12 let loggedIn = undefined;
13 if (!req.cookies.token)
14 {
15 loggedIn = false;
16 callback();
17 }
18 else
19 {
20 UserModel.getOne("sessionToken", req.cookies.token, function(err, user) {
21 if (!!user)
22 {
23 req.userId = user.id;
24 req.userName = user.name;
25 loggedIn = true;
26 }
27 else
28 {
29 // Token in cookies presumably wrong: erase it
30 res.clearCookie("token");
31 loggedIn = false;
32 }
33 callback();
34 });
35 }
36 },
8d7e2786 37
dac39588
BA
38 // Prevent access to "anonymous pages"
39 unlogged: function(req, res, next) {
40 // Just a quick heuristic, which should be enough
41 const loggedIn = !!req.cookies.token;
42 if (loggedIn)
09d37571 43 res.json({errmsg: "Error: please delete cookies and cross fingers"});
866842c3 44 else next();
dac39588 45 },
8d7e2786 46
dac39588
BA
47 // Prevent direct access to AJAX results
48 ajax: function(req, res, next) {
317b8a56 49 if (!req.xhr)
866842c3
BA
50 res.json({errmsg: "Unauthorized access"});
51 else next();
dac39588 52 },
8d7e2786 53
dac39588
BA
54 // Check for errors before callback (continue page loading). TODO: better name.
55 checkRequest: function(res, err, out, msg, cb) {
866842c3
BA
56 if (err)
57 res.json({errmsg: err.errmsg || err.toString()});
58 else if (!out
dac39588
BA
59 || (Array.isArray(out) && out.length == 0)
60 || (typeof out === "object" && Object.keys(out).length == 0))
61 {
866842c3 62 res.json({errmsg: msg});
dac39588 63 }
866842c3 64 else cb();
dac39588 65 },
8d7e2786 66}