d51c4b77c6b673780810ee7d71448c342871ff9e
[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 return res.json({errmsg: "Not logged in"});
10 next();
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 },
37
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)
43 return res.json({errmsg: "Already logged in"});
44 next();
45 },
46
47 // Prevent direct access to AJAX results
48 ajax: function(req, res, next) {
49 if (!req.xhr)
50 return res.json({errmsg: "Unauthorized access"});
51 next();
52 },
53
54 // Check for errors before callback (continue page loading). TODO: better name.
55 checkRequest: function(res, err, out, msg, cb) {
56 if (!!err)
57 return res.json({errmsg: err.errmsg || err.toString()});
58 if (!out
59 || (Array.isArray(out) && out.length == 0)
60 || (typeof out === "object" && Object.keys(out).length == 0))
61 {
62 return res.json({errmsg: msg});
63 }
64 cb();
65 },
66 }