setup.js 4.8 KB

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