settings.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. var nodemailer = require('nodemailer');
  2. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  3. // in the package definition.
  4. const isSandstorm =
  5. Meteor.settings && Meteor.settings.public && Meteor.settings.public.sandstorm;
  6. Settings = new Mongo.Collection('settings');
  7. Settings.attachSchema(
  8. new SimpleSchema({
  9. disableRegistration: {
  10. type: Boolean,
  11. },
  12. 'mailServer.username': {
  13. type: String,
  14. optional: true,
  15. },
  16. 'mailServer.password': {
  17. type: String,
  18. optional: true,
  19. },
  20. 'mailServer.host': {
  21. type: String,
  22. optional: true,
  23. },
  24. 'mailServer.port': {
  25. type: String,
  26. optional: true,
  27. },
  28. 'mailServer.enableTLS': {
  29. type: Boolean,
  30. optional: true,
  31. },
  32. 'mailServer.from': {
  33. type: String,
  34. optional: true,
  35. },
  36. productName: {
  37. type: String,
  38. optional: true,
  39. },
  40. displayAuthenticationMethod: {
  41. type: Boolean,
  42. optional: true,
  43. },
  44. defaultAuthenticationMethod: {
  45. type: String,
  46. optional: false,
  47. },
  48. spinnerName: {
  49. type: String,
  50. optional: true,
  51. },
  52. hideLogo: {
  53. type: Boolean,
  54. optional: true,
  55. },
  56. customLoginLogoImageUrl: {
  57. type: String,
  58. optional: true,
  59. },
  60. customLoginLogoLinkUrl: {
  61. type: String,
  62. optional: true,
  63. },
  64. textBelowCustomLoginLogo: {
  65. type: String,
  66. optional: true,
  67. },
  68. automaticLinkedUrlSchemes: {
  69. type: String,
  70. optional: true,
  71. },
  72. customTopLeftCornerLogoImageUrl: {
  73. type: String,
  74. optional: true,
  75. },
  76. customTopLeftCornerLogoLinkUrl: {
  77. type: String,
  78. optional: true,
  79. },
  80. customTopLeftCornerLogoHeight: {
  81. type: String,
  82. optional: true,
  83. },
  84. createdAt: {
  85. type: Date,
  86. denyUpdate: true,
  87. // eslint-disable-next-line consistent-return
  88. autoValue() {
  89. if (this.isInsert) {
  90. return new Date();
  91. } else if (this.isUpsert) {
  92. return { $setOnInsert: new Date() };
  93. } else {
  94. this.unset();
  95. }
  96. },
  97. },
  98. modifiedAt: {
  99. type: Date,
  100. // eslint-disable-next-line consistent-return
  101. autoValue() {
  102. if (this.isInsert || this.isUpsert || this.isUpdate) {
  103. return new Date();
  104. } else {
  105. this.unset();
  106. }
  107. },
  108. },
  109. }),
  110. );
  111. Settings.helpers({
  112. mailUrl() {
  113. if (!this.mailServer.host) {
  114. return null;
  115. }
  116. const protocol = this.mailServer.enableTLS ? 'smtps://' : 'smtp://';
  117. if (!this.mailServer.username && !this.mailServer.password) {
  118. return `${protocol}${this.mailServer.host}:${this.mailServer.port}/`;
  119. }
  120. return `${protocol}${this.mailServer.username}:${encodeURIComponent(
  121. this.mailServer.password,
  122. )}@${this.mailServer.host}:${this.mailServer.port}/`;
  123. },
  124. });
  125. Settings.allow({
  126. update(userId) {
  127. const user = Users.findOne(userId);
  128. return user && user.isAdmin;
  129. },
  130. });
  131. if (Meteor.isServer) {
  132. Meteor.startup(() => {
  133. Settings._collection._ensureIndex({ modifiedAt: -1 });
  134. const setting = Settings.findOne({});
  135. if (!setting) {
  136. const now = new Date();
  137. const domain = process.env.ROOT_URL.match(
  138. /\/\/(?:www\.)?(.*)?(?:\/)?/,
  139. )[1];
  140. const from = `Boards Support <support@${domain}>`;
  141. const defaultSetting = {
  142. disableRegistration: false,
  143. mailServer: {
  144. username: '',
  145. password: '',
  146. host: '',
  147. port: '',
  148. enableTLS: false,
  149. from,
  150. },
  151. createdAt: now,
  152. modifiedAt: now,
  153. displayAuthenticationMethod: true,
  154. defaultAuthenticationMethod: 'password',
  155. };
  156. Settings.insert(defaultSetting);
  157. }
  158. if (isSandstorm) {
  159. // At Sandstorm, Admin Panel has SMTP settings
  160. const newSetting = Settings.findOne();
  161. if (!process.env.MAIL_URL && newSetting.mailUrl())
  162. process.env.MAIL_URL = newSetting.mailUrl();
  163. Accounts.emailTemplates.from = process.env.MAIL_FROM
  164. ? process.env.MAIL_FROM
  165. : newSetting.mailServer.from;
  166. } else {
  167. // Not running on Sandstorm, so using environment variables
  168. Accounts.emailTemplates.from = process.env.MAIL_FROM;
  169. }
  170. });
  171. if (isSandstorm) {
  172. // At Sandstorm Wekan Admin Panel, save SMTP settings.
  173. Settings.after.update((userId, doc, fieldNames) => {
  174. // assign new values to mail-from & MAIL_URL in environment
  175. if (_.contains(fieldNames, 'mailServer') && doc.mailServer.host) {
  176. const protocol = doc.mailServer.enableTLS ? 'smtps://' : 'smtp://';
  177. if (!doc.mailServer.username && !doc.mailServer.password) {
  178. process.env.MAIL_URL = `${protocol}${doc.mailServer.host}:${doc.mailServer.port}/`;
  179. } else {
  180. process.env.MAIL_URL = `${protocol}${
  181. doc.mailServer.username
  182. }:${encodeURIComponent(doc.mailServer.password)}@${
  183. doc.mailServer.host
  184. }:${doc.mailServer.port}/`;
  185. }
  186. Accounts.emailTemplates.from = doc.mailServer.from;
  187. }
  188. });
  189. }
  190. function getRandomNum(min, max) {
  191. const range = max - min;
  192. const rand = Math.random();
  193. return min + Math.round(rand * range);
  194. }
  195. function getEnvVar(name) {
  196. const value = process.env[name];
  197. if (value) {
  198. return value;
  199. }
  200. throw new Meteor.Error([
  201. 'var-not-exist',
  202. `The environment variable ${name} does not exist`,
  203. ]);
  204. }
  205. function sendInvitationEmail(_id) {
  206. const icode = InvitationCodes.findOne(_id);
  207. const author = Users.findOne(Meteor.userId());
  208. try {
  209. const params = {
  210. email: icode.email,
  211. inviter: Users.findOne(icode.authorId).username,
  212. user: icode.email.split('@')[0],
  213. icode: icode.code,
  214. url: FlowRouter.url('sign-up'),
  215. };
  216. const lang = author.getLanguage();
  217. if (process.env.MAIL_SERVICE !== '') {
  218. let transporter = nodemailer.createTransport({
  219. service: process.env.MAIL_SERVICE,
  220. auth: {
  221. user: process.env.MAIL_SERVICE_USER,
  222. pass: process.env.MAIL_SERVICE_PASSWORD
  223. },
  224. })
  225. let info = transporter.sendMail({
  226. to: icode.email,
  227. from: Accounts.emailTemplates.from,
  228. subject: TAPi18n.__('email-invite-register-subject', params, lang),
  229. text: TAPi18n.__('email-invite-register-text', params, lang),
  230. })
  231. } else {
  232. Email.send({
  233. to: icode.email,
  234. from: Accounts.emailTemplates.from,
  235. subject: TAPi18n.__('email-invite-register-subject', params, lang),
  236. text: TAPi18n.__('email-invite-register-text', params, lang),
  237. });
  238. }
  239. } catch (e) {
  240. InvitationCodes.remove(_id);
  241. throw new Meteor.Error('email-fail', e.message);
  242. }
  243. }
  244. function isLdapEnabled() {
  245. return (
  246. process.env.LDAP_ENABLE === 'true' || process.env.LDAP_ENABLE === true
  247. );
  248. }
  249. function isOauth2Enabled() {
  250. return (
  251. process.env.OAUTH2_ENABLED === 'true' ||
  252. process.env.OAUTH2_ENABLED === true
  253. );
  254. }
  255. function isCasEnabled() {
  256. return (
  257. process.env.CAS_ENABLED === 'true' || process.env.CAS_ENABLED === true
  258. );
  259. }
  260. function isApiEnabled() {
  261. return process.env.WITH_API === 'true' || process.env.WITH_API === true;
  262. }
  263. Meteor.methods({
  264. sendInvitation(emails, boards) {
  265. check(emails, [String]);
  266. check(boards, [String]);
  267. const user = Users.findOne(Meteor.userId());
  268. if (!user.isAdmin) {
  269. throw new Meteor.Error('not-allowed');
  270. }
  271. emails.forEach(email => {
  272. if (email && SimpleSchema.RegEx.Email.test(email)) {
  273. // Checks if the email is already link to an account.
  274. const userExist = Users.findOne({ email });
  275. if (userExist) {
  276. throw new Meteor.Error(
  277. 'user-exist',
  278. `The user with the email ${email} has already an account.`,
  279. );
  280. }
  281. // Checks if the email is already link to an invitation.
  282. const invitation = InvitationCodes.findOne({ email });
  283. if (invitation) {
  284. InvitationCodes.update(invitation, {
  285. $set: { boardsToBeInvited: boards },
  286. });
  287. sendInvitationEmail(invitation._id);
  288. } else {
  289. const code = getRandomNum(100000, 999999);
  290. InvitationCodes.insert(
  291. {
  292. code,
  293. email,
  294. boardsToBeInvited: boards,
  295. createdAt: new Date(),
  296. authorId: Meteor.userId(),
  297. },
  298. function(err, _id) {
  299. if (!err && _id) {
  300. sendInvitationEmail(_id);
  301. } else {
  302. throw new Meteor.Error(
  303. 'invitation-generated-fail',
  304. err.message,
  305. );
  306. }
  307. },
  308. );
  309. }
  310. }
  311. });
  312. },
  313. sendSMTPTestEmail() {
  314. if (!Meteor.userId()) {
  315. throw new Meteor.Error('invalid-user');
  316. }
  317. const user = Meteor.user();
  318. if (!user.emails || !user.emails[0] || !user.emails[0].address) {
  319. throw new Meteor.Error('email-invalid');
  320. }
  321. this.unblock();
  322. const lang = user.getLanguage();
  323. try {
  324. if (process.env.MAIL_SERVICE !== '') {
  325. let transporter = nodemailer.createTransport({
  326. service: process.env.MAIL_SERVICE,
  327. auth: {
  328. user: process.env.MAIL_SERVICE_USER,
  329. pass: process.env.MAIL_SERVICE_PASSWORD
  330. },
  331. })
  332. let info = transporter.sendMail({
  333. to: user.emails[0].address,
  334. from: Accounts.emailTemplates.from,
  335. subject: TAPi18n.__('email-smtp-test-subject', { lng: lang }),
  336. text: TAPi18n.__('email-smtp-test-text', { lng: lang }),
  337. })
  338. } else {
  339. Email.send({
  340. to: user.emails[0].address,
  341. from: Accounts.emailTemplates.from,
  342. subject: TAPi18n.__('email-smtp-test-subject', { lng: lang }),
  343. text: TAPi18n.__('email-smtp-test-text', { lng: lang }),
  344. });
  345. }
  346. } catch ({ message }) {
  347. throw new Meteor.Error(
  348. 'email-fail',
  349. `${TAPi18n.__('email-fail-text', { lng: lang })}: ${message}`,
  350. message,
  351. );
  352. }
  353. return {
  354. message: 'email-sent',
  355. email: user.emails[0].address,
  356. };
  357. },
  358. getCustomUI() {
  359. const setting = Settings.findOne({});
  360. if (!setting.productName) {
  361. return {
  362. productName: '',
  363. };
  364. } else {
  365. return {
  366. productName: `${setting.productName}`,
  367. };
  368. }
  369. },
  370. getMatomoConf() {
  371. return {
  372. address: getEnvVar('MATOMO_ADDRESS'),
  373. siteId: getEnvVar('MATOMO_SITE_ID'),
  374. doNotTrack: process.env.MATOMO_DO_NOT_TRACK || false,
  375. withUserName: process.env.MATOMO_WITH_USERNAME || false,
  376. };
  377. },
  378. _isLdapEnabled() {
  379. return isLdapEnabled();
  380. },
  381. _isOauth2Enabled() {
  382. return isOauth2Enabled();
  383. },
  384. _isCasEnabled() {
  385. return isCasEnabled();
  386. },
  387. _isApiEnabled() {
  388. return isApiEnabled();
  389. },
  390. // Gets all connection methods to use it in the Template
  391. getAuthenticationsEnabled() {
  392. return {
  393. ldap: isLdapEnabled(),
  394. oauth2: isOauth2Enabled(),
  395. cas: isCasEnabled(),
  396. };
  397. },
  398. getDefaultAuthenticationMethod() {
  399. return process.env.DEFAULT_AUTHENTICATION_METHOD;
  400. },
  401. isPasswordLoginDisabled() {
  402. return process.env.PASSWORD_LOGIN_ENABLED === 'false';
  403. },
  404. });
  405. }
  406. export default Settings;