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

async function login (req, res, next) {
	if (req.body) {
		const {user, password} = req.body;
		const payload = await jwt.checkValidCredentials({user, password});
		if (payload) {
			const token = jwt.issue(payload, req, res);
			res.set("X-JWT", token);
			res.status(200).send({token});
			next();
			return;
		} else {
			next({status: 401, message: "Unauthorised"});
		}
	} else {
		next({status: 400, message: "Bad request"});
	}
}

module.exports = login;
