Files
dougal-software/lib/www/server/api/middleware/auth/authentify.js
D. Berge a3bfb73937 Add authentication middleware.
The user is authenticated by one of the following
methods, in order of priority:

* The presence of a valid JWT.
* Its IP.
* Its hostname.

In the case of the latter two methods, if authentication
is successful a JWT valid for 15 minutes will be generated
and passed back to the user in a cookie.
2020-10-11 13:11:43 +02:00

62 lines
1.2 KiB
JavaScript

const dns = require('dns');
const { Netmask } = require('netmask');
const cfg = require('../../../lib/config');
const jwt = require('../../../lib/jwt');
async function authorisedIP (req, res) {
const validIPs = cfg.global.login.ip;
for (const key in validIPs) {
const block = new Netmask(key);
if (block.contains(req.ip)) {
const payload = Object.assign({
ip: req.ip,
autologin: true
}, validIPs[key]);
jwt.issue(payload, req, res);
}
}
return Promise.resolve(true);
}
async function authorisedHost (req, res) {
const validHosts = cfg.global.login.host
for (const key in validHosts) {
const ip = await dns.promises.resolve(key);
if (ip == req.ip) {
const payload = Object.assign({
ip: req.ip,
host: key,
autologin: true
});
jwt.issue(payload, req, res);
}
}
return true;
}
async function auth (req, res, next) {
// Check for a valid JWT (already decoded by a previous
// middleware).
if (req.user) {
next();
return;
}
// Check if the IP is known to us
if (await authorisedIP(req, res)) {
next();
return;
}
// Check if the hostname is known to us
if (await authorisedHost(req, res)) {
next();
return;
}
next({status: 401, message: "Not authorised"});
}
module.exports = auth;