dead-host.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. const _ = require('lodash');
  2. const error = require('../lib/error');
  3. const utils = require('../lib/utils');
  4. const deadHostModel = require('../models/dead_host');
  5. const internalHost = require('./host');
  6. const internalNginx = require('./nginx');
  7. const internalAuditLog = require('./audit-log');
  8. const internalCertificate = require('./certificate');
  9. function omissions () {
  10. return ['is_deleted'];
  11. }
  12. const internalDeadHost = {
  13. /**
  14. * @param {Access} access
  15. * @param {Object} data
  16. * @returns {Promise}
  17. */
  18. create: (access, data) => {
  19. let create_certificate = data.certificate_id === 'new';
  20. if (create_certificate) {
  21. delete data.certificate_id;
  22. }
  23. return access.can('dead_hosts:create', data)
  24. .then((/*access_data*/) => {
  25. // Get a list of the domain names and check each of them against existing records
  26. let domain_name_check_promises = [];
  27. data.domain_names.map(function (domain_name) {
  28. domain_name_check_promises.push(internalHost.isHostnameTaken(domain_name));
  29. });
  30. return Promise.all(domain_name_check_promises)
  31. .then((check_results) => {
  32. check_results.map(function (result) {
  33. if (result.is_taken) {
  34. throw new error.ValidationError(result.hostname + ' is already in use');
  35. }
  36. });
  37. });
  38. })
  39. .then(() => {
  40. // At this point the domains should have been checked
  41. data.owner_user_id = access.token.getUserId(1);
  42. data = internalHost.cleanSslHstsData(data);
  43. return deadHostModel
  44. .query()
  45. .insertAndFetch(data)
  46. .then(utils.omitRow(omissions()));
  47. })
  48. .then((row) => {
  49. if (create_certificate) {
  50. return internalCertificate.createQuickCertificate(access, data)
  51. .then((cert) => {
  52. // update host with cert id
  53. return internalDeadHost.update(access, {
  54. id: row.id,
  55. certificate_id: cert.id
  56. });
  57. })
  58. .then(() => {
  59. return row;
  60. });
  61. } else {
  62. return row;
  63. }
  64. })
  65. .then((row) => {
  66. // re-fetch with cert
  67. return internalDeadHost.get(access, {
  68. id: row.id,
  69. expand: ['certificate', 'owner']
  70. });
  71. })
  72. .then((row) => {
  73. // Configure nginx
  74. return internalNginx.configure(deadHostModel, 'dead_host', row)
  75. .then(() => {
  76. return row;
  77. });
  78. })
  79. .then((row) => {
  80. data.meta = _.assign({}, data.meta || {}, row.meta);
  81. // Add to audit log
  82. return internalAuditLog.add(access, {
  83. action: 'created',
  84. object_type: 'dead-host',
  85. object_id: row.id,
  86. meta: data
  87. })
  88. .then(() => {
  89. return row;
  90. });
  91. });
  92. },
  93. /**
  94. * @param {Access} access
  95. * @param {Object} data
  96. * @param {Number} data.id
  97. * @return {Promise}
  98. */
  99. update: (access, data) => {
  100. let create_certificate = data.certificate_id === 'new';
  101. if (create_certificate) {
  102. delete data.certificate_id;
  103. }
  104. return access.can('dead_hosts:update', data.id)
  105. .then((/*access_data*/) => {
  106. // Get a list of the domain names and check each of them against existing records
  107. let domain_name_check_promises = [];
  108. if (typeof data.domain_names !== 'undefined') {
  109. data.domain_names.map(function (domain_name) {
  110. domain_name_check_promises.push(internalHost.isHostnameTaken(domain_name, 'dead', data.id));
  111. });
  112. return Promise.all(domain_name_check_promises)
  113. .then((check_results) => {
  114. check_results.map(function (result) {
  115. if (result.is_taken) {
  116. throw new error.ValidationError(result.hostname + ' is already in use');
  117. }
  118. });
  119. });
  120. }
  121. })
  122. .then(() => {
  123. return internalDeadHost.get(access, {id: data.id});
  124. })
  125. .then((row) => {
  126. if (row.id !== data.id) {
  127. // Sanity check that something crazy hasn't happened
  128. throw new error.InternalValidationError('404 Host could not be updated, IDs do not match: ' + row.id + ' !== ' + data.id);
  129. }
  130. if (create_certificate) {
  131. return internalCertificate.createQuickCertificate(access, {
  132. domain_names: data.domain_names || row.domain_names,
  133. meta: _.assign({}, row.meta, data.meta)
  134. })
  135. .then((cert) => {
  136. // update host with cert id
  137. data.certificate_id = cert.id;
  138. })
  139. .then(() => {
  140. return row;
  141. });
  142. } else {
  143. return row;
  144. }
  145. })
  146. .then((row) => {
  147. // Add domain_names to the data in case it isn't there, so that the audit log renders correctly. The order is important here.
  148. data = _.assign({}, {
  149. domain_names: row.domain_names
  150. }, data);
  151. data = internalHost.cleanSslHstsData(data, row);
  152. return deadHostModel
  153. .query()
  154. .where({id: data.id})
  155. .patch(data)
  156. .then((saved_row) => {
  157. // Add to audit log
  158. return internalAuditLog.add(access, {
  159. action: 'updated',
  160. object_type: 'dead-host',
  161. object_id: row.id,
  162. meta: data
  163. })
  164. .then(() => {
  165. return _.omit(saved_row, omissions());
  166. });
  167. });
  168. })
  169. .then(() => {
  170. return internalDeadHost.get(access, {
  171. id: data.id,
  172. expand: ['owner', 'certificate']
  173. })
  174. .then((row) => {
  175. // Configure nginx
  176. return internalNginx.configure(deadHostModel, 'dead_host', row)
  177. .then((new_meta) => {
  178. row.meta = new_meta;
  179. row = internalHost.cleanRowCertificateMeta(row);
  180. return _.omit(row, omissions());
  181. });
  182. });
  183. });
  184. },
  185. /**
  186. * @param {Access} access
  187. * @param {Object} data
  188. * @param {Number} data.id
  189. * @param {Array} [data.expand]
  190. * @param {Array} [data.omit]
  191. * @return {Promise}
  192. */
  193. get: (access, data) => {
  194. if (typeof data === 'undefined') {
  195. data = {};
  196. }
  197. return access.can('dead_hosts:get', data.id)
  198. .then((access_data) => {
  199. let query = deadHostModel
  200. .query()
  201. .where('is_deleted', 0)
  202. .andWhere('id', data.id)
  203. .allowGraph('[owner,certificate]')
  204. .first();
  205. if (access_data.permission_visibility !== 'all') {
  206. query.andWhere('owner_user_id', access.token.getUserId(1));
  207. }
  208. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  209. query.withGraphFetched('[' + data.expand.join(', ') + ']');
  210. }
  211. return query.then(utils.omitRow(omissions()));
  212. })
  213. .then((row) => {
  214. if (!row) {
  215. throw new error.ItemNotFoundError(data.id);
  216. }
  217. // Custom omissions
  218. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  219. row = _.omit(row, data.omit);
  220. }
  221. return row;
  222. });
  223. },
  224. /**
  225. * @param {Access} access
  226. * @param {Object} data
  227. * @param {Number} data.id
  228. * @param {String} [data.reason]
  229. * @returns {Promise}
  230. */
  231. delete: (access, data) => {
  232. return access.can('dead_hosts:delete', data.id)
  233. .then(() => {
  234. return internalDeadHost.get(access, {id: data.id});
  235. })
  236. .then((row) => {
  237. if (!row) {
  238. throw new error.ItemNotFoundError(data.id);
  239. }
  240. return deadHostModel
  241. .query()
  242. .where('id', row.id)
  243. .patch({
  244. is_deleted: 1
  245. })
  246. .then(() => {
  247. // Delete Nginx Config
  248. return internalNginx.deleteConfig('dead_host', row)
  249. .then(() => {
  250. return internalNginx.reload();
  251. });
  252. })
  253. .then(() => {
  254. // Add to audit log
  255. return internalAuditLog.add(access, {
  256. action: 'deleted',
  257. object_type: 'dead-host',
  258. object_id: row.id,
  259. meta: _.omit(row, omissions())
  260. });
  261. });
  262. })
  263. .then(() => {
  264. return true;
  265. });
  266. },
  267. /**
  268. * @param {Access} access
  269. * @param {Object} data
  270. * @param {Number} data.id
  271. * @param {String} [data.reason]
  272. * @returns {Promise}
  273. */
  274. enable: (access, data) => {
  275. return access.can('dead_hosts:update', data.id)
  276. .then(() => {
  277. return internalDeadHost.get(access, {
  278. id: data.id,
  279. expand: ['certificate', 'owner']
  280. });
  281. })
  282. .then((row) => {
  283. if (!row) {
  284. throw new error.ItemNotFoundError(data.id);
  285. } else if (row.enabled) {
  286. throw new error.ValidationError('Host is already enabled');
  287. }
  288. row.enabled = 1;
  289. return deadHostModel
  290. .query()
  291. .where('id', row.id)
  292. .patch({
  293. enabled: 1
  294. })
  295. .then(() => {
  296. // Configure nginx
  297. return internalNginx.configure(deadHostModel, 'dead_host', row);
  298. })
  299. .then(() => {
  300. // Add to audit log
  301. return internalAuditLog.add(access, {
  302. action: 'enabled',
  303. object_type: 'dead-host',
  304. object_id: row.id,
  305. meta: _.omit(row, omissions())
  306. });
  307. });
  308. })
  309. .then(() => {
  310. return true;
  311. });
  312. },
  313. /**
  314. * @param {Access} access
  315. * @param {Object} data
  316. * @param {Number} data.id
  317. * @param {String} [data.reason]
  318. * @returns {Promise}
  319. */
  320. disable: (access, data) => {
  321. return access.can('dead_hosts:update', data.id)
  322. .then(() => {
  323. return internalDeadHost.get(access, {id: data.id});
  324. })
  325. .then((row) => {
  326. if (!row) {
  327. throw new error.ItemNotFoundError(data.id);
  328. } else if (!row.enabled) {
  329. throw new error.ValidationError('Host is already disabled');
  330. }
  331. row.enabled = 0;
  332. return deadHostModel
  333. .query()
  334. .where('id', row.id)
  335. .patch({
  336. enabled: 0
  337. })
  338. .then(() => {
  339. // Delete Nginx Config
  340. return internalNginx.deleteConfig('dead_host', row)
  341. .then(() => {
  342. return internalNginx.reload();
  343. });
  344. })
  345. .then(() => {
  346. // Add to audit log
  347. return internalAuditLog.add(access, {
  348. action: 'disabled',
  349. object_type: 'dead-host',
  350. object_id: row.id,
  351. meta: _.omit(row, omissions())
  352. });
  353. });
  354. })
  355. .then(() => {
  356. return true;
  357. });
  358. },
  359. /**
  360. * All Hosts
  361. *
  362. * @param {Access} access
  363. * @param {Array} [expand]
  364. * @param {String} [search_query]
  365. * @returns {Promise}
  366. */
  367. getAll: (access, expand, search_query) => {
  368. return access.can('dead_hosts:list')
  369. .then((access_data) => {
  370. let query = deadHostModel
  371. .query()
  372. .where('is_deleted', 0)
  373. .groupBy('id')
  374. .allowGraph('[owner,certificate]')
  375. .orderBy('domain_names', 'ASC');
  376. if (access_data.permission_visibility !== 'all') {
  377. query.andWhere('owner_user_id', access.token.getUserId(1));
  378. }
  379. // Query is used for searching
  380. if (typeof search_query === 'string') {
  381. query.where(function () {
  382. this.where('domain_names', 'like', '%' + search_query + '%');
  383. });
  384. }
  385. if (typeof expand !== 'undefined' && expand !== null) {
  386. query.withGraphFetched('[' + expand.join(', ') + ']');
  387. }
  388. return query.then(utils.omitRows(omissions()));
  389. })
  390. .then((rows) => {
  391. if (typeof expand !== 'undefined' && expand !== null && expand.indexOf('certificate') !== -1) {
  392. return internalHost.cleanAllRowsCertificateMeta(rows);
  393. }
  394. return rows;
  395. });
  396. },
  397. /**
  398. * Report use
  399. *
  400. * @param {Number} user_id
  401. * @param {String} visibility
  402. * @returns {Promise}
  403. */
  404. getCount: (user_id, visibility) => {
  405. let query = deadHostModel
  406. .query()
  407. .count('id as count')
  408. .where('is_deleted', 0);
  409. if (visibility !== 'all') {
  410. query.andWhere('owner_user_id', user_id);
  411. }
  412. return query.first()
  413. .then((row) => {
  414. return parseInt(row.count, 10);
  415. });
  416. }
  417. };
  418. module.exports = internalDeadHost;