Skip to content

Commit

Permalink
Implemented reusable UniFi sessions. Fixed UniFi login rate-limit tri…
Browse files Browse the repository at this point in the history
…gger. Implemented bulk voucher generation. Implemented revoke/delete voucher function. Added grayscale logo. Fixed issue where headers are send 2 times.
  • Loading branch information
glenndehaan committed Apr 4, 2024
1 parent 4404fab commit ddc512b
Show file tree
Hide file tree
Showing 4 changed files with 158 additions and 62 deletions.
139 changes: 90 additions & 49 deletions modules/unifi.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,53 @@ const config = {
}
};

/**
* Controller session
*/
let controller = null;

/**
* Start a UniFi controller reusable session
*
* @return {Promise<unknown>}
*/
const startSession = () => {
return new Promise((resolve, reject) => {
// Check if we have a current session already
if(controller !== null) {
resolve();
return;
}

// Create new UniFi controller object
controller = new unifi.Controller({
host: config.unifi.ip,
port: config.unifi.port,
site: config.unifi.siteID,
sslverify: false
});

// Login to UniFi Controller
controller.login(config.unifi.username, config.unifi.password).then(() => {
log.info('[UniFi] Login successful!');
resolve();

// Clear session after about 1 hour (bearer token will expire after 2 hours)
setTimeout(async () => {
log.info('[UniFi] Controller session timeout reached! Cleanup controller...');
await controller.logout();
controller = null;
}, 3600000);
}).catch((e) => {
// Something went wrong so clear the current controller so a user can retry
controller = null;
log.error('[UniFi] Error while logging in!');
log.error(e);
reject('[UniFi] Error while logging in!');
});
});
}

/**
* Exports the UniFi voucher functions
*
Expand All @@ -32,72 +79,68 @@ module.exports = {
* Creates a new UniFi Voucher
*
* @param type
* @param amount
* @return {Promise<unknown>}
*/
create: (type) => {
create: (type, amount = 1) => {
return new Promise((resolve, reject) => {
/**
* Create new UniFi controller object
*
* @type {Controller}
*/
const controller = new unifi.Controller({
host: config.unifi.ip,
port: config.unifi.port,
site: config.unifi.siteID,
sslverify: false
});

/**
* Login and create a voucher
*/
controller.login(config.unifi.username, config.unifi.password).then(() => {
controller.createVouchers(type.expiration, 1, parseInt(type.usage) === 1 ? 1 : 0, null, typeof type.upload !== "undefined" ? type.upload : null, typeof type.download !== "undefined" ? type.download : null, typeof type.megabytes !== "undefined" ? type.megabytes : null).then((voucher_data) => {
controller.getVouchers(voucher_data[0].create_time).then((voucher_data_complete) => {
const voucher = `${[voucher_data_complete[0].code.slice(0, 5), '-', voucher_data_complete[0].code.slice(5)].join('')}`;
log.info(`[UniFi] Created voucher with code: ${voucher}`);
resolve(voucher);
}).catch((e) => {
log.error('[UniFi] Error while getting voucher!');
log.error(e);
reject('[UniFi] Error while getting voucher!');
});
startSession().then(() => {
controller.createVouchers(type.expiration, amount, parseInt(type.usage) === 1 ? 1 : 0, null, typeof type.upload !== "undefined" ? type.upload : null, typeof type.download !== "undefined" ? type.download : null, typeof type.megabytes !== "undefined" ? type.megabytes : null).then((voucher_data) => {
if(amount > 1) {
log.info(`[UniFi] Created ${amount} vouchers`);
resolve(true);
} else {
controller.getVouchers(voucher_data[0].create_time).then((voucher_data_complete) => {
const voucher = `${[voucher_data_complete[0].code.slice(0, 5), '-', voucher_data_complete[0].code.slice(5)].join('')}`;
log.info(`[UniFi] Created voucher with code: ${voucher}`);
resolve(voucher);
}).catch((e) => {
log.error('[UniFi] Error while getting voucher!');
log.error(e);
reject('[UniFi] Error while getting voucher!');
});
}
}).catch((e) => {
log.error('[UniFi] Error while creating voucher!');
log.error(e);
reject('[UniFi] Error while creating voucher!');
});
}).catch((e) => {
log.error('[UniFi] Error while logging in!');
log.error(e);
reject('[UniFi] Error while logging in!');
reject(e);
});
});
},

/**
* Returns a list with all UniFi Vouchers
* Removes a UniFi Voucher
*
* @param id
* @return {Promise<unknown>}
*/
list: () => {
remove: (id) => {
return new Promise((resolve, reject) => {
/**
* Create new UniFi controller object
*
* @type {Controller}
*/
const controller = new unifi.Controller({
host: config.unifi.ip,
port: config.unifi.port,
site: config.unifi.siteID,
sslverify: false
startSession().then(() => {
controller.revokeVoucher(id).then(() => {
resolve(true);
}).catch((e) => {
log.error('[UniFi] Error while removing voucher!');
log.error(e);
reject('[UniFi] Error while removing voucher!');
});
}).catch((e) => {
reject(e);
});
});
},

/**
* Login and get vouchers
*/
controller.login(config.unifi.username, config.unifi.password).then(() => {
/**
* Returns a list with all UniFi Vouchers
*
* @return {Promise<unknown>}
*/
list: () => {
return new Promise((resolve, reject) => {
startSession().then(() => {
controller.getVouchers().then((vouchers) => {
log.info(`[UniFi] Found ${vouchers.length} voucher(s)`);
resolve(vouchers);
Expand All @@ -107,9 +150,7 @@ module.exports = {
reject('[UniFi] Error while getting vouchers!');
});
}).catch((e) => {
log.error('[UniFi] Error while logging in!');
log.error(e);
reject('[UniFi] Error while logging in!');
reject(e);
});
});
}
Expand Down
Binary file added public/images/logo_grayscale.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 36 additions & 12 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,26 +189,50 @@ if(webService) {
}

// Create voucher code
const voucherCode = await unifi.create(types(req.body['voucher-type'], true)).catch((e) => {
const voucherCode = await unifi.create(types(req.body['voucher-type'], true), parseInt(req.body['voucher-amount'])).catch((e) => {
res.cookie('flashMessage', JSON.stringify({type: 'error', message: e}), {httpOnly: true, expires: new Date(Date.now() + 24 * 60 * 60 * 1000)}).redirect(302, `${req.headers['x-ingress-path'] ? req.headers['x-ingress-path'] : ''}/vouchers`);
});

log.info('[Cache] Requesting UniFi Vouchers...');
if(voucherCode) {
log.info('[Cache] Requesting UniFi Vouchers...');

const vouchers = await unifi.list().catch((e) => {
log.error('[Cache] Error requesting vouchers!');
log.error(e);
res.cookie('flashMessage', JSON.stringify({type: 'error', message: e}), {httpOnly: true, expires: new Date(Date.now() + 24 * 60 * 60 * 1000)}).redirect(302, `${req.headers['x-ingress-path'] ? req.headers['x-ingress-path'] : ''}/vouchers`);
});

const vouchers = await unifi.list().catch((e) => {
log.error('[Cache] Error requesting vouchers!');
log.error(e);
if(vouchers) {
cache.vouchers = vouchers;
cache.updated = new Date().getTime();
log.info(`[Cache] Saved ${vouchers.length} voucher(s)`);

res.cookie('flashMessage', JSON.stringify({type: 'info', message: parseInt(req.body['voucher-amount']) > 1 ? `${req.body['voucher-amount']} Vouchers Created!` : `Voucher Created: ${voucherCode}`}), {httpOnly: true, expires: new Date(Date.now() + 24 * 60 * 60 * 1000)}).redirect(302, `${req.headers['x-ingress-path'] ? req.headers['x-ingress-path'] : ''}/vouchers`);
}
}
});
app.get('/voucher/:id/remove', [authorization.web], async (req, res) => {
// Revoke voucher code
const response = await unifi.remove(req.params.id).catch((e) => {
res.cookie('flashMessage', JSON.stringify({type: 'error', message: e}), {httpOnly: true, expires: new Date(Date.now() + 24 * 60 * 60 * 1000)}).redirect(302, `${req.headers['x-ingress-path'] ? req.headers['x-ingress-path'] : ''}/vouchers`);
});

if(vouchers) {
cache.vouchers = vouchers;
cache.updated = new Date().getTime();
log.info(`[Cache] Saved ${vouchers.length} voucher(s)`);
}
if(response) {
log.info('[Cache] Requesting UniFi Vouchers...');

if(vouchers && voucherCode) {
res.cookie('flashMessage', JSON.stringify({type: 'info', message: `Voucher Created: ${voucherCode}`}), {httpOnly: true, expires: new Date(Date.now() + 24 * 60 * 60 * 1000)}).redirect(302, `${req.headers['x-ingress-path'] ? req.headers['x-ingress-path'] : ''}/vouchers`);
const vouchers = await unifi.list().catch((e) => {
log.error('[Cache] Error requesting vouchers!');
log.error(e);
res.cookie('flashMessage', JSON.stringify({type: 'error', message: e}), {httpOnly: true, expires: new Date(Date.now() + 24 * 60 * 60 * 1000)}).redirect(302, `${req.headers['x-ingress-path'] ? req.headers['x-ingress-path'] : ''}/vouchers`);
});

if(vouchers) {
cache.vouchers = vouchers;
cache.updated = new Date().getTime();
log.info(`[Cache] Saved ${vouchers.length} voucher(s)`);

res.cookie('flashMessage', JSON.stringify({type: 'info', message: `Voucher Removed!`}), {httpOnly: true, expires: new Date(Date.now() + 24 * 60 * 60 * 1000)}).redirect(302, `${req.headers['x-ingress-path'] ? req.headers['x-ingress-path'] : ''}/vouchers`);
}
}
});
app.get('/vouchers', [authorization.web], async (req, res) => {
Expand Down
33 changes: 32 additions & 1 deletion template/voucher.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,13 @@
<path fill-rule="evenodd" d="M15.75 4.5a3 3 0 1 1 .825 2.066l-8.421 4.679a3.002 3.002 0 0 1 0 1.51l8.421 4.679a3 3 0 1 1-.729 1.31l-8.421-4.678a3 3 0 1 1 0-4.132l8.421-4.679a3 3 0 0 1-.096-.755Z" clip-rule="evenodd" />
</svg>
</button>
<a href="<%= baseUrl %>/voucher/<%= voucher._id %>/remove" type="button" class="remove-button relative rounded-full p-1 text-red-500 dark:text-red-400 hover:text-black dark:hover:text-white">
<span class="absolute -inset-1.5"></span>
<span class="sr-only">Remove Voucher Code</span>
<svg class="h-5 w-5" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M16.5 4.478v.227a48.816 48.816 0 0 1 3.878.512.75.75 0 1 1-.256 1.478l-.209-.035-1.005 13.07a3 3 0 0 1-2.991 2.77H8.084a3 3 0 0 1-2.991-2.77L4.087 6.66l-.209.035a.75.75 0 0 1-.256-1.478A48.567 48.567 0 0 1 7.5 4.705v-.227c0-1.564 1.213-2.9 2.816-2.951a52.662 52.662 0 0 1 3.369 0c1.603.051 2.815 1.387 2.815 2.951Zm-6.136-1.452a51.196 51.196 0 0 1 3.273 0C14.39 3.05 15 3.684 15 4.478v.113a49.488 49.488 0 0 0-6 0v-.113c0-.794.609-1.428 1.364-1.452Zm-.355 5.945a.75.75 0 1 0-1.5.058l.347 9a.75.75 0 1 0 1.499-.058l-.346-9Zm5.48.058a.75.75 0 1 0-1.498-.058l-.347 9a.75.75 0 0 0 1.5.058l.345-9Z" clip-rule="evenodd" />
</svg>
</a>
</li>
<% }); %>
</ul>
Expand Down Expand Up @@ -219,6 +226,12 @@
</select>
</div>
</div>
<div>
<label for="voucher-amount" class="block text-sm font-medium leading-6 text-gray-900 dark:text-white">Amount</label>
<div class="mt-2">
<input type="number" min="1" step="1" value="1" id="voucher-amount" name="voucher-amount" required class="mt-2 block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 dark:text-white dark:bg-white/5 ring-1 ring-inset ring-gray-300 dark:ring-white/10 focus:ring-2 focus:ring-sky-600 sm:text-sm sm:leading-6">
</div>
</div>
</div>
</div>
</div>
Expand All @@ -245,6 +258,17 @@
<p class="w-1/2 text-center text-white">This may take a few seconds, please don't close this page.</p>
</div>

<div id="spinner-remove" style="display: none;" class="fixed top-0 left-0 right-0 bottom-0 w-full h-screen z-50 overflow-hidden bg-gray-900 opacity-90 flex flex-col items-center justify-center">
<div class="mb-4">
<svg class="w-14 h-14 text-gray-200 animate-spin dark:text-gray-600 fill-cyan-400" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
<path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
</svg>
</div>
<h2 class="text-center text-white text-xl font-semibold">Removing Voucher...</h2>
<p class="w-1/2 text-center text-white">This may take a few seconds, please don't close this page.</p>
</div>

<div id="spinner-list" style="display: none;" class="fixed top-0 left-0 right-0 bottom-0 w-full h-screen z-50 overflow-hidden bg-gray-900 opacity-90 flex flex-col items-center justify-center">
<div class="mb-4">
<svg class="w-14 h-14 text-gray-200 animate-spin dark:text-gray-600 fill-cyan-400" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
Expand Down Expand Up @@ -284,7 +308,9 @@
const cancelButton = document.querySelector('#cancel');
const reloadButton = document.querySelector('#reload-vouchers');
const shareButtons = document.querySelectorAll('.share-button');
const removeButtons = document.querySelectorAll('.remove-button');
const spinnerCreate = document.querySelector("#spinner-create");
const spinnerRemove = document.querySelector("#spinner-remove");
const spinnerList = document.querySelector("#spinner-list");
const copyNotification = document.querySelector("#copy-notification");
Expand Down Expand Up @@ -318,7 +344,12 @@
console.error(error.message);
}
});
})
});
removeButtons.forEach((el) => {
el.addEventListener('click', async () => {
spinnerRemove.style.display = '';
});
});
</script>
</body>
</html>

0 comments on commit ddc512b

Please sign in to comment.