const {expressjwt: expressJWT} = require('express-jwt');

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

const getToken = function (req) {
	if (req.headers.authorization && req.headers.authorization.split(' ')[0] == 'Bearer') {
		return req.headers.authorization.split(' ')[1];
	}
	return null;
}

const onExpired = async function (req, err) {
	// If it's not too badly expired, let it through
	// and hope that a new token will be issued soon.
	const elapsed = new Date() - err.inner.expiredAt;
	// TODO: Add proper logging
	// console.log("Expiry details (elapsed, gracePeriod)", elapsed, cfg.gracePeriod*1000);
	if (elapsed < cfg.gracePeriod*1000) {
		// console.log("JWT within grace period");
		return;
	}

	throw err;
}

const options = {
	secret: cfg.secret,
	credentialsRequired: false,
	algorithms: ['HS256'],
	requestProperty: "user",
	getToken,
	onExpired
};

module.exports = expressJWT(options);
