const crypto = require('crypto');
const cfg = require('../../../lib/config');
const jwt = require('../../../lib/jwt');

async function login (req, res, next) {
	if (req.body) {
		const {user, password} = req.body;
		if (user && password) {
			const hash = crypto
				.pbkdf2Sync(password, 'Dougal'+user, 10712, 48, 'sha512')
				.toString('base64');
			for (const credentials of cfg._("global.users.login.user") || []) {
				if (credentials.name == user && credentials.hash == hash) {
					const payload = Object.assign({}, credentials);
					delete payload.hash;
					jwt.issue(payload, req, res);
					res.status(204).send();
					next();
					return;
				}
			}
			next({status: 401, message: "Unauthorised"});
		}
	}
	next({status: 400, message: "Bad request"});
}

module.exports = login;
