| 1 | const _ = require("underscore"); |
| 2 | const UserModel = require("../models/user"); |
| 3 | |
| 4 | let Access = |
| 5 | { |
| 6 | getUser: function(req, res, callback) |
| 7 | { |
| 8 | if (!res.locals.loggedIn) |
| 9 | return callback({errmsg: "Not logged in!"}, undefined); |
| 10 | UserModel.getBySessionToken(req.cookies.token, function(err, user) { |
| 11 | if (!user) |
| 12 | return callback({errmsg: "Not logged in!"}, undefined); |
| 13 | return callback(null, user); |
| 14 | }); |
| 15 | }, |
| 16 | |
| 17 | // Before loading sensible content, check + save credentials |
| 18 | logged: function(req, res, next) |
| 19 | { |
| 20 | Access.getUser(req, res, (err,user) => { |
| 21 | if (!!err) |
| 22 | return res.json(err); |
| 23 | req.user = user; |
| 24 | next(); |
| 25 | }); |
| 26 | }, |
| 27 | |
| 28 | // Prevent access to "anonymous pages" |
| 29 | unlogged: function(req, res, next) |
| 30 | { |
| 31 | if (!!req.user) |
| 32 | return res.json({errmsg: "Already logged in!"}); |
| 33 | next(); |
| 34 | }, |
| 35 | |
| 36 | // Prevent direct access to AJAX results |
| 37 | ajax: function(req, res, next) |
| 38 | { |
| 39 | if (!req.xhr) |
| 40 | return res.json({errmsg: "Unauthorized access"}); |
| 41 | next(); |
| 42 | }, |
| 43 | |
| 44 | // Check for errors before callback (continue page loading). TODO: better name. |
| 45 | checkRequest: function(res, err, out, msg, cb) |
| 46 | { |
| 47 | if (!!err) |
| 48 | return res.json(err); |
| 49 | if (!out || _.isEmpty(out)) |
| 50 | return res.json({errmsg: msg}); |
| 51 | cb(); |
| 52 | }, |
| 53 | }; |
| 54 | |
| 55 | module.exports = Access; |