Refactor from Promises to async/await

This commit is contained in:
Jamie Curnow
2025-09-10 23:59:00 +10:00
parent a7d4fd55d9
commit 538d28d32d
5 changed files with 1128 additions and 1440 deletions

View File

@@ -21,11 +21,9 @@ const internalAccessList = {
* @param {Object} data * @param {Object} data
* @returns {Promise} * @returns {Promise}
*/ */
create: (access, data) => { create: async (access, data) => {
return access await access.can("access_lists:create", data);
.can("access_lists:create", data) const row = await accessListModel
.then((/*access_data*/) => {
return accessListModel
.query() .query()
.insertAndFetch({ .insertAndFetch({
name: data.name, name: data.name,
@@ -34,13 +32,11 @@ const internalAccessList = {
owner_user_id: access.token.getUserId(1), owner_user_id: access.token.getUserId(1),
}) })
.then(utils.omitRow(omissions())); .then(utils.omitRow(omissions()));
})
.then((row) => {
data.id = row.id; data.id = row.id;
const promises = []; const promises = [];
// Items
// Now add the items
data.items.map((item) => { data.items.map((item) => {
promises.push( promises.push(
accessListAuthModel.query().insert({ accessListAuthModel.query().insert({
@@ -52,9 +48,8 @@ const internalAccessList = {
return true; return true;
}); });
// Now add the clients // Clients
if (typeof data.clients !== "undefined" && data.clients) { data.clients?.map((client) => {
data.clients.map((client) => {
promises.push( promises.push(
accessListClientModel.query().insert({ accessListClientModel.query().insert({
access_list_id: row.id, access_list_id: row.id,
@@ -64,45 +59,36 @@ const internalAccessList = {
); );
return true; return true;
}); });
}
return Promise.all(promises); await Promise.all(promises);
})
.then(() => {
// re-fetch with expansions // re-fetch with expansions
return internalAccessList.get( const freshRow = await internalAccessList.get(
access, access,
{ {
id: data.id, id: data.id,
expand: ["owner", "items", "clients", "proxy_hosts.access_list.[clients,items]"], expand: ["owner", "items", "clients", "proxy_hosts.access_list.[clients,items]"],
}, },
true /* <- skip masking */, true // skip masking
); );
})
.then((row) => {
// Audit log
data.meta = _.assign({}, data.meta || {}, row.meta);
return internalAccessList // Audit log
.build(row) data.meta = _.assign({}, data.meta || {}, freshRow.meta);
.then(() => { await internalAccessList.build(freshRow);
if (Number.parseInt(row.proxy_host_count, 10)) {
return internalNginx.bulkGenerateConfigs("proxy_host", row.proxy_hosts); if (Number.parseInt(freshRow.proxy_host_count, 10)) {
await internalNginx.bulkGenerateConfigs("proxy_host", freshRow.proxy_hosts);
} }
})
.then(() => {
// Add to audit log // Add to audit log
return internalAuditLog.add(access, { await internalAuditLog.add(access, {
action: "created", action: "created",
object_type: "access-list", object_type: "access-list",
object_id: row.id, object_id: freshRow.id,
meta: internalAccessList.maskItems(data), meta: internalAccessList.maskItems(data),
}); });
})
.then(() => { return internalAccessList.maskItems(freshRow);
return internalAccessList.maskItems(row);
});
});
}, },
/** /**
@@ -113,35 +99,29 @@ const internalAccessList = {
* @param {String} [data.items] * @param {String} [data.items]
* @return {Promise} * @return {Promise}
*/ */
update: (access, data) => { update: async (access, data) => {
return access await access.can("access_lists:update", data.id);
.can("access_lists:update", data.id) const row = await internalAccessList.get(access, { id: data.id });
.then((/*access_data*/) => {
return internalAccessList.get(access, { id: data.id });
})
.then((row) => {
if (row.id !== data.id) { if (row.id !== data.id) {
// Sanity check that something crazy hasn't happened // Sanity check that something crazy hasn't happened
throw new errs.InternalValidationError( throw new errs.InternalValidationError(
`Access List could not be updated, IDs do not match: ${row.id} !== ${data.id}`, `Access List could not be updated, IDs do not match: ${row.id} !== ${data.id}`,
); );
} }
})
.then(() => {
// patch name if specified // patch name if specified
if (typeof data.name !== "undefined" && data.name) { if (typeof data.name !== "undefined" && data.name) {
return accessListModel.query().where({ id: data.id }).patch({ await accessListModel.query().where({ id: data.id }).patch({
name: data.name, name: data.name,
satisfy_any: data.satisfy_any, satisfy_any: data.satisfy_any,
pass_auth: data.pass_auth, pass_auth: data.pass_auth,
}); });
} }
})
.then(() => {
// Check for items and add/update/remove them // Check for items and add/update/remove them
if (typeof data.items !== "undefined" && data.items) { if (typeof data.items !== "undefined" && data.items) {
const promises = []; const promises = [];
const items_to_keep = []; const itemsToKeep = [];
data.items.map((item) => { data.items.map((item) => {
if (item.password) { if (item.password) {
@@ -154,33 +134,30 @@ const internalAccessList = {
); );
} else { } else {
// This was supplied with an empty password, which means keep it but don't change the password // This was supplied with an empty password, which means keep it but don't change the password
items_to_keep.push(item.username); itemsToKeep.push(item.username);
} }
return true; return true;
}); });
const query = accessListAuthModel.query().delete().where("access_list_id", data.id); const query = accessListAuthModel.query().delete().where("access_list_id", data.id);
if (items_to_keep.length) { if (itemsToKeep.length) {
query.andWhere("username", "NOT IN", items_to_keep); query.andWhere("username", "NOT IN", itemsToKeep);
} }
return query.then(() => { await query;
// Add new items // Add new items
if (promises.length) { if (promises.length) {
return Promise.all(promises); await Promise.all(promises);
} }
});
} }
})
.then(() => {
// Check for clients and add/update/remove them // Check for clients and add/update/remove them
if (typeof data.clients !== "undefined" && data.clients) { if (typeof data.clients !== "undefined" && data.clients) {
const promises = []; const clientPromises = [];
data.clients.map((client) => { data.clients.map((client) => {
if (client.address) { if (client.address) {
promises.push( clientPromises.push(
accessListClientModel.query().insert({ accessListClientModel.query().insert({
access_list_id: data.id, access_list_id: data.id,
address: client.address, address: client.address,
@@ -192,48 +169,37 @@ const internalAccessList = {
}); });
const query = accessListClientModel.query().delete().where("access_list_id", data.id); const query = accessListClientModel.query().delete().where("access_list_id", data.id);
await query;
// Add new clitens
if (clientPromises.length) {
await Promise.all(clientPromises);
}
}
return query.then(() => {
// Add new items
if (promises.length) {
return Promise.all(promises);
}
});
}
})
.then(() => {
// Add to audit log // Add to audit log
return internalAuditLog.add(access, { await internalAuditLog.add(access, {
action: "updated", action: "updated",
object_type: "access-list", object_type: "access-list",
object_id: data.id, object_id: data.id,
meta: internalAccessList.maskItems(data), meta: internalAccessList.maskItems(data),
}); });
})
.then(() => {
// re-fetch with expansions // re-fetch with expansions
return internalAccessList.get( const freshRow = await internalAccessList.get(
access, access,
{ {
id: data.id, id: data.id,
expand: ["owner", "items", "clients", "proxy_hosts.[certificate,access_list.[clients,items]]"], expand: ["owner", "items", "clients", "proxy_hosts.[certificate,access_list.[clients,items]]"],
}, },
true /* <- skip masking */, true // skip masking
); );
})
.then((row) => { await internalAccessList.build(freshRow)
return internalAccessList
.build(row)
.then(() => {
if (Number.parseInt(row.proxy_host_count, 10)) { if (Number.parseInt(row.proxy_host_count, 10)) {
return internalNginx.bulkGenerateConfigs("proxy_host", row.proxy_hosts); await internalNginx.bulkGenerateConfigs("proxy_host", row.proxy_hosts);
} }
}) await internalNginx.reload();
.then(internalNginx.reload)
.then(() => {
return internalAccessList.maskItems(row); return internalAccessList.maskItems(row);
});
});
}, },
/** /**
@@ -242,15 +208,13 @@ const internalAccessList = {
* @param {Integer} data.id * @param {Integer} data.id
* @param {Array} [data.expand] * @param {Array} [data.expand]
* @param {Array} [data.omit] * @param {Array} [data.omit]
* @param {Boolean} [skip_masking] * @param {Boolean} [skipMasking]
* @return {Promise} * @return {Promise}
*/ */
get: (access, data, skip_masking) => { get: async (access, data, skipMasking) => {
const thisData = data || {}; const thisData = data || {};
const accessData = await access.can("access_lists:get", thisData.id)
return access
.can("access_lists:get", thisData.id)
.then((accessData) => {
const query = accessListModel const query = accessListModel
.query() .query()
.select("access_list.*", accessListModel.raw("COUNT(proxy_host.id) as proxy_host_count")) .select("access_list.*", accessListModel.raw("COUNT(proxy_host.id) as proxy_host_count"))
@@ -275,22 +239,19 @@ const internalAccessList = {
query.withGraphFetched(`[${thisData.expand.join(", ")}]`); query.withGraphFetched(`[${thisData.expand.join(", ")}]`);
} }
return query.then(utils.omitRow(omissions())); let row = await query.then(utils.omitRow(omissions()));
})
.then((row) => {
let thisRow = row;
if (!row || !row.id) { if (!row || !row.id) {
throw new errs.ItemNotFoundError(thisData.id); throw new errs.ItemNotFoundError(thisData.id);
} }
if (!skip_masking && typeof thisRow.items !== "undefined" && thisRow.items) { if (!skipMasking && typeof row.items !== "undefined" && row.items) {
thisRow = internalAccessList.maskItems(thisRow); row = internalAccessList.maskItems(row);
} }
// Custom omissions // Custom omissions
if (typeof data.omit !== "undefined" && data.omit !== null) { if (typeof data.omit !== "undefined" && data.omit !== null) {
thisRow = _.omit(thisRow, data.omit); row = _.omit(row, data.omit);
} }
return thisRow; return row;
});
}, },
/** /**
@@ -300,13 +261,13 @@ const internalAccessList = {
* @param {String} [data.reason] * @param {String} [data.reason]
* @returns {Promise} * @returns {Promise}
*/ */
delete: (access, data) => { delete: async (access, data) => {
return access await access.can("access_lists:delete", data.id);
.can("access_lists:delete", data.id) const row = await internalAccessList.get(access, {
.then(() => { id: data.id,
return internalAccessList.get(access, { id: data.id, expand: ["proxy_hosts", "items", "clients"] }); expand: ["proxy_hosts", "items", "clients"],
}) });
.then((row) => {
if (!row || !row.id) { if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id); throw new errs.ItemNotFoundError(data.id);
} }
@@ -317,58 +278,47 @@ const internalAccessList = {
// 4. audit log // 4. audit log
// 1. update row to be deleted // 1. update row to be deleted
return accessListModel await accessListModel
.query() .query()
.where("id", row.id) .where("id", row.id)
.patch({ .patch({
is_deleted: 1, is_deleted: 1,
}) });
.then(() => {
// 2. update any proxy hosts that were using it (ignoring permissions) // 2. update any proxy hosts that were using it (ignoring permissions)
if (row.proxy_hosts) { if (row.proxy_hosts) {
return proxyHostModel await proxyHostModel
.query() .query()
.where("access_list_id", "=", row.id) .where("access_list_id", "=", row.id)
.patch({ access_list_id: 0 }) .patch({ access_list_id: 0 });
.then(() => {
// 3. reconfigure those hosts, then reload nginx
// 3. reconfigure those hosts, then reload nginx
// set the access_list_id to zero for these items // set the access_list_id to zero for these items
row.proxy_hosts.map((_val, idx) => { row.proxy_hosts.map((_val, idx) => {
row.proxy_hosts[idx].access_list_id = 0; row.proxy_hosts[idx].access_list_id = 0;
return true; return true;
}); });
return internalNginx.bulkGenerateConfigs("proxy_host", row.proxy_hosts); await internalNginx.bulkGenerateConfigs("proxy_host", row.proxy_hosts);
})
.then(() => {
return internalNginx.reload();
});
} }
})
.then(() => {
// delete the htpasswd file
const htpasswd_file = internalAccessList.getFilename(row);
await internalNginx.reload();
// delete the htpasswd file
try { try {
fs.unlinkSync(htpasswd_file); fs.unlinkSync(internalAccessList.getFilename(row));
} catch (_err) { } catch (_err) {
// do nothing // do nothing
} }
})
.then(() => {
// 4. audit log // 4. audit log
return internalAuditLog.add(access, { await internalAuditLog.add(access, {
action: "deleted", action: "deleted",
object_type: "access-list", object_type: "access-list",
object_id: row.id, object_id: row.id,
meta: _.omit(internalAccessList.maskItems(row), ["is_deleted", "proxy_hosts"]), meta: _.omit(internalAccessList.maskItems(row), ["is_deleted", "proxy_hosts"]),
}); });
});
})
.then(() => {
return true; return true;
});
}, },
/** /**
@@ -376,13 +326,12 @@ const internalAccessList = {
* *
* @param {Access} access * @param {Access} access
* @param {Array} [expand] * @param {Array} [expand]
* @param {String} [search_query] * @param {String} [searchQuery]
* @returns {Promise} * @returns {Promise}
*/ */
getAll: (access, expand, search_query) => { getAll: async (access, expand, searchQuery) => {
return access const accessData = await access.can("access_lists:list");
.can("access_lists:list")
.then((access_data) => {
const query = accessListModel const query = accessListModel
.query() .query()
.select("access_list.*", accessListModel.raw("COUNT(proxy_host.id) as proxy_host_count")) .select("access_list.*", accessListModel.raw("COUNT(proxy_host.id) as proxy_host_count"))
@@ -398,14 +347,14 @@ const internalAccessList = {
.allowGraph("[owner,items,clients]") .allowGraph("[owner,items,clients]")
.orderBy("access_list.name", "ASC"); .orderBy("access_list.name", "ASC");
if (access_data.permission_visibility !== "all") { if (accessData.permission_visibility !== "all") {
query.andWhere("access_list.owner_user_id", access.token.getUserId(1)); query.andWhere("access_list.owner_user_id", access.token.getUserId(1));
} }
// Query is used for searching // Query is used for searching
if (typeof search_query === "string") { if (typeof searchQuery === "string") {
query.where(function () { query.where(function () {
this.where("name", "like", `%${search_query}%`); this.where("name", "like", `%${searchQuery}%`);
}); });
} }
@@ -413,9 +362,7 @@ const internalAccessList = {
query.withGraphFetched(`[${expand.join(", ")}]`); query.withGraphFetched(`[${expand.join(", ")}]`);
} }
return query.then(utils.omitRows(omissions())); const rows = await query.then(utils.omitRows(omissions()));
})
.then((rows) => {
if (rows) { if (rows) {
rows.map((row, idx) => { rows.map((row, idx) => {
if (typeof row.items !== "undefined" && row.items) { if (typeof row.items !== "undefined" && row.items) {
@@ -424,28 +371,28 @@ const internalAccessList = {
return true; return true;
}); });
} }
return rows; return rows;
});
}, },
/** /**
* Report use * Count is used in reports
* *
* @param {Integer} user_id * @param {Integer} userId
* @param {String} visibility * @param {String} visibility
* @returns {Promise} * @returns {Promise}
*/ */
getCount: (user_id, visibility) => { getCount: async (userId, visibility) => {
const query = accessListModel.query().count("id as count").where("is_deleted", 0); const query = accessListModel
.query()
.count("id as count")
.where("is_deleted", 0);
if (visibility !== "all") { if (visibility !== "all") {
query.andWhere("owner_user_id", user_id); query.andWhere("owner_user_id", userId);
} }
return query.first().then((row) => { const row = await query.first();
return Number.parseInt(row.count, 10); return Number.parseInt(row.count, 10);
});
}, },
/** /**
@@ -455,20 +402,19 @@ const internalAccessList = {
maskItems: (list) => { maskItems: (list) => {
if (list && typeof list.items !== "undefined") { if (list && typeof list.items !== "undefined") {
list.items.map((val, idx) => { list.items.map((val, idx) => {
let repeat_for = 8; let repeatFor = 8;
let first_char = "*"; let firstChar = "*";
if (typeof val.password !== "undefined" && val.password) { if (typeof val.password !== "undefined" && val.password) {
repeat_for = val.password.length - 1; repeatFor = val.password.length - 1;
first_char = val.password.charAt(0); firstChar = val.password.charAt(0);
} }
list.items[idx].hint = first_char + "*".repeat(repeat_for); list.items[idx].hint = firstChar + "*".repeat(repeatFor);
list.items[idx].password = ""; list.items[idx].password = "";
return true; return true;
}); });
} }
return list; return list;
}, },
@@ -488,43 +434,33 @@ const internalAccessList = {
* @param {Array} list.items * @param {Array} list.items
* @returns {Promise} * @returns {Promise}
*/ */
build: (list) => { build: async (list) => {
logger.info(`Building Access file #${list.id} for: ${list.name}`); logger.info(`Building Access file #${list.id} for: ${list.name}`);
return new Promise((resolve, reject) => { const htpasswdFile = internalAccessList.getFilename(list);
const htpasswd_file = internalAccessList.getFilename(list);
// 1. remove any existing access file // 1. remove any existing access file
try { try {
fs.unlinkSync(htpasswd_file); fs.unlinkSync(htpasswdFile);
} catch (_err) { } catch (_err) {
// do nothing // do nothing
} }
// 2. create empty access file // 2. create empty access file
try { fs.writeFileSync(htpasswdFile, '', {encoding: 'utf8'});
fs.writeFileSync(htpasswd_file, "", { encoding: "utf8" });
resolve(htpasswd_file);
} catch (err) {
reject(err);
}
}).then((htpasswd_file) => {
// 3. generate password for each user // 3. generate password for each user
if (list.items.length) { if (list.items.length) {
return new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
batchflow(list.items) batchflow(list.items).sequential()
.sequential()
.each((_i, item, next) => { .each((_i, item, next) => {
if (item.password?.length) { if (item.password?.length) {
logger.info(`Adding: ${item.username}`); logger.info(`Adding: ${item.username}`);
utils utils.execFile('openssl', ['passwd', '-apr1', item.password])
.execFile("openssl", ["passwd", "-apr1", item.password])
.then((res) => { .then((res) => {
try { try {
fs.appendFileSync(htpasswd_file, `${item.username}:${res}\n`, { fs.appendFileSync(htpasswdFile, `${item.username}:${res}\n`, {encoding: 'utf8'});
encoding: "utf8",
});
} catch (err) { } catch (err) {
reject(err); reject(err);
} }
@@ -546,8 +482,7 @@ const internalAccessList = {
}); });
}); });
} }
}); }
}, }
};
export default internalAccessList; export default internalAccessList;

View File

@@ -9,11 +9,12 @@ const internalAuditLog = {
* *
* @param {Access} access * @param {Access} access
* @param {Array} [expand] * @param {Array} [expand]
* @param {String} [search_query] * @param {String} [searchQuery]
* @returns {Promise} * @returns {Promise}
*/ */
getAll: (access, expand, search_query) => { getAll: async (access, expand, searchQuery) => {
return access.can("auditlog:list").then(() => { await access.can("auditlog:list");
const query = auditLogModel const query = auditLogModel
.query() .query()
.orderBy("created_on", "DESC") .orderBy("created_on", "DESC")
@@ -22,9 +23,9 @@ const internalAuditLog = {
.allowGraph("[user]"); .allowGraph("[user]");
// Query is used for searching // Query is used for searching
if (typeof search_query === "string" && search_query.length > 0) { if (typeof searchQuery === "string" && searchQuery.length > 0) {
query.where(function () { query.where(function () {
this.where(castJsonIfNeed("meta"), "like", `%${search_query}`); this.where(castJsonIfNeed("meta"), "like", `%${searchQuery}`);
}); });
} }
@@ -32,8 +33,7 @@ const internalAuditLog = {
query.withGraphFetched(`[${expand.join(", ")}]`); query.withGraphFetched(`[${expand.join(", ")}]`);
} }
return query; return await query;
});
}, },
/** /**
@@ -50,27 +50,22 @@ const internalAuditLog = {
* @param {Object} [data.meta] * @param {Object} [data.meta]
* @returns {Promise} * @returns {Promise}
*/ */
add: (access, data) => { add: async (access, data) => {
return new Promise((resolve, reject) => {
// Default the user id
if (typeof data.user_id === "undefined" || !data.user_id) { if (typeof data.user_id === "undefined" || !data.user_id) {
data.user_id = access.token.getUserId(1); data.user_id = access.token.getUserId(1);
} }
if (typeof data.action === "undefined" || !data.action) { if (typeof data.action === "undefined" || !data.action) {
reject(new errs.InternalValidationError("Audit log entry must contain an Action")); throw new errs.InternalValidationError("Audit log entry must contain an Action");
} else { }
// Make sure at least 1 of the IDs are set and action // Make sure at least 1 of the IDs are set and action
resolve( return await auditLogModel.query().insert({
auditLogModel.query().insert({
user_id: data.user_id, user_id: data.user_id,
action: data.action, action: data.action,
object_type: data.object_type || "", object_type: data.object_type || "",
object_id: data.object_id || 0, object_id: data.object_id || 0,
meta: data.meta || {}, meta: data.meta || {},
}),
);
}
}); });
}, },
}; };

View File

@@ -110,19 +110,19 @@ const internalCertificate = {
* @param {Object} data * @param {Object} data
* @returns {Promise} * @returns {Promise}
*/ */
create: (access, data) => { create: async (access, data) => {
return access await access.can("certificates:create", data);
.can("certificates:create", data)
.then(() => {
data.owner_user_id = access.token.getUserId(1); data.owner_user_id = access.token.getUserId(1);
if (data.provider === "letsencrypt") { if (data.provider === "letsencrypt") {
data.nice_name = data.domain_names.join(", "); data.nice_name = data.domain_names.join(", ");
} }
return certificateModel.query().insertAndFetch(data).then(utils.omitRow(omissions())); const certificate = await certificateModel
}) .query()
.then((certificate) => { .insertAndFetch(data)
.then(utils.omitRow(omissions()));
if (certificate.provider === "letsencrypt") { if (certificate.provider === "letsencrypt") {
// Request a new Cert from LE. Let the fun begin. // Request a new Cert from LE. Let the fun begin.
@@ -134,123 +134,85 @@ const internalCertificate = {
// 6. Re-instate previously disabled hosts // 6. Re-instate previously disabled hosts
// 1. Find out any hosts that are using any of the hostnames in this cert // 1. Find out any hosts that are using any of the hostnames in this cert
return internalHost const inUseResult = await internalHost.getHostsWithDomains(certificate.domain_names);
.getHostsWithDomains(certificate.domain_names)
.then((in_use_result) => {
// 2. Disable them in nginx temporarily // 2. Disable them in nginx temporarily
return internalCertificate.disableInUseHosts(in_use_result).then(() => { await internalCertificate.disableInUseHosts(inUseResult);
return in_use_result;
});
})
.then((in_use_result) => {
// With DNS challenge no config is needed, so skip 3 and 5. // With DNS challenge no config is needed, so skip 3 and 5.
if (certificate.meta.dns_challenge) { if (certificate.meta?.dns_challenge) {
return internalNginx try {
.reload() await internalNginx.reload();
.then(() => {
// 4. Request cert // 4. Request cert
return internalCertificate.requestLetsEncryptSslWithDnsChallenge(certificate); await internalCertificate.requestLetsEncryptSslWithDnsChallenge(certificate);
}) await internalNginx.reload();
.then(internalNginx.reload)
.then(() => {
// 6. Re-instate previously disabled hosts // 6. Re-instate previously disabled hosts
return internalCertificate.enableInUseHosts(in_use_result); await internalCertificate.enableInUseHosts(inUseResult);
}) } catch (err) {
.then(() => {
return certificate;
})
.catch((err) => {
// In the event of failure, revert things and throw err back // In the event of failure, revert things and throw err back
return internalCertificate await internalCertificate.enableInUseHosts(inUseResult);
.enableInUseHosts(in_use_result) await internalNginx.reload();
.then(internalNginx.reload)
.then(() => {
throw err; throw err;
});
});
} }
} else {
// 3. Generate the LE config // 3. Generate the LE config
return internalNginx try {
.generateLetsEncryptRequestConfig(certificate) await internalNginx.generateLetsEncryptRequestConfig(certificate);
.then(internalNginx.reload) await internalNginx.reload();
.then(async () => await new Promise((r) => setTimeout(r, 5000))) setTimeout(() => {}, 5000)
.then(() => {
// 4. Request cert // 4. Request cert
return internalCertificate.requestLetsEncryptSsl(certificate); await internalCertificate.requestLetsEncryptSsl(certificate);
})
.then(() => {
// 5. Remove LE config // 5. Remove LE config
return internalNginx.deleteLetsEncryptRequestConfig(certificate); await internalNginx.deleteLetsEncryptRequestConfig(certificate);
}) await internalNginx.reload();
.then(internalNginx.reload)
.then(() => {
// 6. Re-instate previously disabled hosts // 6. Re-instate previously disabled hosts
return internalCertificate.enableInUseHosts(in_use_result); await internalCertificate.enableInUseHosts(inUseResult);
}) } catch (err) {
.then(() => {
return certificate;
})
.catch((err) => {
// In the event of failure, revert things and throw err back // In the event of failure, revert things and throw err back
return internalNginx await internalNginx.deleteLetsEncryptRequestConfig(certificate);
.deleteLetsEncryptRequestConfig(certificate) await internalCertificate.enableInUseHosts(inUseResult);
.then(() => { await internalNginx.reload();
return internalCertificate.enableInUseHosts(in_use_result);
})
.then(internalNginx.reload)
.then(() => {
throw err; throw err;
}); }
}); }
})
.then(() => {
// At this point, the letsencrypt cert should exist on disk. // At this point, the letsencrypt cert should exist on disk.
// Lets get the expiry date from the file and update the row silently // Lets get the expiry date from the file and update the row silently
return internalCertificate try {
.getCertificateInfoFromFile( const certInfo = await internalCertificate.getCertificateInfoFromFile(
`${internalCertificate.getLiveCertPath(certificate.id)}/fullchain.pem`, `${internalCertificate.getLiveCertPath(certificate.id)}/fullchain.pem`,
) );
.then((cert_info) => { const savedRow = await certificateModel
return certificateModel
.query() .query()
.patchAndFetchById(certificate.id, { .patchAndFetchById(certificate.id, {
expires_on: moment(cert_info.dates.to, "X").format("YYYY-MM-DD HH:mm:ss"), expires_on: moment(certInfo.dates.to, "X").format("YYYY-MM-DD HH:mm:ss"),
}) })
.then(utils.omitRow(omissions())) .then(utils.omitRow(omissions()));
.then((saved_row) => {
// Add cert data for audit log
saved_row.meta = _.assign({}, saved_row.meta, {
letsencrypt_certificate: cert_info,
});
return saved_row; // Add cert data for audit log
savedRow.meta = _.assign({}, savedRow.meta, {
letsencrypt_certificate: certInfo,
}); });
}); return savedRow;
}) } catch (err) {
.catch(async (error) => {
// Delete the certificate from the database if it was not created successfully // Delete the certificate from the database if it was not created successfully
await certificateModel.query().deleteById(certificate.id); await certificateModel.query().deleteById(certificate.id);
throw err;
throw error;
});
} }
return certificate; }
})
.then((certificate) => {
data.meta = _.assign({}, data.meta || {}, certificate.meta); data.meta = _.assign({}, data.meta || {}, certificate.meta);
// Add to audit log // Add to audit log
return internalAuditLog await internalAuditLog
.add(access, { .add(access, {
action: "created", action: "created",
object_type: "certificate", object_type: "certificate",
object_id: certificate.id, object_id: certificate.id,
meta: data, meta: data,
}) });
.then(() => {
return certificate; return certificate;
});
});
}, },
/** /**
@@ -261,13 +223,10 @@ const internalCertificate = {
* @param {String} [data.name] * @param {String} [data.name]
* @return {Promise} * @return {Promise}
*/ */
update: (access, data) => { update: async (access, data) => {
return access await access.can("certificates:update", data.id);
.can("certificates:update", data.id) const row = await internalCertificate.get(access, { id: data.id });
.then((/*access_data*/) => {
return internalCertificate.get(access, { id: data.id });
})
.then((row) => {
if (row.id !== data.id) { if (row.id !== data.id) {
// Sanity check that something crazy hasn't happened // Sanity check that something crazy hasn't happened
throw new error.InternalValidationError( throw new error.InternalValidationError(
@@ -275,32 +234,29 @@ const internalCertificate = {
); );
} }
return certificateModel const savedRow = await certificateModel
.query() .query()
.patchAndFetchById(row.id, data) .patchAndFetchById(row.id, data)
.then(utils.omitRow(omissions())) .then(utils.omitRow(omissions()));
.then((saved_row) => {
saved_row.meta = internalCertificate.cleanMeta(saved_row.meta); savedRow.meta = internalCertificate.cleanMeta(savedRow.meta);
data.meta = internalCertificate.cleanMeta(data.meta); data.meta = internalCertificate.cleanMeta(data.meta);
// Add row.nice_name for custom certs // Add row.nice_name for custom certs
if (saved_row.provider === "other") { if (savedRow.provider === "other") {
data.nice_name = saved_row.nice_name; data.nice_name = savedRow.nice_name;
} }
// Add to audit log // Add to audit log
return internalAuditLog await internalAuditLog
.add(access, { .add(access, {
action: "updated", action: "updated",
object_type: "certificate", object_type: "certificate",
object_id: row.id, object_id: row.id,
meta: _.omit(data, ["expires_on"]), // this prevents json circular reference because expires_on might be raw meta: _.omit(data, ["expires_on"]), // this prevents json circular reference because expires_on might be raw
})
.then(() => {
return saved_row;
});
});
}); });
return savedRow;
}, },
/** /**
@@ -311,16 +267,12 @@ const internalCertificate = {
* @param {Array} [data.omit] * @param {Array} [data.omit]
* @return {Promise} * @return {Promise}
*/ */
get: (access, data) => { get: async (access, data) => {
const thisData = data || {}; const accessData = await access.can("certificates:get", data.id)
return access
.can("certificates:get", thisData.id)
.then((accessData) => {
const query = certificateModel const query = certificateModel
.query() .query()
.where("is_deleted", 0) .where("is_deleted", 0)
.andWhere("id", thisData.id) .andWhere("id", data.id)
.allowGraph("[owner]") .allowGraph("[owner]")
.allowGraph("[proxy_hosts]") .allowGraph("[proxy_hosts]")
.allowGraph("[redirection_hosts]") .allowGraph("[redirection_hosts]")
@@ -331,22 +283,19 @@ const internalCertificate = {
query.andWhere("owner_user_id", access.token.getUserId(1)); query.andWhere("owner_user_id", access.token.getUserId(1));
} }
if (typeof thisData.expand !== "undefined" && thisData.expand !== null) { if (typeof data.expand !== "undefined" && data.expand !== null) {
query.withGraphFetched(`[${thisData.expand.join(", ")}]`); query.withGraphFetched(`[${data.expand.join(", ")}]`);
} }
return query.then(utils.omitRow(omissions())); const row = await query.then(utils.omitRow(omissions()));
})
.then((row) => {
if (!row || !row.id) { if (!row || !row.id) {
throw new error.ItemNotFoundError(thisData.id); throw new error.ItemNotFoundError(data.id);
} }
// Custom omissions // Custom omissions
if (typeof thisData.omit !== "undefined" && thisData.omit !== null) { if (typeof data.omit !== "undefined" && data.omit !== null) {
return _.omit(row, thisData.omit); return _.omit(row, data.omit);
} }
return row; return row;
});
}, },
/** /**
@@ -355,17 +304,11 @@ const internalCertificate = {
* @param {Number} data.id * @param {Number} data.id
* @returns {Promise} * @returns {Promise}
*/ */
download: (access, data) => { download: async (access, data) => {
return new Promise((resolve, reject) => { await access.can("certificates:get", data);
access const certificate = await internalCertificate.get(access, data);
.can("certificates:get", data)
.then(() => {
return internalCertificate.get(access, data);
})
.then((certificate) => {
if (certificate.provider === "letsencrypt") { if (certificate.provider === "letsencrypt") {
const zipDirectory = internalCertificate.getLiveCertPath(data.id); const zipDirectory = internalCertificate.getLiveCertPath(data.id);
if (!fs.existsSync(zipDirectory)) { if (!fs.existsSync(zipDirectory)) {
throw new error.ItemNotFoundError(`Certificate ${certificate.nice_name} does not exists`); throw new error.ItemNotFoundError(`Certificate ${certificate.nice_name} does not exists`);
} }
@@ -374,24 +317,17 @@ const internalCertificate = {
.readdirSync(zipDirectory) .readdirSync(zipDirectory)
.filter((fn) => fn.endsWith(".pem")) .filter((fn) => fn.endsWith(".pem"))
.map((fn) => fs.realpathSync(path.join(zipDirectory, fn))); .map((fn) => fs.realpathSync(path.join(zipDirectory, fn)));
const downloadName = `npm-${data.id}-${Date.now()}.zip`; const downloadName = `npm-${data.id}-${Date.now()}.zip`;
const opName = `/tmp/${downloadName}`; const opName = `/tmp/${downloadName}`;
internalCertificate
.zipFiles(certFiles, opName) await internalCertificate.zipFiles(certFiles, opName);
.then(() => {
logger.debug("zip completed : ", opName); logger.debug("zip completed : ", opName);
const resp = { return {
fileName: opName, fileName: opName,
}; };
resolve(resp);
})
.catch((err) => reject(err));
} else {
throw new error.ValidationError("Only Let'sEncrypt certificates can be downloaded");
} }
}) throw new error.ValidationError("Only Let'sEncrypt certificates can be downloaded");
.catch((err) => reject(err));
});
}, },
/** /**
@@ -399,7 +335,7 @@ const internalCertificate = {
* @param {String} out * @param {String} out
* @returns {Promise} * @returns {Promise}
*/ */
zipFiles(source, out) { zipFiles: async (source, out) => {
const archive = archiver("zip", { zlib: { level: 9 } }); const archive = archiver("zip", { zlib: { level: 9 } });
const stream = fs.createWriteStream(out); const stream = fs.createWriteStream(out);
@@ -423,44 +359,36 @@ const internalCertificate = {
* @param {String} [data.reason] * @param {String} [data.reason]
* @returns {Promise} * @returns {Promise}
*/ */
delete: (access, data) => { delete: async (access, data) => {
return access await access.can("certificates:delete", data.id);
.can("certificates:delete", data.id) const row = await internalCertificate.get(access, { id: data.id });
.then(() => {
return internalCertificate.get(access, { id: data.id });
})
.then((row) => {
if (!row || !row.id) { if (!row || !row.id) {
throw new error.ItemNotFoundError(data.id); throw new error.ItemNotFoundError(data.id);
} }
return certificateModel await certificateModel
.query() .query()
.where("id", row.id) .where("id", row.id)
.patch({ .patch({
is_deleted: 1, is_deleted: 1,
}) });
.then(() => {
// Add to audit log // Add to audit log
row.meta = internalCertificate.cleanMeta(row.meta); row.meta = internalCertificate.cleanMeta(row.meta);
return internalAuditLog.add(access, { await internalAuditLog.add(access, {
action: "deleted", action: "deleted",
object_type: "certificate", object_type: "certificate",
object_id: row.id, object_id: row.id,
meta: _.omit(row, omissions()), meta: _.omit(row, omissions()),
}); });
})
.then(() => {
if (row.provider === "letsencrypt") { if (row.provider === "letsencrypt") {
// Revoke the cert // Revoke the cert
return internalCertificate.revokeLetsEncryptSsl(row); await internalCertificate.revokeLetsEncryptSsl(row);
} }
});
})
.then(() => {
return true; return true;
});
}, },
/** /**
@@ -468,11 +396,12 @@ const internalCertificate = {
* *
* @param {Access} access * @param {Access} access
* @param {Array} [expand] * @param {Array} [expand]
* @param {String} [search_query] * @param {String} [searchQuery]
* @returns {Promise} * @returns {Promise}
*/ */
getAll: (access, expand, search_query) => { getAll: async (access, expand, searchQuery) => {
return access.can("certificates:list").then((access_data) => { const accessData = await access.can("certificates:list");
const query = certificateModel const query = certificateModel
.query() .query()
.where("is_deleted", 0) .where("is_deleted", 0)
@@ -483,14 +412,14 @@ const internalCertificate = {
.allowGraph("[dead_hosts]") .allowGraph("[dead_hosts]")
.orderBy("nice_name", "ASC"); .orderBy("nice_name", "ASC");
if (access_data.permission_visibility !== "all") { if (accessData.permission_visibility !== "all") {
query.andWhere("owner_user_id", access.token.getUserId(1)); query.andWhere("owner_user_id", access.token.getUserId(1));
} }
// Query is used for searching // Query is used for searching
if (typeof search_query === "string") { if (typeof searchQuery === "string") {
query.where(function () { query.where(function () {
this.where("nice_name", "like", `%${search_query}%`); this.where("nice_name", "like", `%${searchQuery}%`);
}); });
} }
@@ -498,34 +427,35 @@ const internalCertificate = {
query.withGraphFetched(`[${expand.join(", ")}]`); query.withGraphFetched(`[${expand.join(", ")}]`);
} }
return query.then(utils.omitRows(omissions())); return await query.then(utils.omitRows(omissions()));
});
}, },
/** /**
* Report use * Report use
* *
* @param {Number} user_id * @param {Number} userId
* @param {String} visibility * @param {String} visibility
* @returns {Promise} * @returns {Promise}
*/ */
getCount: (user_id, visibility) => { getCount: async (userId, visibility) => {
const query = certificateModel.query().count("id as count").where("is_deleted", 0); const query = certificateModel
.query()
.count("id as count")
.where("is_deleted", 0);
if (visibility !== "all") { if (visibility !== "all") {
query.andWhere("owner_user_id", user_id); query.andWhere("owner_user_id", userId);
} }
return query.first().then((row) => { const row = await query.first();
return Number.parseInt(row.count, 10); return Number.parseInt(row.count, 10);
});
}, },
/** /**
* @param {Object} certificate * @param {Object} certificate
* @returns {Promise} * @returns {Promise}
*/ */
writeCustomCert: (certificate) => { writeCustomCert: async (certificate) => {
logger.info("Writing Custom Certificate:", certificate); logger.info("Writing Custom Certificate:", certificate);
const dir = `/data/custom_ssl/npm-${certificate.id}`; const dir = `/data/custom_ssl/npm-${certificate.id}`;
@@ -578,7 +508,7 @@ const internalCertificate = {
* @param {Boolean} data.meta.letsencrypt_agree * @param {Boolean} data.meta.letsencrypt_agree
* @returns {Promise} * @returns {Promise}
*/ */
createQuickCertificate: (access, data) => { createQuickCertificate: async (access, data) => {
return internalCertificate.create(access, { return internalCertificate.create(access, {
provider: "letsencrypt", provider: "letsencrypt",
domain_names: data.domain_names, domain_names: data.domain_names,
@@ -595,7 +525,6 @@ const internalCertificate = {
* @returns {Promise} * @returns {Promise}
*/ */
validate: (data) => { validate: (data) => {
return new Promise((resolve) => {
// Put file contents into an object // Put file contents into an object
const files = {}; const files = {};
_.map(data.files, (file, name) => { _.map(data.files, (file, name) => {
@@ -604,8 +533,6 @@ const internalCertificate = {
} }
}); });
resolve(files);
}).then((files) => {
// For each file, create a temp file and write the contents to it // For each file, create a temp file and write the contents to it
// Then test it depending on the file type // Then test it depending on the file type
const promises = []; const promises = [];
@@ -626,14 +553,11 @@ const internalCertificate = {
return Promise.all(promises).then((files) => { return Promise.all(promises).then((files) => {
let data = {}; let data = {};
_.each(files, (file) => { _.each(files, (file) => {
data = _.assign({}, data, file); data = _.assign({}, data, file);
}); });
return data; return data;
}); });
});
}, },
/** /**
@@ -643,15 +567,13 @@ const internalCertificate = {
* @param {Object} data.files * @param {Object} data.files
* @returns {Promise} * @returns {Promise}
*/ */
upload: (access, data) => { upload: async (access, data) => {
return internalCertificate.get(access, { id: data.id }).then((row) => { const row = await internalCertificate.get(access, { id: data.id });
if (row.provider !== "other") { if (row.provider !== "other") {
throw new error.ValidationError("Cannot upload certificates for this type of provider"); throw new error.ValidationError("Cannot upload certificates for this type of provider");
} }
return internalCertificate const validations = await internalCertificate.validate(data);
.validate(data)
.then((validations) => {
if (typeof validations.certificate === "undefined") { if (typeof validations.certificate === "undefined") {
throw new error.ValidationError("Certificate file was not provided"); throw new error.ValidationError("Certificate file was not provided");
} }
@@ -662,58 +584,45 @@ const internalCertificate = {
} }
}); });
// TODO: This uses a mysql only raw function that won't translate to postgres const certificate = internalCertificate.update(access, {
return internalCertificate
.update(access, {
id: data.id, id: data.id,
expires_on: moment(validations.certificate.dates.to, "X").format("YYYY-MM-DD HH:mm:ss"), expires_on: moment(validations.certificate.dates.to, "X").format("YYYY-MM-DD HH:mm:ss"),
domain_names: [validations.certificate.cn], domain_names: [validations.certificate.cn],
meta: _.clone(row.meta), // Prevent the update method from changing this value that we'll use later meta: _.clone(row.meta), // Prevent the update method from changing this value that we'll use later
}) });
.then((certificate) => {
certificate.meta = row.meta; certificate.meta = row.meta;
return internalCertificate.writeCustomCert(certificate); await internalCertificate.writeCustomCert(certificate);
});
})
.then(() => {
return _.pick(row.meta, internalCertificate.allowedSslFiles); return _.pick(row.meta, internalCertificate.allowedSslFiles);
});
});
}, },
/** /**
* Uses the openssl command to validate the private key. * Uses the openssl command to validate the private key.
* It will save the file to disk first, then run commands on it, then delete the file. * It will save the file to disk first, then run commands on it, then delete the file.
* *
* @param {String} private_key This is the entire key contents as a string * @param {String} privateKey This is the entire key contents as a string
*/ */
checkPrivateKey: (private_key) => { checkPrivateKey: async (privateKey) => {
return tempWrite(private_key, "/tmp").then((filepath) => { const filepath = await tempWrite(privateKey, "/tmp");
return new Promise((resolve, reject) => {
const failTimeout = setTimeout(() => { const failTimeout = setTimeout(() => {
reject( throw new error.ValidationError(
new error.ValidationError(
"Result Validation Error: Validation timed out. This could be due to the key being passphrase-protected.", "Result Validation Error: Validation timed out. This could be due to the key being passphrase-protected.",
),
); );
}, 10000); }, 10000);
utils
.exec(`openssl pkey -in ${filepath} -check -noout 2>&1 `) try {
.then((result) => { const result = await utils.exec(`openssl pkey -in ${filepath} -check -noout 2>&1 `);
clearTimeout(failTimeout); clearTimeout(failTimeout);
if (!result.toLowerCase().includes("key is valid")) { if (!result.toLowerCase().includes("key is valid")) {
reject(new error.ValidationError(`Result Validation Error: ${result}`)); throw new error.ValidationError(`Result Validation Error: ${result}`);
} }
fs.unlinkSync(filepath); fs.unlinkSync(filepath);
resolve(true); return true;
}) } catch (err) {
.catch((err) => {
clearTimeout(failTimeout); clearTimeout(failTimeout);
fs.unlinkSync(filepath); fs.unlinkSync(filepath);
reject(new error.ValidationError(`Certificate Key is not valid (${err.message})`, err)); throw new error.ValidationError(`Certificate Key is not valid (${err.message})`, err);
}); }
});
});
}, },
/** /**
@@ -721,36 +630,32 @@ const internalCertificate = {
* It will save the file to disk first, then run commands on it, then delete the file. * It will save the file to disk first, then run commands on it, then delete the file.
* *
* @param {String} certificate This is the entire cert contents as a string * @param {String} certificate This is the entire cert contents as a string
* @param {Boolean} [throw_expired] Throw when the certificate is out of date * @param {Boolean} [throwExpired] Throw when the certificate is out of date
*/ */
getCertificateInfo: (certificate, throw_expired) => { getCertificateInfo: async (certificate, throwExpired) => {
return tempWrite(certificate, "/tmp").then((filepath) => { try {
return internalCertificate const filepath = await tempWrite(certificate, "/tmp");
.getCertificateInfoFromFile(filepath, throw_expired) const certData = await internalCertificate.getCertificateInfoFromFile(filepath, throwExpired);
.then((certData) => {
fs.unlinkSync(filepath); fs.unlinkSync(filepath);
return certData; return certData;
}) } catch (err) {
.catch((err) => {
fs.unlinkSync(filepath); fs.unlinkSync(filepath);
throw err; throw err;
}); }
});
}, },
/** /**
* Uses the openssl command to both validate and get info out of the certificate. * Uses the openssl command to both validate and get info out of the certificate.
* It will save the file to disk first, then run commands on it, then delete the file. * It will save the file to disk first, then run commands on it, then delete the file.
* *
* @param {String} certificate_file The file location on disk * @param {String} certificateFile The file location on disk
* @param {Boolean} [throw_expired] Throw when the certificate is out of date * @param {Boolean} [throw_expired] Throw when the certificate is out of date
*/ */
getCertificateInfoFromFile: (certificate_file, throw_expired) => { getCertificateInfoFromFile: async (certificateFile, throw_expired) => {
const certData = {}; const certData = {};
return utils try {
.execFile("openssl", ["x509", "-in", certificate_file, "-subject", "-noout"]) const result = await utils.execFile("openssl", ["x509", "-in", certificateFile, "-subject", "-noout"])
.then((result) => {
// Examples: // Examples:
// subject=CN = *.jc21.com // subject=CN = *.jc21.com
// subject=CN = something.example.com // subject=CN = something.example.com
@@ -759,32 +664,25 @@ const internalCertificate = {
if (match && typeof match[1] !== "undefined") { if (match && typeof match[1] !== "undefined") {
certData.cn = match[1]; certData.cn = match[1];
} }
})
.then(() => {
return utils.execFile("openssl", ["x509", "-in", certificate_file, "-issuer", "-noout"]);
})
.then((result) => { const result2 = await utils.execFile("openssl", ["x509", "-in", certificateFile, "-issuer", "-noout"]);
// Examples: // Examples:
// issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3 // issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
// issuer=C = US, O = Let's Encrypt, CN = E5 // issuer=C = US, O = Let's Encrypt, CN = E5
// issuer=O = NginxProxyManager, CN = NginxProxyManager Intermediate CA","O = NginxProxyManager, CN = NginxProxyManager Intermediate CA // issuer=O = NginxProxyManager, CN = NginxProxyManager Intermediate CA","O = NginxProxyManager, CN = NginxProxyManager Intermediate CA
const regex = /^(?:issuer=)?(.*)$/gim; const regex2 = /^(?:issuer=)?(.*)$/gim;
const match = regex.exec(result); const match2 = regex2.exec(result2);
if (match && typeof match[1] !== "undefined") { if (match2 && typeof match2[1] !== "undefined") {
certData.issuer = match[1]; certData.issuer = match2[1];
} }
})
.then(() => { const result3 = await utils.execFile("openssl", ["x509", "-in", certificateFile, "-dates", "-noout"]);
return utils.execFile("openssl", ["x509", "-in", certificate_file, "-dates", "-noout"]);
})
.then((result) => {
// notBefore=Jul 14 04:04:29 2018 GMT // notBefore=Jul 14 04:04:29 2018 GMT
// notAfter=Oct 12 04:04:29 2018 GMT // notAfter=Oct 12 04:04:29 2018 GMT
let validFrom = null; let validFrom = null;
let validTo = null; let validTo = null;
const lines = result.split("\n"); const lines = result3.split("\n");
lines.map((str) => { lines.map((str) => {
const regex = /^(\S+)=(.*)$/gim; const regex = /^(\S+)=(.*)$/gim;
const match = regex.exec(str.trim()); const match = regex.exec(str.trim());
@@ -815,10 +713,9 @@ const internalCertificate = {
}; };
return certData; return certData;
}) } catch (err) {
.catch((err) => {
throw new error.ValidationError(`Certificate is not valid (${err.message})`, err); throw new error.ValidationError(`Certificate is not valid (${err.message})`, err);
}); }
}, },
/** /**
@@ -839,7 +736,6 @@ const internalCertificate = {
} }
return true; return true;
}); });
return meta; return meta;
}, },
@@ -848,7 +744,7 @@ const internalCertificate = {
* @param {Object} certificate the certificate row * @param {Object} certificate the certificate row
* @returns {Promise} * @returns {Promise}
*/ */
requestLetsEncryptSsl: (certificate) => { requestLetsEncryptSsl: async (certificate) => {
logger.info( logger.info(
`Requesting LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`, `Requesting LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
); );
@@ -879,17 +775,13 @@ const internalCertificate = {
logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`); logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
return utils.execFile(certbotCommand, args, adds.opts).then((result) => { const result = await utils.execFile(certbotCommand, args, adds.opts);
logger.success(result); logger.success(result);
return result; return result;
});
}, },
/** /**
* @param {Object} certificate the certificate row * @param {Object} certificate the certificate row
* @param {String} dns_provider the dns provider name (key used in `certbot-dns-plugins.json`)
* @param {String | null} credentials the content of this providers credentials file
* @param {String} propagation_seconds
* @returns {Promise} * @returns {Promise}
*/ */
requestLetsEncryptSslWithDnsChallenge: async (certificate) => { requestLetsEncryptSslWithDnsChallenge: async (certificate) => {
@@ -957,52 +849,43 @@ const internalCertificate = {
* @param {Number} data.id * @param {Number} data.id
* @returns {Promise} * @returns {Promise}
*/ */
renew: (access, data) => { renew: async (access, data) => {
return access await access.can("certificates:update", data)
.can("certificates:update", data) const certificate = await internalCertificate.get(access, data);
.then(() => {
return internalCertificate.get(access, data);
})
.then((certificate) => {
if (certificate.provider === "letsencrypt") { if (certificate.provider === "letsencrypt") {
const renewMethod = certificate.meta.dns_challenge const renewMethod = certificate.meta.dns_challenge
? internalCertificate.renewLetsEncryptSslWithDnsChallenge ? internalCertificate.renewLetsEncryptSslWithDnsChallenge
: internalCertificate.renewLetsEncryptSsl; : internalCertificate.renewLetsEncryptSsl;
return renewMethod(certificate) await renewMethod(certificate);
.then(() => { const certInfo = await internalCertificate.getCertificateInfoFromFile(
return internalCertificate.getCertificateInfoFromFile(
`${internalCertificate.getLiveCertPath(certificate.id)}/fullchain.pem`, `${internalCertificate.getLiveCertPath(certificate.id)}/fullchain.pem`,
); );
})
.then((cert_info) => { const updatedCertificate = await certificateModel
return certificateModel.query().patchAndFetchById(certificate.id, { .query()
expires_on: moment(cert_info.dates.to, "X").format("YYYY-MM-DD HH:mm:ss"), .patchAndFetchById(certificate.id, {
expires_on: moment(certInfo.dates.to, "X").format("YYYY-MM-DD HH:mm:ss"),
}); });
})
.then((updated_certificate) => {
// Add to audit log // Add to audit log
return internalAuditLog await internalAuditLog.add(access, {
.add(access, {
action: "renewed", action: "renewed",
object_type: "certificate", object_type: "certificate",
object_id: updated_certificate.id, object_id: updatedCertificate.id,
meta: updated_certificate, meta: updatedCertificate,
})
.then(() => {
return updated_certificate;
}); });
}); } else {
}
throw new error.ValidationError("Only Let'sEncrypt certificates can be renewed"); throw new error.ValidationError("Only Let'sEncrypt certificates can be renewed");
}); }
}, },
/** /**
* @param {Object} certificate the certificate row * @param {Object} certificate the certificate row
* @returns {Promise} * @returns {Promise}
*/ */
renewLetsEncryptSsl: (certificate) => { renewLetsEncryptSsl: async (certificate) => {
logger.info( logger.info(
`Renewing LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`, `Renewing LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
); );
@@ -1029,19 +912,17 @@ const internalCertificate = {
logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`); logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
return utils.execFile(certbotCommand, args, adds.opts).then((result) => { const result = await utils.execFile(certbotCommand, args, adds.opts);
logger.info(result); logger.info(result);
return result; return result;
});
}, },
/** /**
* @param {Object} certificate the certificate row * @param {Object} certificate the certificate row
* @returns {Promise} * @returns {Promise}
*/ */
renewLetsEncryptSslWithDnsChallenge: (certificate) => { renewLetsEncryptSslWithDnsChallenge: async (certificate) => {
const dnsPlugin = dnsPlugins[certificate.meta.dns_provider]; const dnsPlugin = dnsPlugins[certificate.meta.dns_provider];
if (!dnsPlugin) { if (!dnsPlugin) {
throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`); throw Error(`Unknown DNS provider '${certificate.meta.dns_provider}'`);
} }
@@ -1070,18 +951,17 @@ const internalCertificate = {
logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`); logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
return utils.execFile(certbotCommand, args, adds.opts).then(async (result) => { const result = await utils.execFile(certbotCommand, args, adds.opts);
logger.info(result); logger.info(result);
return result; return result;
});
}, },
/** /**
* @param {Object} certificate the certificate row * @param {Object} certificate the certificate row
* @param {Boolean} [throw_errors] * @param {Boolean} [throwErrors]
* @returns {Promise} * @returns {Promise}
*/ */
revokeLetsEncryptSsl: (certificate, throw_errors) => { revokeLetsEncryptSsl: async (certificate, throwErrors) => {
logger.info( logger.info(
`Revoking LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`, `Revoking LetsEncrypt certificates for Cert #${certificate.id}: ${certificate.domain_names.join(", ")}`,
); );
@@ -1104,20 +984,17 @@ const internalCertificate = {
logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`); logger.info(`Command: ${certbotCommand} ${args ? args.join(" ") : ""}`);
return utils try {
.execFile(certbotCommand, args, adds.opts) const result = await utils.execFile(certbotCommand, args, adds.opts);
.then(async (result) => {
await utils.exec(`rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`); await utils.exec(`rm -f '/etc/letsencrypt/credentials/credentials-${certificate.id}' || true`);
logger.info(result); logger.info(result);
return result; return result;
}) } catch (err) {
.catch((err) => {
logger.error(err.message); logger.error(err.message);
if (throwErrors) {
if (throw_errors) {
throw err; throw err;
} }
}); }
}, },
/** /**
@@ -1130,59 +1007,51 @@ const internalCertificate = {
}, },
/** /**
* @param {Object} in_use_result * @param {Object} inUseResult
* @param {Number} in_use_result.total_count * @param {Number} inUseResult.total_count
* @param {Array} in_use_result.proxy_hosts * @param {Array} inUseResult.proxy_hosts
* @param {Array} in_use_result.redirection_hosts * @param {Array} inUseResult.redirection_hosts
* @param {Array} in_use_result.dead_hosts * @param {Array} inUseResult.dead_hosts
* @returns {Promise}
*/ */
disableInUseHosts: (in_use_result) => { disableInUseHosts: async (inUseResult) => {
if (in_use_result.total_count) { if (inUseResult?.total_count) {
const promises = []; if (inUseResult?.proxy_hosts.length) {
await internalNginx.bulkDeleteConfigs("proxy_host", inUseResult.proxy_hosts);
if (in_use_result.proxy_hosts.length) {
promises.push(internalNginx.bulkDeleteConfigs("proxy_host", in_use_result.proxy_hosts));
} }
if (in_use_result.redirection_hosts.length) { if (inUseResult?.redirection_hosts.length) {
promises.push(internalNginx.bulkDeleteConfigs("redirection_host", in_use_result.redirection_hosts)); await internalNginx.bulkDeleteConfigs("redirection_host", inUseResult.redirection_hosts);
} }
if (in_use_result.dead_hosts.length) { if (inUseResult?.dead_hosts.length) {
promises.push(internalNginx.bulkDeleteConfigs("dead_host", in_use_result.dead_hosts)); await internalNginx.bulkDeleteConfigs("dead_host", inUseResult.dead_hosts);
} }
return Promise.all(promises);
} }
return Promise.resolve();
}, },
/** /**
* @param {Object} in_use_result * @param {Object} inUseResult
* @param {Number} in_use_result.total_count * @param {Number} inUseResult.total_count
* @param {Array} in_use_result.proxy_hosts * @param {Array} inUseResult.proxy_hosts
* @param {Array} in_use_result.redirection_hosts * @param {Array} inUseResult.redirection_hosts
* @param {Array} in_use_result.dead_hosts * @param {Array} inUseResult.dead_hosts
* @returns {Promise}
*/ */
enableInUseHosts: (in_use_result) => { enableInUseHosts: async (inUseResult) => {
if (in_use_result.total_count) { if (inUseResult.total_count) {
const promises = []; if (inUseResult.proxy_hosts.length) {
await internalNginx.bulkGenerateConfigs("proxy_host", inUseResult.proxy_hosts);
if (in_use_result.proxy_hosts.length) {
promises.push(internalNginx.bulkGenerateConfigs("proxy_host", in_use_result.proxy_hosts));
} }
if (in_use_result.redirection_hosts.length) { if (inUseResult.redirection_hosts.length) {
promises.push(internalNginx.bulkGenerateConfigs("redirection_host", in_use_result.redirection_hosts)); await internalNginx.bulkGenerateConfigs("redirection_host", inUseResult.redirection_hosts);
} }
if (in_use_result.dead_hosts.length) { if (inUseResult.dead_hosts.length) {
promises.push(internalNginx.bulkGenerateConfigs("dead_host", in_use_result.dead_hosts)); await internalNginx.bulkGenerateConfigs("dead_host", inUseResult.dead_hosts);
} }
return Promise.all(promises);
} }
return Promise.resolve();
}, },
testHttpsChallenge: async (access, domains) => { testHttpsChallenge: async (access, domains) => {
@@ -1293,9 +1162,7 @@ const internalCertificate = {
return "no-host"; return "no-host";
} }
// Other errors // Other errors
logger.info( logger.info(`HTTP challenge test failed for domain ${domain} because code ${result.responsecode} was returned`);
`HTTP challenge test failed for domain ${domain} because code ${result.responsecode} was returned`,
);
return `other:${result.responsecode}`; return `other:${result.responsecode}`;
} }
@@ -1335,9 +1202,9 @@ const internalCertificate = {
return { args: args, opts: opts }; return { args: args, opts: opts };
}, },
getLiveCertPath: (certificate_id) => { getLiveCertPath: (certificateId) => {
return `/etc/letsencrypt/live/npm-${certificate_id}`; return `/etc/letsencrypt/live/npm-${certificateId}`;
}, }
}; };
export default internalCertificate; export default internalCertificate;

View File

@@ -18,25 +18,24 @@ const internalDeadHost = {
* @param {Object} data * @param {Object} data
* @returns {Promise} * @returns {Promise}
*/ */
create: (access, data) => { create: async (access, data) => {
const createCertificate = data.certificate_id === "new"; const createCertificate = data.certificate_id === "new";
if (createCertificate) { if (createCertificate) {
delete data.certificate_id; delete data.certificate_id;
} }
return access await access.can("dead_hosts:create", data);
.can("dead_hosts:create", data)
.then((/*access_data*/) => {
// Get a list of the domain names and check each of them against existing records // Get a list of the domain names and check each of them against existing records
const domain_name_check_promises = []; const domainNameCheckPromises = [];
data.domain_names.map((domain_name) => { data.domain_names.map((domain_name) => {
domain_name_check_promises.push(internalHost.isHostnameTaken(domain_name)); domainNameCheckPromises.push(internalHost.isHostnameTaken(domain_name));
return true; return true;
}); });
return Promise.all(domain_name_check_promises).then((check_results) => { await Promise.all(domainNameCheckPromises).then((check_results) => {
check_results.map((result) => { check_results.map((result) => {
if (result.is_taken) { if (result.is_taken) {
throw new errs.ValidationError(`${result.hostname} is already in use`); throw new errs.ValidationError(`${result.hostname} is already in use`);
@@ -44,8 +43,7 @@ const internalDeadHost = {
return true; return true;
}); });
}); });
})
.then(() => {
// At this point the domains should have been checked // At this point the domains should have been checked
data.owner_user_id = access.token.getUserId(1); data.owner_user_id = access.token.getUserId(1);
const thisData = internalHost.cleanSslHstsData(data); const thisData = internalHost.cleanSslHstsData(data);
@@ -56,53 +54,36 @@ const internalDeadHost = {
thisData.advanced_config = ""; thisData.advanced_config = "";
} }
return deadHostModel.query().insertAndFetch(thisData).then(utils.omitRow(omissions())); const row = await deadHostModel.query().insertAndFetch(thisData).then(utils.omitRow(omissions()));
})
.then((row) => {
if (createCertificate) { if (createCertificate) {
return internalCertificate const cert = await internalCertificate.createQuickCertificate(access, data);
.createQuickCertificate(access, data)
.then((cert) => {
// update host with cert id // update host with cert id
return internalDeadHost.update(access, { await internalDeadHost.update(access, {
id: row.id, id: row.id,
certificate_id: cert.id, certificate_id: cert.id,
}); });
})
.then(() => {
return row;
});
} }
return row;
})
.then((row) => {
// re-fetch with cert // re-fetch with cert
return internalDeadHost.get(access, { const freshRow = await internalDeadHost.get(access, {
id: row.id, id: row.id,
expand: ["certificate", "owner"], expand: ["certificate", "owner"],
}); });
})
.then((row) => {
// Configure nginx // Configure nginx
return internalNginx.configure(deadHostModel, "dead_host", row).then(() => { await internalNginx.configure(deadHostModel, "dead_host", freshRow);
return row; data.meta = _.assign({}, data.meta || {}, freshRow.meta);
});
})
.then((row) => {
data.meta = _.assign({}, data.meta || {}, row.meta);
// Add to audit log // Add to audit log
return internalAuditLog await internalAuditLog.add(access, {
.add(access, {
action: "created", action: "created",
object_type: "dead-host", object_type: "dead-host",
object_id: row.id, object_id: freshRow.id,
meta: data, meta: data,
})
.then(() => {
return row;
});
}); });
return freshRow;
}, },
/** /**
@@ -111,66 +92,52 @@ const internalDeadHost = {
* @param {Number} data.id * @param {Number} data.id
* @return {Promise} * @return {Promise}
*/ */
update: (access, data) => { update: async (access, data) => {
let thisData = data; const createCertificate = data.certificate_id === "new";
const createCertificate = thisData.certificate_id === "new";
if (createCertificate) { if (createCertificate) {
delete thisData.certificate_id; delete data.certificate_id;
} }
return access await access.can("dead_hosts:update", data.id);
.can("dead_hosts:update", thisData.id)
.then((/*access_data*/) => {
// Get a list of the domain names and check each of them against existing records
const domain_name_check_promises = [];
if (typeof thisData.domain_names !== "undefined") { // Get a list of the domain names and check each of them against existing records
thisData.domain_names.map((domain_name) => { const domainNameCheckPromises = [];
domain_name_check_promises.push(internalHost.isHostnameTaken(domain_name, "dead", data.id)); if (typeof data.domain_names !== "undefined") {
data.domain_names.map((domainName) => {
domainNameCheckPromises.push(internalHost.isHostnameTaken(domainName, "dead", data.id));
return true; return true;
}); });
return Promise.all(domain_name_check_promises).then((check_results) => { const checkResults = await Promise.all(domainNameCheckPromises);
check_results.map((result) => { checkResults.map((result) => {
if (result.is_taken) { if (result.is_taken) {
throw new errs.ValidationError(`${result.hostname} is already in use`); throw new errs.ValidationError(`${result.hostname} is already in use`);
} }
return true; return true;
}); });
});
} }
}) const row = await internalDeadHost.get(access, { id: data.id });
.then(() => {
return internalDeadHost.get(access, { id: thisData.id }); if (row.id !== data.id) {
})
.then((row) => {
if (row.id !== thisData.id) {
// Sanity check that something crazy hasn't happened // Sanity check that something crazy hasn't happened
throw new errs.InternalValidationError( throw new errs.InternalValidationError(
`404 Host could not be updated, IDs do not match: ${row.id} !== ${thisData.id}`, `404 Host could not be updated, IDs do not match: ${row.id} !== ${data.id}`,
); );
} }
if (createCertificate) { if (createCertificate) {
return internalCertificate const cert = await internalCertificate.createQuickCertificate(access, {
.createQuickCertificate(access, { domain_names: data.domain_names || row.domain_names,
domain_names: thisData.domain_names || row.domain_names, meta: _.assign({}, row.meta, data.meta),
meta: _.assign({}, row.meta, thisData.meta),
})
.then((cert) => {
// update host with cert id
thisData.certificate_id = cert.id;
})
.then(() => {
return row;
}); });
// update host with cert id
data.certificate_id = cert.id;
} }
return row;
})
.then((row) => {
// Add domain_names to the data in case it isn't there, so that the audit log renders correctly. The order is important here. // Add domain_names to the data in case it isn't there, so that the audit log renders correctly. The order is important here.
thisData = _.assign( let thisData = _.assign(
{}, {},
{ {
domain_names: row.domain_names, domain_names: row.domain_names,
@@ -180,38 +147,24 @@ const internalDeadHost = {
thisData = internalHost.cleanSslHstsData(thisData, row); thisData = internalHost.cleanSslHstsData(thisData, row);
return deadHostModel
.query()
.where({ id: thisData.id })
.patch(thisData)
.then((saved_row) => {
// Add to audit log // Add to audit log
return internalAuditLog await internalAuditLog.add(access, {
.add(access, {
action: "updated", action: "updated",
object_type: "dead-host", object_type: "dead-host",
object_id: row.id, object_id: row.id,
meta: thisData, meta: thisData,
})
.then(() => {
return _.omit(saved_row, omissions());
}); });
});
}) const thisRow = await internalDeadHost
.then(() => {
return internalDeadHost
.get(access, { .get(access, {
id: thisData.id, id: thisData.id,
expand: ["owner", "certificate"], expand: ["owner", "certificate"],
}) });
.then((row) => {
// Configure nginx // Configure nginx
return internalNginx.configure(deadHostModel, "dead_host", row).then((new_meta) => { const newMeta = await internalNginx.configure(deadHostModel, "dead_host", row);
row.meta = new_meta; row.meta = newMeta;
return _.omit(internalHost.cleanRowCertificateMeta(row), omissions()); return _.omit(internalHost.cleanRowCertificateMeta(thisRow), omissions());
});
});
});
}, },
/** /**
@@ -222,39 +175,32 @@ const internalDeadHost = {
* @param {Array} [data.omit] * @param {Array} [data.omit]
* @return {Promise} * @return {Promise}
*/ */
get: (access, data) => { get: async (access, data) => {
const thisData = data || {}; const accessData = await access.can("dead_hosts:get", data.id);
return access
.can("dead_hosts:get", thisData.id)
.then((access_data) => {
const query = deadHostModel const query = deadHostModel
.query() .query()
.where("is_deleted", 0) .where("is_deleted", 0)
.andWhere("id", dthisDataata.id) .andWhere("id", data.id)
.allowGraph("[owner,certificate]") .allowGraph("[owner,certificate]")
.first(); .first();
if (access_data.permission_visibility !== "all") { if (accessData.permission_visibility !== "all") {
query.andWhere("owner_user_id", access.token.getUserId(1)); query.andWhere("owner_user_id", access.token.getUserId(1));
} }
if (typeof thisData.expand !== "undefined" && thisData.expand !== null) { if (typeof data.expand !== "undefined" && data.expand !== null) {
query.withGraphFetched(`[${data.expand.join(", ")}]`); query.withGraphFetched(`[${data.expand.join(", ")}]`);
} }
return query.then(utils.omitRow(omissions())); const row = await query.then(utils.omitRow(omissions()));
})
.then((row) => {
if (!row || !row.id) { if (!row || !row.id) {
throw new errs.ItemNotFoundError(thisData.id); throw new errs.ItemNotFoundError(data.id);
} }
// Custom omissions // Custom omissions
if (typeof thisData.omit !== "undefined" && thisData.omit !== null) { if (typeof data.omit !== "undefined" && data.omit !== null) {
return _.omit(row, thisData.omit); return _.omit(row, data.omit);
} }
return row; return row;
});
}, },
/** /**
@@ -264,42 +210,30 @@ const internalDeadHost = {
* @param {String} [data.reason] * @param {String} [data.reason]
* @returns {Promise} * @returns {Promise}
*/ */
delete: (access, data) => { delete: async (access, data) => {
return access await access.can("dead_hosts:delete", data.id)
.can("dead_hosts:delete", data.id) const row = await internalDeadHost.get(access, { id: data.id });
.then(() => {
return internalDeadHost.get(access, { id: data.id });
})
.then((row) => {
if (!row || !row.id) { if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id); throw new errs.ItemNotFoundError(data.id);
} }
return deadHostModel await deadHostModel
.query() .query()
.where("id", row.id) .where("id", row.id)
.patch({ .patch({
is_deleted: 1, is_deleted: 1,
})
.then(() => {
// Delete Nginx Config
return internalNginx.deleteConfig("dead_host", row).then(() => {
return internalNginx.reload();
}); });
})
.then(() => { // Delete Nginx Config
await internalNginx.deleteConfig("dead_host", row);
await internalNginx.reload();
// Add to audit log // Add to audit log
return internalAuditLog.add(access, { await internalAuditLog.add(access, {
action: "deleted", action: "deleted",
object_type: "dead-host", object_type: "dead-host",
object_id: row.id, object_id: row.id,
meta: _.omit(row, omissions()), meta: _.omit(row, omissions()),
}); });
});
})
.then(() => {
return true;
});
}, },
/** /**
@@ -309,16 +243,12 @@ const internalDeadHost = {
* @param {String} [data.reason] * @param {String} [data.reason]
* @returns {Promise} * @returns {Promise}
*/ */
enable: (access, data) => { enable: async (access, data) => {
return access await access.can("dead_hosts:update", data.id)
.can("dead_hosts:update", data.id) const row = await internalDeadHost.get(access, {
.then(() => {
return internalDeadHost.get(access, {
id: data.id, id: data.id,
expand: ["certificate", "owner"], expand: ["certificate", "owner"],
}); });
})
.then((row) => {
if (!row || !row.id) { if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id); throw new errs.ItemNotFoundError(data.id);
} }
@@ -328,29 +258,24 @@ const internalDeadHost = {
row.enabled = 1; row.enabled = 1;
return deadHostModel await deadHostModel
.query() .query()
.where("id", row.id) .where("id", row.id)
.patch({ .patch({
enabled: 1, enabled: 1,
}) });
.then(() => {
// Configure nginx // Configure nginx
return internalNginx.configure(deadHostModel, "dead_host", row); await internalNginx.configure(deadHostModel, "dead_host", row);
})
.then(() => {
// Add to audit log // Add to audit log
return internalAuditLog.add(access, { await internalAuditLog.add(access, {
action: "enabled", action: "enabled",
object_type: "dead-host", object_type: "dead-host",
object_id: row.id, object_id: row.id,
meta: _.omit(row, omissions()), meta: _.omit(row, omissions()),
}); });
});
})
.then(() => {
return true; return true;
});
}, },
/** /**
@@ -360,13 +285,9 @@ const internalDeadHost = {
* @param {String} [data.reason] * @param {String} [data.reason]
* @returns {Promise} * @returns {Promise}
*/ */
disable: (access, data) => { disable: async (access, data) => {
return access await access.can("dead_hosts:update", data.id)
.can("dead_hosts:update", data.id) const row = await internalDeadHost.get(access, { id: data.id });
.then(() => {
return internalDeadHost.get(access, { id: data.id });
})
.then((row) => {
if (!row || !row.id) { if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id); throw new errs.ItemNotFoundError(data.id);
} }
@@ -376,31 +297,25 @@ const internalDeadHost = {
row.enabled = 0; row.enabled = 0;
return deadHostModel await deadHostModel
.query() .query()
.where("id", row.id) .where("id", row.id)
.patch({ .patch({
enabled: 0, enabled: 0,
})
.then(() => {
// Delete Nginx Config
return internalNginx.deleteConfig("dead_host", row).then(() => {
return internalNginx.reload();
}); });
})
.then(() => { // Delete Nginx Config
await internalNginx.deleteConfig("dead_host", row);
await internalNginx.reload();
// Add to audit log // Add to audit log
return internalAuditLog.add(access, { await internalAuditLog.add(access, {
action: "disabled", action: "disabled",
object_type: "dead-host", object_type: "dead-host",
object_id: row.id, object_id: row.id,
meta: _.omit(row, omissions()), meta: _.omit(row, omissions()),
}); });
});
})
.then(() => {
return true; return true;
});
}, },
/** /**
@@ -408,13 +323,11 @@ const internalDeadHost = {
* *
* @param {Access} access * @param {Access} access
* @param {Array} [expand] * @param {Array} [expand]
* @param {String} [search_query] * @param {String} [searchQuery]
* @returns {Promise} * @returns {Promise}
*/ */
getAll: (access, expand, search_query) => { getAll: async (access, expand, searchQuery) => {
return access const accessData = await access.can("dead_hosts:list")
.can("dead_hosts:list")
.then((access_data) => {
const query = deadHostModel const query = deadHostModel
.query() .query()
.where("is_deleted", 0) .where("is_deleted", 0)
@@ -422,14 +335,14 @@ const internalDeadHost = {
.allowGraph("[owner,certificate]") .allowGraph("[owner,certificate]")
.orderBy(castJsonIfNeed("domain_names"), "ASC"); .orderBy(castJsonIfNeed("domain_names"), "ASC");
if (access_data.permission_visibility !== "all") { if (accessData.permission_visibility !== "all") {
query.andWhere("owner_user_id", access.token.getUserId(1)); query.andWhere("owner_user_id", access.token.getUserId(1));
} }
// Query is used for searching // Query is used for searching
if (typeof search_query === "string" && search_query.length > 0) { if (typeof searchQuery === "string" && searchQuery.length > 0) {
query.where(function () { query.where(function () {
this.where(castJsonIfNeed("domain_names"), "like", `%${search_query}%`); this.where(castJsonIfNeed("domain_names"), "like", `%${searchQuery}%`);
}); });
} }
@@ -437,15 +350,11 @@ const internalDeadHost = {
query.withGraphFetched(`[${expand.join(", ")}]`); query.withGraphFetched(`[${expand.join(", ")}]`);
} }
return query.then(utils.omitRows(omissions())); const rows = await query.then(utils.omitRows(omissions()));
})
.then((rows) => {
if (typeof expand !== "undefined" && expand !== null && expand.indexOf("certificate") !== -1) { if (typeof expand !== "undefined" && expand !== null && expand.indexOf("certificate") !== -1) {
return internalHost.cleanAllRowsCertificateMeta(rows); internalHost.cleanAllRowsCertificateMeta(rows);
} }
return rows; return rows;
});
}, },
/** /**
@@ -455,16 +364,15 @@ const internalDeadHost = {
* @param {String} visibility * @param {String} visibility
* @returns {Promise} * @returns {Promise}
*/ */
getCount: (user_id, visibility) => { getCount: async (user_id, visibility) => {
const query = deadHostModel.query().count("id as count").where("is_deleted", 0); const query = deadHostModel.query().count("id as count").where("is_deleted", 0);
if (visibility !== "all") { if (visibility !== "all") {
query.andWhere("owner_user_id", user_id); query.andWhere("owner_user_id", user_id);
} }
return query.first().then((row) => { const row = await query.first();
return Number.parseInt(row.count, 10); return Number.parseInt(row.count, 10);
});
}, },
}; };

View File

@@ -65,50 +65,33 @@ const internalHost = {
}, },
/** /**
* This returns all the host types with any domain listed in the provided domain_names array. * This returns all the host types with any domain listed in the provided domainNames array.
* This is used by the certificates to temporarily disable any host that is using the domain * This is used by the certificates to temporarily disable any host that is using the domain
* *
* @param {Array} domain_names * @param {Array} domainNames
* @returns {Promise} * @returns {Promise}
*/ */
getHostsWithDomains: (domain_names) => { getHostsWithDomains: async (domainNames) => {
const promises = [ const responseObject = {
proxyHostModel.query().where("is_deleted", 0),
redirectionHostModel.query().where("is_deleted", 0),
deadHostModel.query().where("is_deleted", 0),
];
return Promise.all(promises).then((promises_results) => {
const response_object = {
total_count: 0, total_count: 0,
dead_hosts: [], dead_hosts: [],
proxy_hosts: [], proxy_hosts: [],
redirection_hosts: [], redirection_hosts: [],
}; };
if (promises_results[0]) { const proxyRes = await proxyHostModel.query().where("is_deleted", 0);
// Proxy Hosts responseObject.proxy_hosts = internalHost._getHostsWithDomains(proxyRes, domainNames);
response_object.proxy_hosts = internalHost._getHostsWithDomains(promises_results[0], domain_names); responseObject.total_count += responseObject.proxy_hosts.length;
response_object.total_count += response_object.proxy_hosts.length;
}
if (promises_results[1]) { const redirRes = await redirectionHostModel.query().where("is_deleted", 0);
// Redirection Hosts responseObject.redirection_hosts = internalHost._getHostsWithDomains(redirRes, domainNames);
response_object.redirection_hosts = internalHost._getHostsWithDomains( responseObject.total_count += responseObject.redirection_hosts.length;
promises_results[1],
domain_names,
);
response_object.total_count += response_object.redirection_hosts.length;
}
if (promises_results[2]) { const deadRes = await deadHostModel.query().where("is_deleted", 0);
// Dead Hosts responseObject.dead_hosts = internalHost._getHostsWithDomains(deadRes, domainNames);
response_object.dead_hosts = internalHost._getHostsWithDomains(promises_results[2], domain_names); responseObject.total_count += responseObject.dead_hosts.length;
response_object.total_count += response_object.dead_hosts.length;
}
return response_object; return responseObject;
});
}, },
/** /**