setup.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. const config = require('./lib/config');
  2. const logger = require('./logger').setup;
  3. const certificateModel = require('./models/certificate');
  4. const userModel = require('./models/user');
  5. const userPermissionModel = require('./models/user_permission');
  6. const utils = require('./lib/utils');
  7. const authModel = require('./models/auth');
  8. const settingModel = require('./models/setting');
  9. const certbot = require('./lib/certbot');
  10. /**
  11. * Creates a default admin users if one doesn't already exist in the database
  12. *
  13. * @returns {Promise}
  14. */
  15. const setupDefaultUser = () => {
  16. return userModel
  17. .query()
  18. .select(userModel.raw('COUNT(`id`) as `count`'))
  19. .where('is_deleted', 0)
  20. .first()
  21. .then((row) => {
  22. if (!row.count) {
  23. // Create a new user and set password
  24. logger.info('Creating a new user: [email protected] with password: changeme');
  25. let data = {
  26. is_deleted: 0,
  27. email: '[email protected]',
  28. name: 'Administrator',
  29. nickname: 'Admin',
  30. avatar: '',
  31. roles: ['admin'],
  32. };
  33. return userModel
  34. .query()
  35. .insertAndFetch(data)
  36. .then((user) => {
  37. return authModel
  38. .query()
  39. .insert({
  40. user_id: user.id,
  41. type: 'password',
  42. secret: 'changeme',
  43. meta: {},
  44. })
  45. .then(() => {
  46. return userPermissionModel.query().insert({
  47. user_id: user.id,
  48. visibility: 'all',
  49. proxy_hosts: 'manage',
  50. redirection_hosts: 'manage',
  51. dead_hosts: 'manage',
  52. streams: 'manage',
  53. access_lists: 'manage',
  54. certificates: 'manage',
  55. });
  56. });
  57. })
  58. .then(() => {
  59. logger.info('Initial admin setup completed');
  60. });
  61. } else if (config.debug()) {
  62. logger.info('Admin user setup not required');
  63. }
  64. });
  65. };
  66. /**
  67. * Creates default settings if they don't already exist in the database
  68. *
  69. * @returns {Promise}
  70. */
  71. const setupDefaultSettings = () => {
  72. return settingModel
  73. .query()
  74. .select(settingModel.raw('COUNT(`id`) as `count`'))
  75. .where({id: 'default-site'})
  76. .first()
  77. .then((row) => {
  78. if (!row.count) {
  79. settingModel
  80. .query()
  81. .insert({
  82. id: 'default-site',
  83. name: 'Default Site',
  84. description: 'What to show when Nginx is hit with an unknown Host',
  85. value: 'congratulations',
  86. meta: {},
  87. })
  88. .then(() => {
  89. logger.info('Default settings added');
  90. });
  91. }
  92. if (config.debug()) {
  93. logger.info('Default setting setup not required');
  94. }
  95. });
  96. };
  97. /**
  98. * Installs all Certbot plugins which are required for an installed certificate
  99. *
  100. * @returns {Promise}
  101. */
  102. const setupCertbotPlugins = () => {
  103. return certificateModel
  104. .query()
  105. .where('is_deleted', 0)
  106. .andWhere('provider', 'letsencrypt')
  107. .then((certificates) => {
  108. if (certificates && certificates.length) {
  109. let plugins = [];
  110. let promises = [];
  111. certificates.map(function (certificate) {
  112. if (certificate.meta && certificate.meta.dns_challenge === true) {
  113. if (plugins.indexOf(certificate.meta.dns_provider) === -1) {
  114. plugins.push(certificate.meta.dns_provider);
  115. }
  116. // Make sure credentials file exists
  117. const credentials_loc = '/etc/letsencrypt/credentials/credentials-' + certificate.id;
  118. // Escape single quotes and backslashes
  119. const escapedCredentials = certificate.meta.dns_provider_credentials.replaceAll('\'', '\\\'').replaceAll('\\', '\\\\');
  120. const credentials_cmd = '[ -f \'' + credentials_loc + '\' ] || { mkdir -p /etc/letsencrypt/credentials 2> /dev/null; echo \'' + escapedCredentials + '\' > \'' + credentials_loc + '\' && chmod 600 \'' + credentials_loc + '\'; }';
  121. promises.push(utils.exec(credentials_cmd));
  122. }
  123. });
  124. return certbot.installPlugins(plugins)
  125. .then(() => {
  126. if (promises.length) {
  127. return Promise.all(promises)
  128. .then(() => {
  129. logger.info('Added Certbot plugins ' + plugins.join(', '));
  130. });
  131. }
  132. });
  133. }
  134. });
  135. };
  136. /**
  137. * Starts a timer to call run the logrotation binary every two days
  138. * @returns {Promise}
  139. */
  140. const setupLogrotation = () => {
  141. const intervalTimeout = 1000 * 60 * 60 * 24 * 2; // 2 days
  142. const runLogrotate = async () => {
  143. try {
  144. await utils.exec('logrotate /etc/logrotate.d/nginx-proxy-manager');
  145. logger.info('Logrotate completed.');
  146. } catch (e) { logger.warn(e); }
  147. };
  148. logger.info('Logrotate Timer initialized');
  149. setInterval(runLogrotate, intervalTimeout);
  150. // And do this now as well
  151. return runLogrotate();
  152. };
  153. module.exports = function () {
  154. return setupDefaultUser()
  155. .then(setupDefaultSettings)
  156. .then(setupCertbotPlugins)
  157. .then(setupLogrotation);
  158. };