Skip to content

Commit

Permalink
Moved application startup logs to dedicated info.js module. Lowered l…
Browse files Browse the repository at this point in the history
…og output from unifi.js. Created tag.ejs partial. Implemented dedicated application status page. Updated voucher.ejs to implement status link. Lowered log output from cache.js. General cleanup of server.js. Implemented 501 Not Implemented responses when features are not enabled or configured properly
  • Loading branch information
glenndehaan committed Sep 4, 2024
1 parent fefdab9 commit 86ad445
Show file tree
Hide file tree
Showing 8 changed files with 562 additions and 81 deletions.
110 changes: 110 additions & 0 deletions modules/info.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* Import base packages
*/
const fs = require('fs');

/**
* Import own modules
*/
const log = require('./log');
const config = require('./config');
const logo = require('../utils/logo');
const types = require('../utils/types');
const time = require('../utils/time');

/**
* Define global variables
*/
const voucherTypes = types(config('voucher_types') || process.env.VOUCHER_TYPES || '480,1,,,;');
const voucherCustom = config('voucher_custom') !== null ? config('voucher_custom') : process.env.VOUCHER_CUSTOM ? process.env.VOUCHER_CUSTOM !== 'false' : true;
const webService = process.env.SERVICE_WEB ? process.env.SERVICE_WEB !== 'false' : true;
const apiService = config('service_api') || (process.env.SERVICE_API === 'true') || false;
const authDisabled = (process.env.AUTH_DISABLE === 'true') || false;
const printerType = config('printer_type') || process.env.PRINTER_TYPE || '';
const printerIp = config('printer_ip') || process.env.PRINTER_IP || '192.168.1.1';
const smtpFrom = config('smtp_from') || process.env.SMTP_FROM || '';
const smtpHost = config('smtp_host') || process.env.SMTP_HOST || '';
const smtpPort = config('smtp_port') || process.env.SMTP_PORT || 25;
const oidcIssuerBaseUrl = process.env.AUTH_OIDC_ISSUER_BASE_URL || '';
const oidcAppBaseUrl = process.env.AUTH_OIDC_APP_BASE_URL || '';
const oidcClientId = process.env.AUTH_OIDC_CLIENT_ID || '';
const oidcClientType = process.env.AUTH_OIDC_CLIENT_TYPE || 'public';
const oidcClientSecret = process.env.AUTH_OIDC_CLIENT_SECRET || '';

/**
* Output info to console
*/
module.exports = () => {
/**
* Output logo
*/
logo();

/**
* Output build version
*/
if(fs.existsSync('/etc/unifi_voucher_site_build')) {
log.info(`[Version] ${fs.readFileSync('/etc/unifi_voucher_site_build', 'utf-8')}`);
} else {
log.info(`[Version] **DEVELOPMENT**`);
}

/**
* Log external config
*/
if (fs.existsSync('/data/options.json')) {
log.info('[Options] Found at /data/options.json');
}
if (fs.existsSync(`${process.cwd()}/.options.json`)) {
log.info(`[Options] Found at ${process.cwd()}/.options.json`);
}

/**
* Log service status
*/
log.info(`[Service][Web] ${webService ? 'Enabled!' : 'Disabled!'}`);
log.info(`[Service][Api] ${apiService ? 'Enabled!' : 'Disabled!'}`);

/**
* Log voucher types
*/
log.info('[Voucher] Loaded the following types:');
voucherTypes.forEach((type, key) => {
log.info(`[Voucher][Type][${key}] ${time(type.expiration)}, ${type.usage === '1' ? 'single-use' : 'multi-use'}${typeof type.upload === "undefined" && typeof type.download === "undefined" && typeof type.megabytes === "undefined" ? ', no limits' : `${typeof type.upload !== "undefined" ? `, upload bandwidth limit: ${type.upload} kb/s` : ''}${typeof type.download !== "undefined" ? `, download bandwidth limit: ${type.download} kb/s` : ''}${typeof type.megabytes !== "undefined" ? `, quota limit: ${type.megabytes} mb` : ''}`}`);
});
log.info(`[Voucher][Custom] ${voucherCustom ? 'Enabled!' : 'Disabled!'}`);

/**
* Log auth status
*/
log.info(`[Auth] ${authDisabled ? 'Disabled!' : `Enabled! Type: ${(oidcIssuerBaseUrl !== '' || oidcAppBaseUrl !== '' || oidcClientId !== '') ? 'OIDC' : 'Internal'}`}`);

/**
* Verify OIDC configuration
*/
if(oidcIssuerBaseUrl !== '' && (oidcAppBaseUrl === '' || oidcClientId === '')) {
log.error(`[OIDC] Incorrect Configuration Detected!. Verify 'AUTH_OIDC_ISSUER_BASE_URL', 'AUTH_OIDC_APP_BASE_URL' and 'AUTH_OIDC_CLIENT_ID' are set! Authentication will be unstable or disabled until issue is resolved!`);
}
if(oidcIssuerBaseUrl !== '' && oidcClientType === 'confidential' && oidcClientSecret === '') {
log.error(`[OIDC] Incorrect Configuration Detected!. Verify 'AUTH_OIDC_CLIENT_SECRET' is set! Authentication will be unstable or disabled until issue is resolved!`);
}

/**
* Log printer status
*/
log.info(`[Printer] ${printerType !== '' ? `Enabled! Type: ${printerType}${printerType === 'escpos' ? `, IP: ${printerIp}` : ''}` : 'Disabled!'}`);

/**
* Log email status
*/
if(smtpFrom !== '' && smtpHost !== '' && smtpPort !== '') {
log.info(`[Email] Enabled! SMTP Server: ${smtpHost}:${smtpPort}`);
} else {
log.info(`[Email] Disabled!`);
}

/**
* Log controller
*/
log.info(`[UniFi] Using Controller on: ${config('unifi_ip') || process.env.UNIFI_IP || '192.168.1.1'}:${config('unifi_port') || process.env.UNIFI_PORT || 443} (Site ID: ${config('unifi_site_id') || process.env.UNIFI_SITE_ID || 'default'})`);
};
2 changes: 1 addition & 1 deletion modules/unifi.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const startSession = () => {

// Login to UniFi Controller
controller.login(settings.username, settings.password).then(() => {
log.info('[UniFi] Login successful!');
log.debug('[UniFi] Login successful!');
resolve();
}).catch((e) => {
// Something went wrong so clear the current controller so a user can retry
Expand Down
106 changes: 28 additions & 78 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/**
* Import base packages
*/
const fs = require('fs');
const os = require('os');
const express = require('express');
const multer = require('multer');
Expand All @@ -14,10 +13,7 @@ const config = require('./modules/config');
const log = require('./modules/log');
const cache = require('./modules/cache');
const jwt = require('./modules/jwt');
const logo = require('./utils/logo');
const types = require('./utils/types');
const time = require('./utils/time');
const bytes = require('./utils/bytes');
const info = require('./modules/info');
const unifi = require('./modules/unifi');
const print = require('./modules/print');
const mail = require('./modules/mail');
Expand All @@ -33,6 +29,10 @@ const flashMessage = require('./middlewares/flashMessage');
* Import own utils
*/
const {updateCache} = require('./utils/cache');
const types = require('./utils/types');
const time = require('./utils/time');
const bytes = require('./utils/bytes');
const status = require('./utils/status');

/**
* Setup Express app
Expand All @@ -48,83 +48,17 @@ const webService = process.env.SERVICE_WEB ? process.env.SERVICE_WEB !== 'false'
const apiService = config('service_api') || (process.env.SERVICE_API === 'true') || false;
const authDisabled = (process.env.AUTH_DISABLE === 'true') || false;
const printerType = config('printer_type') || process.env.PRINTER_TYPE || '';
const printerIp = config('printer_ip') || process.env.PRINTER_IP || '192.168.1.1';
const smtpFrom = config('smtp_from') || process.env.SMTP_FROM || '';
const smtpHost = config('smtp_host') || process.env.SMTP_HOST || '';
const smtpPort = config('smtp_port') || process.env.SMTP_PORT || 25;
const oidcIssuerBaseUrl = process.env.AUTH_OIDC_ISSUER_BASE_URL || '';
const oidcAppBaseUrl = process.env.AUTH_OIDC_APP_BASE_URL || '';
const oidcClientId = process.env.AUTH_OIDC_CLIENT_ID || '';
const oidcClientType = process.env.AUTH_OIDC_CLIENT_TYPE || 'public';
const oidcClientSecret = process.env.AUTH_OIDC_CLIENT_SECRET || '';

/**
* Output logo
*/
logo();

/**
* Output build version
*/
if(fs.existsSync('/etc/unifi_voucher_site_build')) {
log.info(`[Version] ${fs.readFileSync('/etc/unifi_voucher_site_build', 'utf-8')}`);
} else {
log.info(`[Version] **DEVELOPMENT**`);
}

/**
* Log external config
*/
if (fs.existsSync('/data/options.json')) {
log.info('[Options] Found at /data/options.json');
}
if (fs.existsSync(`${__dirname}/.options.json`)) {
log.info(`[Options] Found at ${__dirname}/.options.json`);
}

/**
* Log service status
*/
log.info(`[Service][Web] ${webService ? 'Enabled!' : 'Disabled!'}`);
log.info(`[Service][Api] ${apiService ? 'Enabled!' : 'Disabled!'}`);

/**
* Log voucher types
*/
log.info('[Voucher] Loaded the following types:');
voucherTypes.forEach((type, key) => {
log.info(`[Voucher][Type][${key}] ${time(type.expiration)}, ${type.usage === '1' ? 'single-use' : 'multi-use'}${typeof type.upload === "undefined" && typeof type.download === "undefined" && typeof type.megabytes === "undefined" ? ', no limits' : `${typeof type.upload !== "undefined" ? `, upload bandwidth limit: ${type.upload} kb/s` : ''}${typeof type.download !== "undefined" ? `, download bandwidth limit: ${type.download} kb/s` : ''}${typeof type.megabytes !== "undefined" ? `, quota limit: ${type.megabytes} mb` : ''}`}`);
});
log.info(`[Voucher][Custom] ${voucherCustom ? 'Enabled!' : 'Disabled!'}`);

/**
* Log auth status
*/
log.info(`[Auth] ${authDisabled ? 'Disabled!' : `Enabled! Type: ${(oidcIssuerBaseUrl !== '' || oidcAppBaseUrl !== '' || oidcClientId !== '') ? 'OIDC' : 'Internal'}`}`);

/**
* Verify OIDC configuration
*/
if(oidcIssuerBaseUrl !== '' && (oidcAppBaseUrl === '' || oidcClientId === '')) {
log.error(`[OIDC] Incorrect Configuration Detected!. Verify 'AUTH_OIDC_ISSUER_BASE_URL', 'AUTH_OIDC_APP_BASE_URL' and 'AUTH_OIDC_CLIENT_ID' are set! Authentication will be unstable or disabled until issue is resolved!`);
}
if(oidcIssuerBaseUrl !== '' && oidcClientType === 'confidential' && oidcClientSecret === '') {
log.error(`[OIDC] Incorrect Configuration Detected!. Verify 'AUTH_OIDC_CLIENT_SECRET' is set! Authentication will be unstable or disabled until issue is resolved!`);
}

/**
* Log printer status
* Output info
*/
log.info(`[Printer] ${printerType !== '' ? `Enabled! Type: ${printerType}${printerType === 'escpos' ? `, IP: ${printerIp}` : ''}` : 'Disabled!'}`);

/**
* Log email status
*/
if(smtpFrom !== '' && smtpHost !== '' && smtpPort !== '') {
log.info(`[Email] Enabled! SMTP Server: ${smtpHost}:${smtpPort}`);
} else {
log.info(`[Email] Disabled!`);
}
info();

/**
* Initialize JWT
Expand All @@ -133,11 +67,6 @@ if(!authDisabled && (oidcIssuerBaseUrl === '' && oidcAppBaseUrl === '' && oidcCl
jwt.init();
}

/**
* Log controller
*/
log.info(`[UniFi] Using Controller on: ${config('unifi_ip') || process.env.UNIFI_IP || '192.168.1.1'}:${config('unifi_port') || process.env.UNIFI_PORT || 443} (Site ID: ${config('unifi_site_id') || process.env.UNIFI_SITE_ID || 'default'})`);

/**
* Trust proxy
*/
Expand Down Expand Up @@ -305,6 +234,11 @@ if(webService) {
}
});
app.get('/voucher/:id/print', [authorization.web], async (req, res) => {
if(printerType === '') {
res.status(501).send();
return;
}

const voucher = cache.vouchers.find((e) => {
return e._id === req.params.id;
});
Expand Down Expand Up @@ -337,6 +271,11 @@ if(webService) {
}
});
app.get('/voucher/:id/email', [authorization.web], async (req, res) => {
if(smtpFrom === '' || smtpHost === '' || smtpPort === '') {
res.status(501).send();
return;
}

const voucher = cache.vouchers.find((e) => {
return e._id === req.params.id;
});
Expand All @@ -357,6 +296,11 @@ if(webService) {
}
});
app.post('/voucher/:id/email', [authorization.web], async (req, res) => {
if(smtpFrom === '' || smtpHost === '' || smtpPort === '') {
res.status(501).send();
return;
}

if (typeof req.body === "undefined") {
res.status(400).send();
return;
Expand Down Expand Up @@ -445,6 +389,12 @@ if(webService) {
});
}
});
app.get('/status', [authorization.web], (req, res) => {
res.render('status', {
baseUrl: req.headers['x-ingress-path'] ? req.headers['x-ingress-path'] : '',
status: status()
});
});
}

if(apiService) {
Expand Down
17 changes: 17 additions & 0 deletions template/partials/tag.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<% if(status.state === 'red') { %>
<div class="inline-flex w-fit items-center whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ring-inset bg-red-50 text-red-800 ring-red-600/20 dark:text-red-400 dark:bg-red-400/10 dark:ring-red-400/20">
<%= status.text %>
</div>
<% } %>

<% if(status.state === 'yellow') { %>
<div class="inline-flex w-fit items-center whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ring-inset bg-yellow-50 text-yellow-800 ring-yellow-600/20 dark:text-yellow-400 dark:bg-yellow-400/10 dark:ring-yellow-400/20">
<%= status.text %>
</div>
<% } %>

<% if(status.state === 'green') { %>
<div class="inline-flex w-fit items-center whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ring-inset bg-green-50 text-green-700 ring-green-600/20 dark:text-green-400 dark:bg-green-400/10 dark:ring-green-400/20">
<%= status.text %>
</div>
<% } %>
Loading

0 comments on commit 86ad445

Please sign in to comment.