proxy-host.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. const _ = require('lodash');
  2. const error = require('../lib/error');
  3. const proxyHostModel = require('../models/proxy_host');
  4. const internalHost = require('./host');
  5. const internalNginx = require('./nginx');
  6. const internalAuditLog = require('./audit-log');
  7. const internalCertificate = require('./certificate');
  8. function omissions () {
  9. return ['is_deleted'];
  10. }
  11. const internalProxyHost = {
  12. /**
  13. * @param {Access} access
  14. * @param {Object} data
  15. * @returns {Promise}
  16. */
  17. create: (access, data) => {
  18. let create_certificate = data.certificate_id === 'new';
  19. if (create_certificate) {
  20. delete data.certificate_id;
  21. }
  22. return access.can('proxy_hosts:create', data)
  23. .then(() => {
  24. // Get a list of the domain names and check each of them against existing records
  25. let domain_name_check_promises = [];
  26. data.domain_names.map(function (domain_name) {
  27. domain_name_check_promises.push(internalHost.isHostnameTaken(domain_name));
  28. });
  29. return Promise.all(domain_name_check_promises)
  30. .then((check_results) => {
  31. check_results.map(function (result) {
  32. if (result.is_taken) {
  33. throw new error.ValidationError(result.hostname + ' is already in use');
  34. }
  35. });
  36. });
  37. })
  38. .then(() => {
  39. // At this point the domains should have been checked
  40. data.owner_user_id = access.token.getUserId(1);
  41. data = internalHost.cleanSslHstsData(data);
  42. return proxyHostModel
  43. .query()
  44. .omit(omissions())
  45. .insertAndFetch(data);
  46. })
  47. .then((row) => {
  48. if (create_certificate) {
  49. return internalCertificate.createQuickCertificate(access, data)
  50. .then((cert) => {
  51. // update host with cert id
  52. return internalProxyHost.update(access, {
  53. id: row.id,
  54. certificate_id: cert.id
  55. });
  56. })
  57. .then(() => {
  58. return row;
  59. });
  60. } else {
  61. return row;
  62. }
  63. })
  64. .then((row) => {
  65. // re-fetch with cert
  66. return internalProxyHost.get(access, {
  67. id: row.id,
  68. expand: ['certificate', 'owner', 'access_list.[clients,items]']
  69. });
  70. })
  71. .then((row) => {
  72. // Configure nginx
  73. return internalNginx.configure(proxyHostModel, 'proxy_host', row)
  74. .then(() => {
  75. return row;
  76. });
  77. })
  78. .then((row) => {
  79. // Audit log
  80. data.meta = _.assign({}, data.meta || {}, row.meta);
  81. // Add to audit log
  82. return internalAuditLog.add(access, {
  83. action: 'created',
  84. object_type: 'proxy-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('proxy_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, 'proxy', 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 internalProxyHost.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('Proxy 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 proxyHostModel
  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: 'proxy-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 internalProxyHost.get(access, {
  171. id: data.id,
  172. expand: ['owner', 'certificate', 'access_list.[clients,items]']
  173. })
  174. .then((row) => {
  175. if (!row.enabled) {
  176. // No need to add nginx config if host is disabled
  177. return row;
  178. }
  179. // Configure nginx
  180. return internalNginx.configure(proxyHostModel, 'proxy_host', row)
  181. .then((new_meta) => {
  182. row.meta = new_meta;
  183. row = internalHost.cleanRowCertificateMeta(row);
  184. return _.omit(row, omissions());
  185. });
  186. });
  187. });
  188. },
  189. /**
  190. * @param {Access} access
  191. * @param {Object} data
  192. * @param {Number} data.id
  193. * @param {Array} [data.expand]
  194. * @param {Array} [data.omit]
  195. * @return {Promise}
  196. */
  197. get: (access, data) => {
  198. if (typeof data === 'undefined') {
  199. data = {};
  200. }
  201. return access.can('proxy_hosts:get', data.id)
  202. .then((access_data) => {
  203. let query = proxyHostModel
  204. .query()
  205. .where('is_deleted', 0)
  206. .andWhere('id', data.id)
  207. .allowEager('[owner,access_list,access_list.[clients,items],certificate]')
  208. .first();
  209. if (access_data.permission_visibility !== 'all') {
  210. query.andWhere('owner_user_id', access.token.getUserId(1));
  211. }
  212. // Custom omissions
  213. if (typeof data.omit !== 'undefined' && data.omit !== null) {
  214. query.omit(data.omit);
  215. }
  216. if (typeof data.expand !== 'undefined' && data.expand !== null) {
  217. query.eager('[' + data.expand.join(', ') + ']');
  218. }
  219. return query;
  220. })
  221. .then((row) => {
  222. if (row) {
  223. row = internalHost.cleanRowCertificateMeta(row);
  224. return _.omit(row, omissions());
  225. } else {
  226. throw new error.ItemNotFoundError(data.id);
  227. }
  228. });
  229. },
  230. /**
  231. * @param {Access} access
  232. * @param {Object} data
  233. * @param {Number} data.id
  234. * @param {String} [data.reason]
  235. * @returns {Promise}
  236. */
  237. delete: (access, data) => {
  238. return access.can('proxy_hosts:delete', data.id)
  239. .then(() => {
  240. return internalProxyHost.get(access, {id: data.id});
  241. })
  242. .then((row) => {
  243. if (!row) {
  244. throw new error.ItemNotFoundError(data.id);
  245. }
  246. return proxyHostModel
  247. .query()
  248. .where('id', row.id)
  249. .patch({
  250. is_deleted: 1
  251. })
  252. .then(() => {
  253. // Delete Nginx Config
  254. return internalNginx.deleteConfig('proxy_host', row)
  255. .then(() => {
  256. return internalNginx.reload();
  257. });
  258. })
  259. .then(() => {
  260. // Add to audit log
  261. return internalAuditLog.add(access, {
  262. action: 'deleted',
  263. object_type: 'proxy-host',
  264. object_id: row.id,
  265. meta: _.omit(row, omissions())
  266. });
  267. });
  268. })
  269. .then(() => {
  270. return true;
  271. });
  272. },
  273. /**
  274. * @param {Access} access
  275. * @param {Object} data
  276. * @param {Number} data.id
  277. * @param {String} [data.reason]
  278. * @returns {Promise}
  279. */
  280. enable: (access, data) => {
  281. return access.can('proxy_hosts:update', data.id)
  282. .then(() => {
  283. return internalProxyHost.get(access, {
  284. id: data.id,
  285. expand: ['certificate', 'owner', 'access_list']
  286. });
  287. })
  288. .then((row) => {
  289. if (!row) {
  290. throw new error.ItemNotFoundError(data.id);
  291. } else if (row.enabled) {
  292. throw new error.ValidationError('Host is already enabled');
  293. }
  294. row.enabled = 1;
  295. return proxyHostModel
  296. .query()
  297. .where('id', row.id)
  298. .patch({
  299. enabled: 1
  300. })
  301. .then(() => {
  302. // Configure nginx
  303. return internalNginx.configure(proxyHostModel, 'proxy_host', row);
  304. })
  305. .then(() => {
  306. // Add to audit log
  307. return internalAuditLog.add(access, {
  308. action: 'enabled',
  309. object_type: 'proxy-host',
  310. object_id: row.id,
  311. meta: _.omit(row, omissions())
  312. });
  313. });
  314. })
  315. .then(() => {
  316. return true;
  317. });
  318. },
  319. /**
  320. * @param {Access} access
  321. * @param {Object} data
  322. * @param {Number} data.id
  323. * @param {String} [data.reason]
  324. * @returns {Promise}
  325. */
  326. disable: (access, data) => {
  327. return access.can('proxy_hosts:update', data.id)
  328. .then(() => {
  329. return internalProxyHost.get(access, {id: data.id});
  330. })
  331. .then((row) => {
  332. if (!row) {
  333. throw new error.ItemNotFoundError(data.id);
  334. } else if (!row.enabled) {
  335. throw new error.ValidationError('Host is already disabled');
  336. }
  337. row.enabled = 0;
  338. return proxyHostModel
  339. .query()
  340. .where('id', row.id)
  341. .patch({
  342. enabled: 0
  343. })
  344. .then(() => {
  345. // Delete Nginx Config
  346. return internalNginx.deleteConfig('proxy_host', row)
  347. .then(() => {
  348. return internalNginx.reload();
  349. });
  350. })
  351. .then(() => {
  352. // Add to audit log
  353. return internalAuditLog.add(access, {
  354. action: 'disabled',
  355. object_type: 'proxy-host',
  356. object_id: row.id,
  357. meta: _.omit(row, omissions())
  358. });
  359. });
  360. })
  361. .then(() => {
  362. return true;
  363. });
  364. },
  365. /**
  366. * All Hosts
  367. *
  368. * @param {Access} access
  369. * @param {Array} [expand]
  370. * @param {String} [search_query]
  371. * @returns {Promise}
  372. */
  373. getAll: (access, expand, search_query) => {
  374. return access.can('proxy_hosts:list')
  375. .then((access_data) => {
  376. let query = proxyHostModel
  377. .query()
  378. .where('is_deleted', 0)
  379. .groupBy('id')
  380. .omit(['is_deleted'])
  381. .allowEager('[owner,access_list,certificate]')
  382. .orderBy('domain_names', 'ASC');
  383. if (access_data.permission_visibility !== 'all') {
  384. query.andWhere('owner_user_id', access.token.getUserId(1));
  385. }
  386. // Query is used for searching
  387. if (typeof search_query === 'string') {
  388. query.where(function () {
  389. this.where('domain_names', 'like', '%' + search_query + '%');
  390. });
  391. }
  392. if (typeof expand !== 'undefined' && expand !== null) {
  393. query.eager('[' + expand.join(', ') + ']');
  394. }
  395. return query;
  396. })
  397. .then((rows) => {
  398. if (typeof expand !== 'undefined' && expand !== null && expand.indexOf('certificate') !== -1) {
  399. return internalHost.cleanAllRowsCertificateMeta(rows);
  400. }
  401. return rows;
  402. });
  403. },
  404. /**
  405. * Report use
  406. *
  407. * @param {Number} user_id
  408. * @param {String} visibility
  409. * @returns {Promise}
  410. */
  411. getCount: (user_id, visibility) => {
  412. let query = proxyHostModel
  413. .query()
  414. .count('id as count')
  415. .where('is_deleted', 0);
  416. if (visibility !== 'all') {
  417. query.andWhere('owner_user_id', user_id);
  418. }
  419. return query.first()
  420. .then((row) => {
  421. return parseInt(row.count, 10);
  422. });
  423. }
  424. };
  425. module.exports = internalProxyHost;