Fix /whoami: remove fetch() for now
[vchess.git] / server / utils / access.js
CommitLineData
625022fd
BA
1var UserModel = require("../models/User");
2
fd08ab2c 3module.exports =
8d7e2786 4{
fd08ab2c
BA
5 // Prevent access to "users pages"
6 logged: function(req, res, next) {
625022fd
BA
7 const callback = () => {
8 if (!loggedIn)
98f48579 9 return res.json({errmsg: "Not logged in"});
625022fd
BA
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 res.clearCookie("id");
32 res.clearCookie("name");
33 loggedIn = false;
34 }
35 callback();
36 });
37 }
fd08ab2c 38 },
8d7e2786 39
fd08ab2c
BA
40 // Prevent access to "anonymous pages"
41 unlogged: function(req, res, next) {
625022fd
BA
42 // Just a quick heuristic, which should be enough
43 const loggedIn = !!req.cookies.token;
44 if (loggedIn)
98f48579 45 return res.json({errmsg: "Already logged in"});
fd08ab2c
BA
46 next();
47 },
8d7e2786 48
fd08ab2c
BA
49 // Prevent direct access to AJAX results
50 ajax: function(req, res, next) {
317b8a56 51 if (!req.xhr)
fd08ab2c
BA
52 return res.json({errmsg: "Unauthorized access"});
53 next();
54 },
8d7e2786 55
fd08ab2c
BA
56 // Check for errors before callback (continue page loading). TODO: better name.
57 checkRequest: function(res, err, out, msg, cb) {
58 if (!!err)
59 return res.json({errmsg: err.errmsg || err.toString()});
60 if (!out
61 || (Array.isArray(out) && out.length == 0)
62 || (typeof out === "object" && Object.keys(out).length == 0))
63 {
64 return res.json({errmsg: msg});
65 }
66 cb();
67 },
8d7e2786 68}