users.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  1. import { SyncedCron } from 'meteor/percolate:synced-cron';
  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. Users = Meteor.users;
  7. const allowedSortValues = [
  8. '-modifiedAt',
  9. 'modifiedAt',
  10. '-title',
  11. 'title',
  12. '-sort',
  13. 'sort',
  14. ];
  15. const defaultSortBy = allowedSortValues[0];
  16. /**
  17. * A User in wekan
  18. */
  19. Users.attachSchema(
  20. new SimpleSchema({
  21. username: {
  22. /**
  23. * the username of the user
  24. */
  25. type: String,
  26. optional: true,
  27. // eslint-disable-next-line consistent-return
  28. autoValue() {
  29. if (this.isInsert && !this.isSet) {
  30. const name = this.field('profile.fullname');
  31. if (name.isSet) {
  32. return name.value.toLowerCase().replace(/\s/g, '');
  33. }
  34. }
  35. },
  36. },
  37. emails: {
  38. /**
  39. * the list of emails attached to a user
  40. */
  41. type: [Object],
  42. optional: true,
  43. },
  44. 'emails.$.address': {
  45. /**
  46. * The email address
  47. */
  48. type: String,
  49. regEx: SimpleSchema.RegEx.Email,
  50. },
  51. 'emails.$.verified': {
  52. /**
  53. * Has the email been verified
  54. */
  55. type: Boolean,
  56. },
  57. createdAt: {
  58. /**
  59. * creation date of the user
  60. */
  61. type: Date,
  62. // eslint-disable-next-line consistent-return
  63. autoValue() {
  64. if (this.isInsert) {
  65. return new Date();
  66. } else if (this.isUpsert) {
  67. return { $setOnInsert: new Date() };
  68. } else {
  69. this.unset();
  70. }
  71. },
  72. },
  73. modifiedAt: {
  74. type: Date,
  75. denyUpdate: false,
  76. // eslint-disable-next-line consistent-return
  77. autoValue() {
  78. if (this.isInsert || this.isUpsert || this.isUpdate) {
  79. return new Date();
  80. } else {
  81. this.unset();
  82. }
  83. },
  84. },
  85. profile: {
  86. /**
  87. * profile settings
  88. */
  89. type: Object,
  90. optional: true,
  91. // eslint-disable-next-line consistent-return
  92. autoValue() {
  93. if (this.isInsert && !this.isSet) {
  94. return {
  95. boardView: 'board-view-lists',
  96. };
  97. }
  98. },
  99. },
  100. 'profile.avatarUrl': {
  101. /**
  102. * URL of the avatar of the user
  103. */
  104. type: String,
  105. optional: true,
  106. },
  107. 'profile.emailBuffer': {
  108. /**
  109. * list of email buffers of the user
  110. */
  111. type: [String],
  112. optional: true,
  113. },
  114. 'profile.fullname': {
  115. /**
  116. * full name of the user
  117. */
  118. type: String,
  119. optional: true,
  120. },
  121. 'profile.showDesktopDragHandles': {
  122. /**
  123. * does the user want to hide system messages?
  124. */
  125. type: Boolean,
  126. optional: true,
  127. },
  128. 'profile.hiddenSystemMessages': {
  129. /**
  130. * does the user want to hide system messages?
  131. */
  132. type: Boolean,
  133. optional: true,
  134. },
  135. 'profile.hiddenMinicardLabelText': {
  136. /**
  137. * does the user want to hide minicard label texts?
  138. */
  139. type: Boolean,
  140. optional: true,
  141. },
  142. 'profile.initials': {
  143. /**
  144. * initials of the user
  145. */
  146. type: String,
  147. optional: true,
  148. },
  149. 'profile.invitedBoards': {
  150. /**
  151. * board IDs the user has been invited to
  152. */
  153. type: [String],
  154. optional: true,
  155. },
  156. 'profile.language': {
  157. /**
  158. * language of the user
  159. */
  160. type: String,
  161. optional: true,
  162. },
  163. 'profile.notifications': {
  164. /**
  165. * enabled notifications for the user
  166. */
  167. type: [Object],
  168. optional: true,
  169. },
  170. 'profile.notifications.$.activity': {
  171. /**
  172. * The id of the activity this notification references
  173. */
  174. type: String,
  175. },
  176. 'profile.notifications.$.read': {
  177. /**
  178. * the date on which this notification was read
  179. */
  180. type: Date,
  181. optional: true,
  182. },
  183. 'profile.showCardsCountAt': {
  184. /**
  185. * showCardCountAt field of the user
  186. */
  187. type: Number,
  188. optional: true,
  189. },
  190. 'profile.starredBoards': {
  191. /**
  192. * list of starred board IDs
  193. */
  194. type: [String],
  195. optional: true,
  196. },
  197. 'profile.icode': {
  198. /**
  199. * icode
  200. */
  201. type: String,
  202. optional: true,
  203. },
  204. 'profile.boardView': {
  205. /**
  206. * boardView field of the user
  207. */
  208. type: String,
  209. optional: true,
  210. allowedValues: [
  211. 'board-view-lists',
  212. 'board-view-swimlanes',
  213. 'board-view-cal',
  214. ],
  215. },
  216. 'profile.listSortBy': {
  217. /**
  218. * default sort list for user
  219. */
  220. type: String,
  221. optional: true,
  222. defaultValue: defaultSortBy,
  223. allowedValues: allowedSortValues,
  224. },
  225. 'profile.templatesBoardId': {
  226. /**
  227. * Reference to the templates board
  228. */
  229. type: String,
  230. defaultValue: '',
  231. },
  232. 'profile.cardTemplatesSwimlaneId': {
  233. /**
  234. * Reference to the card templates swimlane Id
  235. */
  236. type: String,
  237. defaultValue: '',
  238. },
  239. 'profile.listTemplatesSwimlaneId': {
  240. /**
  241. * Reference to the list templates swimlane Id
  242. */
  243. type: String,
  244. defaultValue: '',
  245. },
  246. 'profile.boardTemplatesSwimlaneId': {
  247. /**
  248. * Reference to the board templates swimlane Id
  249. */
  250. type: String,
  251. defaultValue: '',
  252. },
  253. services: {
  254. /**
  255. * services field of the user
  256. */
  257. type: Object,
  258. optional: true,
  259. blackbox: true,
  260. },
  261. heartbeat: {
  262. /**
  263. * last time the user has been seen
  264. */
  265. type: Date,
  266. optional: true,
  267. },
  268. isAdmin: {
  269. /**
  270. * is the user an admin of the board?
  271. */
  272. type: Boolean,
  273. optional: true,
  274. },
  275. createdThroughApi: {
  276. /**
  277. * was the user created through the API?
  278. */
  279. type: Boolean,
  280. optional: true,
  281. },
  282. loginDisabled: {
  283. /**
  284. * loginDisabled field of the user
  285. */
  286. type: Boolean,
  287. optional: true,
  288. },
  289. authenticationMethod: {
  290. /**
  291. * authentication method of the user
  292. */
  293. type: String,
  294. optional: false,
  295. defaultValue: 'password',
  296. },
  297. }),
  298. );
  299. Users.allow({
  300. update(userId, doc) {
  301. const user = Users.findOne({ _id: userId });
  302. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  303. return true;
  304. if (!user) {
  305. return false;
  306. }
  307. return doc._id === userId;
  308. },
  309. remove(userId, doc) {
  310. const adminsNumber = Users.find({ isAdmin: true }).count();
  311. const { isAdmin } = Users.findOne(
  312. { _id: userId },
  313. { fields: { isAdmin: 1 } },
  314. );
  315. // Prevents remove of the only one administrator
  316. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  317. return false;
  318. }
  319. // If it's the user or an admin
  320. return userId === doc._id || isAdmin;
  321. },
  322. fetch: [],
  323. });
  324. // Search a user in the complete server database by its name or username. This
  325. // is used for instance to add a new user to a board.
  326. const searchInFields = ['username', 'profile.fullname'];
  327. Users.initEasySearch(searchInFields, {
  328. use: 'mongo-db',
  329. returnFields: [...searchInFields, 'profile.avatarUrl'],
  330. });
  331. if (Meteor.isClient) {
  332. Users.helpers({
  333. isBoardMember() {
  334. const board = Boards.findOne(Session.get('currentBoard'));
  335. return board && board.hasMember(this._id);
  336. },
  337. isNotNoComments() {
  338. const board = Boards.findOne(Session.get('currentBoard'));
  339. return (
  340. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  341. );
  342. },
  343. isNoComments() {
  344. const board = Boards.findOne(Session.get('currentBoard'));
  345. return board && board.hasNoComments(this._id);
  346. },
  347. isNotCommentOnly() {
  348. const board = Boards.findOne(Session.get('currentBoard'));
  349. return (
  350. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  351. );
  352. },
  353. isCommentOnly() {
  354. const board = Boards.findOne(Session.get('currentBoard'));
  355. return board && board.hasCommentOnly(this._id);
  356. },
  357. isNotWorker() {
  358. const board = Boards.findOne(Session.get('currentBoard'));
  359. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  360. },
  361. isWorker() {
  362. const board = Boards.findOne(Session.get('currentBoard'));
  363. return board && board.hasWorker(this._id);
  364. },
  365. isBoardAdmin(boardId = Session.get('currentBoard')) {
  366. const board = Boards.findOne(boardId);
  367. return board && board.hasAdmin(this._id);
  368. },
  369. });
  370. }
  371. Users.helpers({
  372. boards() {
  373. return Boards.find({ 'members.userId': this._id });
  374. },
  375. starredBoards() {
  376. const { starredBoards = [] } = this.profile || {};
  377. return Boards.find({ archived: false, _id: { $in: starredBoards } });
  378. },
  379. hasStarred(boardId) {
  380. const { starredBoards = [] } = this.profile || {};
  381. return _.contains(starredBoards, boardId);
  382. },
  383. invitedBoards() {
  384. const { invitedBoards = [] } = this.profile || {};
  385. return Boards.find({ archived: false, _id: { $in: invitedBoards } });
  386. },
  387. isInvitedTo(boardId) {
  388. const { invitedBoards = [] } = this.profile || {};
  389. return _.contains(invitedBoards, boardId);
  390. },
  391. _getListSortBy() {
  392. const profile = this.profile || {};
  393. const sortBy = profile.listSortBy || defaultSortBy;
  394. const keyPattern = /^(-{0,1})(.*$)/;
  395. const ret = [];
  396. if (keyPattern.exec(sortBy)) {
  397. ret[0] = RegExp.$2;
  398. ret[1] = RegExp.$1 ? -1 : 1;
  399. }
  400. return ret;
  401. },
  402. hasSortBy() {
  403. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  404. return !this.hasShowDesktopDragHandles();
  405. },
  406. getListSortBy() {
  407. return this._getListSortBy()[0];
  408. },
  409. getListSortTypes() {
  410. return allowedSortValues;
  411. },
  412. getListSortByDirection() {
  413. return this._getListSortBy()[1];
  414. },
  415. hasTag(tag) {
  416. const { tags = [] } = this.profile || {};
  417. return _.contains(tags, tag);
  418. },
  419. hasNotification(activityId) {
  420. const { notifications = [] } = this.profile || {};
  421. return _.contains(notifications, activityId);
  422. },
  423. notifications() {
  424. const { notifications = [] } = this.profile || {};
  425. for (const index in notifications) {
  426. if (!notifications.hasOwnProperty(index)) continue;
  427. const notification = notifications[index];
  428. // this preserves their db sort order for editing
  429. notification.dbIndex = index;
  430. notification.activity = Activities.findOne(notification.activity);
  431. }
  432. // this sorts them newest to oldest to match Trello's behavior
  433. notifications.reverse();
  434. return notifications;
  435. },
  436. hasShowDesktopDragHandles() {
  437. const profile = this.profile || {};
  438. return profile.showDesktopDragHandles || false;
  439. },
  440. hasHiddenSystemMessages() {
  441. const profile = this.profile || {};
  442. return profile.hiddenSystemMessages || false;
  443. },
  444. hasHiddenMinicardLabelText() {
  445. const profile = this.profile || {};
  446. return profile.hiddenMinicardLabelText || false;
  447. },
  448. getEmailBuffer() {
  449. const { emailBuffer = [] } = this.profile || {};
  450. return emailBuffer;
  451. },
  452. getInitials() {
  453. const profile = this.profile || {};
  454. if (profile.initials) return profile.initials;
  455. else if (profile.fullname) {
  456. return profile.fullname
  457. .split(/\s+/)
  458. .reduce((memo, word) => {
  459. return memo + word[0];
  460. }, '')
  461. .toUpperCase();
  462. } else {
  463. return this.username[0].toUpperCase();
  464. }
  465. },
  466. getLimitToShowCardsCount() {
  467. const profile = this.profile || {};
  468. return profile.showCardsCountAt;
  469. },
  470. getName() {
  471. const profile = this.profile || {};
  472. return profile.fullname || this.username;
  473. },
  474. getLanguage() {
  475. const profile = this.profile || {};
  476. return profile.language || 'en';
  477. },
  478. getTemplatesBoardId() {
  479. return (this.profile || {}).templatesBoardId;
  480. },
  481. getTemplatesBoardSlug() {
  482. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  483. },
  484. remove() {
  485. User.remove({ _id: this._id });
  486. },
  487. });
  488. Users.mutations({
  489. toggleBoardStar(boardId) {
  490. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  491. return {
  492. [queryKind]: {
  493. 'profile.starredBoards': boardId,
  494. },
  495. };
  496. },
  497. addInvite(boardId) {
  498. return {
  499. $addToSet: {
  500. 'profile.invitedBoards': boardId,
  501. },
  502. };
  503. },
  504. removeInvite(boardId) {
  505. return {
  506. $pull: {
  507. 'profile.invitedBoards': boardId,
  508. },
  509. };
  510. },
  511. addTag(tag) {
  512. return {
  513. $addToSet: {
  514. 'profile.tags': tag,
  515. },
  516. };
  517. },
  518. removeTag(tag) {
  519. return {
  520. $pull: {
  521. 'profile.tags': tag,
  522. },
  523. };
  524. },
  525. toggleTag(tag) {
  526. if (this.hasTag(tag)) this.removeTag(tag);
  527. else this.addTag(tag);
  528. },
  529. setListSortBy(value) {
  530. return {
  531. $set: {
  532. 'profile.listSortBy': value,
  533. },
  534. };
  535. },
  536. toggleDesktopHandles(value = false) {
  537. return {
  538. $set: {
  539. 'profile.showDesktopDragHandles': !value,
  540. },
  541. };
  542. },
  543. toggleSystem(value = false) {
  544. return {
  545. $set: {
  546. 'profile.hiddenSystemMessages': !value,
  547. },
  548. };
  549. },
  550. toggleLabelText(value = false) {
  551. return {
  552. $set: {
  553. 'profile.hiddenMinicardLabelText': !value,
  554. },
  555. };
  556. },
  557. addNotification(activityId) {
  558. return {
  559. $addToSet: {
  560. 'profile.notifications': { activity: activityId },
  561. },
  562. };
  563. },
  564. removeNotification(activityId) {
  565. return {
  566. $pull: {
  567. 'profile.notifications': { activity: activityId },
  568. },
  569. };
  570. },
  571. addEmailBuffer(text) {
  572. return {
  573. $addToSet: {
  574. 'profile.emailBuffer': text,
  575. },
  576. };
  577. },
  578. clearEmailBuffer() {
  579. return {
  580. $set: {
  581. 'profile.emailBuffer': [],
  582. },
  583. };
  584. },
  585. setAvatarUrl(avatarUrl) {
  586. return { $set: { 'profile.avatarUrl': avatarUrl } };
  587. },
  588. setShowCardsCountAt(limit) {
  589. return { $set: { 'profile.showCardsCountAt': limit } };
  590. },
  591. setBoardView(view) {
  592. return {
  593. $set: {
  594. 'profile.boardView': view,
  595. },
  596. };
  597. },
  598. });
  599. Meteor.methods({
  600. setListSortBy(value) {
  601. check(value, String);
  602. Meteor.user().setListSortBy(value);
  603. },
  604. toggleDesktopDragHandles() {
  605. const user = Meteor.user();
  606. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  607. },
  608. toggleSystemMessages() {
  609. const user = Meteor.user();
  610. user.toggleSystem(user.hasHiddenSystemMessages());
  611. },
  612. toggleMinicardLabelText() {
  613. const user = Meteor.user();
  614. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  615. },
  616. changeLimitToShowCardsCount(limit) {
  617. check(limit, Number);
  618. Meteor.user().setShowCardsCountAt(limit);
  619. },
  620. });
  621. if (Meteor.isServer) {
  622. Meteor.methods({
  623. setCreateUser(fullname, username, password, isAdmin, isActive, email) {
  624. if (Meteor.user() && Meteor.user().isAdmin) {
  625. check(fullname, String);
  626. check(username, String);
  627. check(password, String);
  628. check(isAdmin, String);
  629. check(isActive, String);
  630. check(email, String);
  631. const nUsersWithUsername = Users.find({ username }).count();
  632. const nUsersWithEmail = Users.find({ email }).count();
  633. if (nUsersWithUsername > 0) {
  634. throw new Meteor.Error('username-already-taken');
  635. } else if (nUsersWithEmail > 0) {
  636. throw new Meteor.Error('email-already-taken');
  637. } else {
  638. Accounts.createUser({
  639. fullname,
  640. username,
  641. password,
  642. isAdmin,
  643. isActive,
  644. email: email.toLowerCase(),
  645. from: 'admin',
  646. });
  647. }
  648. }
  649. },
  650. setUsername(username, userId) {
  651. if (Meteor.user() && Meteor.user().isAdmin) {
  652. check(username, String);
  653. check(userId, String);
  654. const nUsersWithUsername = Users.find({ username }).count();
  655. if (nUsersWithUsername > 0) {
  656. throw new Meteor.Error('username-already-taken');
  657. } else {
  658. Users.update(userId, { $set: { username } });
  659. }
  660. }
  661. },
  662. setEmail(email, userId) {
  663. if (Meteor.user() && Meteor.user().isAdmin) {
  664. if (Array.isArray(email)) {
  665. email = email.shift();
  666. }
  667. check(email, String);
  668. const existingUser = Users.findOne(
  669. { 'emails.address': email },
  670. { fields: { _id: 1 } },
  671. );
  672. if (existingUser) {
  673. throw new Meteor.Error('email-already-taken');
  674. } else {
  675. Users.update(userId, {
  676. $set: {
  677. emails: [
  678. {
  679. address: email,
  680. verified: false,
  681. },
  682. ],
  683. },
  684. });
  685. }
  686. }
  687. },
  688. setUsernameAndEmail(username, email, userId) {
  689. if (Meteor.user() && Meteor.user().isAdmin) {
  690. check(username, String);
  691. if (Array.isArray(email)) {
  692. email = email.shift();
  693. }
  694. check(email, String);
  695. check(userId, String);
  696. Meteor.call('setUsername', username, userId);
  697. Meteor.call('setEmail', email, userId);
  698. }
  699. },
  700. setPassword(newPassword, userId) {
  701. if (Meteor.user() && Meteor.user().isAdmin) {
  702. check(userId, String);
  703. check(newPassword, String);
  704. if (Meteor.user().isAdmin) {
  705. Accounts.setPassword(userId, newPassword);
  706. }
  707. }
  708. },
  709. // we accept userId, username, email
  710. inviteUserToBoard(username, boardId) {
  711. check(username, String);
  712. check(boardId, String);
  713. const inviter = Meteor.user();
  714. const board = Boards.findOne(boardId);
  715. const allowInvite =
  716. inviter &&
  717. board &&
  718. board.members &&
  719. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  720. _.where(board.members, { userId: inviter._id })[0].isActive;
  721. // GitHub issue 2060
  722. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  723. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  724. this.unblock();
  725. const posAt = username.indexOf('@');
  726. let user = null;
  727. if (posAt >= 0) {
  728. user = Users.findOne({ emails: { $elemMatch: { address: username } } });
  729. } else {
  730. user = Users.findOne(username) || Users.findOne({ username });
  731. }
  732. if (user) {
  733. if (user._id === inviter._id)
  734. throw new Meteor.Error('error-user-notAllowSelf');
  735. } else {
  736. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  737. if (Settings.findOne({ disableRegistration: true })) {
  738. throw new Meteor.Error('error-user-notCreated');
  739. }
  740. // Set in lowercase email before creating account
  741. const email = username.toLowerCase();
  742. username = email.substring(0, posAt);
  743. const newUserId = Accounts.createUser({ username, email });
  744. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  745. // assume new user speak same language with inviter
  746. if (inviter.profile && inviter.profile.language) {
  747. Users.update(newUserId, {
  748. $set: {
  749. 'profile.language': inviter.profile.language,
  750. },
  751. });
  752. }
  753. Accounts.sendEnrollmentEmail(newUserId);
  754. user = Users.findOne(newUserId);
  755. }
  756. board.addMember(user._id);
  757. user.addInvite(boardId);
  758. //Check if there is a subtasks board
  759. if (board.subtasksDefaultBoardId) {
  760. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  761. //If there is, also add user to that board
  762. if (subBoard) {
  763. subBoard.addMember(user._id);
  764. user.addInvite(subBoard._id);
  765. }
  766. }
  767. try {
  768. const params = {
  769. user: user.username,
  770. inviter: inviter.username,
  771. board: board.title,
  772. url: board.absoluteUrl(),
  773. };
  774. const lang = user.getLanguage();
  775. Email.send({
  776. to: user.emails[0].address.toLowerCase(),
  777. from: Accounts.emailTemplates.from,
  778. subject: TAPi18n.__('email-invite-subject', params, lang),
  779. text: TAPi18n.__('email-invite-text', params, lang),
  780. });
  781. } catch (e) {
  782. throw new Meteor.Error('email-fail', e.message);
  783. }
  784. return { username: user.username, email: user.emails[0].address };
  785. },
  786. });
  787. Accounts.onCreateUser((options, user) => {
  788. const userCount = Users.find().count();
  789. if (userCount === 0) {
  790. user.isAdmin = true;
  791. return user;
  792. }
  793. if (user.services.oidc) {
  794. let email = user.services.oidc.email;
  795. if (Array.isArray(email)) {
  796. email = email.shift();
  797. }
  798. email = email.toLowerCase();
  799. user.username = user.services.oidc.username;
  800. user.emails = [{ address: email, verified: true }];
  801. const initials = user.services.oidc.fullname
  802. .match(/\b[a-zA-Z]/g)
  803. .join('')
  804. .toUpperCase();
  805. user.profile = {
  806. initials,
  807. fullname: user.services.oidc.fullname,
  808. boardView: 'board-view-lists',
  809. };
  810. user.authenticationMethod = 'oauth2';
  811. // see if any existing user has this email address or username, otherwise create new
  812. const existingUser = Meteor.users.findOne({
  813. $or: [{ 'emails.address': email }, { username: user.username }],
  814. });
  815. if (!existingUser) return user;
  816. // copy across new service info
  817. const service = _.keys(user.services)[0];
  818. existingUser.services[service] = user.services[service];
  819. existingUser.emails = user.emails;
  820. existingUser.username = user.username;
  821. existingUser.profile = user.profile;
  822. existingUser.authenticationMethod = user.authenticationMethod;
  823. Meteor.users.remove({ _id: existingUser._id }); // remove existing record
  824. return existingUser;
  825. }
  826. if (options.from === 'admin') {
  827. user.createdThroughApi = true;
  828. return user;
  829. }
  830. const disableRegistration = Settings.findOne().disableRegistration;
  831. // If this is the first Authentication by the ldap and self registration disabled
  832. if (disableRegistration && options && options.ldap) {
  833. user.authenticationMethod = 'ldap';
  834. return user;
  835. }
  836. // If self registration enabled
  837. if (!disableRegistration) {
  838. return user;
  839. }
  840. if (!options || !options.profile) {
  841. throw new Meteor.Error(
  842. 'error-invitation-code-blank',
  843. 'The invitation code is required',
  844. );
  845. }
  846. const invitationCode = InvitationCodes.findOne({
  847. code: options.profile.invitationcode,
  848. email: options.email,
  849. valid: true,
  850. });
  851. if (!invitationCode) {
  852. throw new Meteor.Error(
  853. 'error-invitation-code-not-exist',
  854. // eslint-disable-next-line quotes
  855. "The invitation code doesn't exist",
  856. );
  857. } else {
  858. user.profile = { icode: options.profile.invitationcode };
  859. user.profile.boardView = 'board-view-lists';
  860. // Deletes the invitation code after the user was created successfully.
  861. setTimeout(
  862. Meteor.bindEnvironment(() => {
  863. InvitationCodes.remove({ _id: invitationCode._id });
  864. }),
  865. 200,
  866. );
  867. return user;
  868. }
  869. });
  870. }
  871. const addCronJob = _.debounce(
  872. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  873. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  874. const envRemoveAge =
  875. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  876. // default notifications will be removed 2 days after they are read
  877. const defaultRemoveAge = 2;
  878. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  879. SyncedCron.add({
  880. name: 'notification_cleanup',
  881. schedule: parser => parser.text('every 1 days'),
  882. job: () => {
  883. for (const user of Users.find()) {
  884. if (!user.profile || !user.profile.notifications) continue;
  885. for (const notification of user.profile.notifications) {
  886. if (notification.read) {
  887. const removeDate = new Date(notification.read);
  888. removeDate.setDate(removeDate.getDate() + removeAge);
  889. if (removeDate <= new Date()) {
  890. user.removeNotification(notification.activity);
  891. }
  892. }
  893. }
  894. }
  895. },
  896. });
  897. SyncedCron.start();
  898. }),
  899. 500,
  900. );
  901. if (Meteor.isServer) {
  902. // Let mongoDB ensure username unicity
  903. Meteor.startup(() => {
  904. allowedSortValues.forEach(value => {
  905. Lists._collection._ensureIndex(value);
  906. });
  907. Users._collection._ensureIndex({ modifiedAt: -1 });
  908. Users._collection._ensureIndex(
  909. {
  910. username: 1,
  911. },
  912. { unique: true },
  913. );
  914. Meteor.defer(() => {
  915. addCronJob();
  916. });
  917. });
  918. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  919. // if admin is removed, board is removed.
  920. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  921. // to use that board, and not have board deleted.
  922. // Someone can be later changed to be admin of board, by making change to database.
  923. // TODO: Add UI for changing someone as board admin.
  924. //Users.before.remove((userId, doc) => {
  925. // Boards
  926. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  927. // .forEach((board) => {
  928. // // If only one admin for the board
  929. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  930. // Boards.remove(board._id);
  931. // }
  932. // });
  933. //});
  934. // Each board document contains the de-normalized number of users that have
  935. // starred it. If the user star or unstar a board, we need to update this
  936. // counter.
  937. // We need to run this code on the server only, otherwise the incrementation
  938. // will be done twice.
  939. Users.after.update(function(userId, user, fieldNames) {
  940. // The `starredBoards` list is hosted on the `profile` field. If this
  941. // field hasn't been modificated we don't need to run this hook.
  942. if (!_.contains(fieldNames, 'profile')) return;
  943. // To calculate a diff of board starred ids, we get both the previous
  944. // and the newly board ids list
  945. function getStarredBoardsIds(doc) {
  946. return doc.profile && doc.profile.starredBoards;
  947. }
  948. const oldIds = getStarredBoardsIds(this.previous);
  949. const newIds = getStarredBoardsIds(user);
  950. // The _.difference(a, b) method returns the values from a that are not in
  951. // b. We use it to find deleted and newly inserted ids by using it in one
  952. // direction and then in the other.
  953. function incrementBoards(boardsIds, inc) {
  954. boardsIds.forEach(boardId => {
  955. Boards.update(boardId, { $inc: { stars: inc } });
  956. });
  957. }
  958. incrementBoards(_.difference(oldIds, newIds), -1);
  959. incrementBoards(_.difference(newIds, oldIds), +1);
  960. });
  961. const fakeUserId = new Meteor.EnvironmentVariable();
  962. const getUserId = CollectionHooks.getUserId;
  963. CollectionHooks.getUserId = () => {
  964. return fakeUserId.get() || getUserId();
  965. };
  966. if (!isSandstorm) {
  967. Users.after.insert((userId, doc) => {
  968. const fakeUser = {
  969. extendAutoValueContext: {
  970. userId: doc._id,
  971. },
  972. };
  973. fakeUserId.withValue(doc._id, () => {
  974. /*
  975. // Insert the Welcome Board
  976. Boards.insert({
  977. title: TAPi18n.__('welcome-board'),
  978. permission: 'private',
  979. }, fakeUser, (err, boardId) => {
  980. Swimlanes.insert({
  981. title: TAPi18n.__('welcome-swimlane'),
  982. boardId,
  983. sort: 1,
  984. }, fakeUser);
  985. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  986. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  987. });
  988. });
  989. */
  990. Boards.insert(
  991. {
  992. title: TAPi18n.__('templates'),
  993. permission: 'private',
  994. type: 'template-container',
  995. },
  996. fakeUser,
  997. (err, boardId) => {
  998. // Insert the reference to our templates board
  999. Users.update(fakeUserId.get(), {
  1000. $set: { 'profile.templatesBoardId': boardId },
  1001. });
  1002. // Insert the card templates swimlane
  1003. Swimlanes.insert(
  1004. {
  1005. title: TAPi18n.__('card-templates-swimlane'),
  1006. boardId,
  1007. sort: 1,
  1008. type: 'template-container',
  1009. },
  1010. fakeUser,
  1011. (err, swimlaneId) => {
  1012. // Insert the reference to out card templates swimlane
  1013. Users.update(fakeUserId.get(), {
  1014. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1015. });
  1016. },
  1017. );
  1018. // Insert the list templates swimlane
  1019. Swimlanes.insert(
  1020. {
  1021. title: TAPi18n.__('list-templates-swimlane'),
  1022. boardId,
  1023. sort: 2,
  1024. type: 'template-container',
  1025. },
  1026. fakeUser,
  1027. (err, swimlaneId) => {
  1028. // Insert the reference to out list templates swimlane
  1029. Users.update(fakeUserId.get(), {
  1030. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1031. });
  1032. },
  1033. );
  1034. // Insert the board templates swimlane
  1035. Swimlanes.insert(
  1036. {
  1037. title: TAPi18n.__('board-templates-swimlane'),
  1038. boardId,
  1039. sort: 3,
  1040. type: 'template-container',
  1041. },
  1042. fakeUser,
  1043. (err, swimlaneId) => {
  1044. // Insert the reference to out board templates swimlane
  1045. Users.update(fakeUserId.get(), {
  1046. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1047. });
  1048. },
  1049. );
  1050. },
  1051. );
  1052. });
  1053. });
  1054. }
  1055. Users.after.insert((userId, doc) => {
  1056. if (doc.createdThroughApi) {
  1057. // The admin user should be able to create a user despite disabling registration because
  1058. // it is two different things (registration and creation).
  1059. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1060. // the disableRegistration check.
  1061. // Issue : https://github.com/wekan/wekan/issues/1232
  1062. // PR : https://github.com/wekan/wekan/pull/1251
  1063. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1064. return;
  1065. }
  1066. //invite user to corresponding boards
  1067. const disableRegistration = Settings.findOne().disableRegistration;
  1068. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1069. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1070. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1071. const invitationCode = InvitationCodes.findOne({
  1072. code: doc.profile.icode,
  1073. valid: true,
  1074. });
  1075. if (!invitationCode) {
  1076. throw new Meteor.Error('error-invitation-code-not-exist');
  1077. } else {
  1078. invitationCode.boardsToBeInvited.forEach(boardId => {
  1079. const board = Boards.findOne(boardId);
  1080. board.addMember(doc._id);
  1081. });
  1082. if (!doc.profile) {
  1083. doc.profile = {};
  1084. }
  1085. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1086. Users.update(doc._id, { $set: { profile: doc.profile } });
  1087. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1088. }
  1089. }
  1090. });
  1091. }
  1092. // USERS REST API
  1093. if (Meteor.isServer) {
  1094. // Middleware which checks that API is enabled.
  1095. JsonRoutes.Middleware.use(function(req, res, next) {
  1096. const api = req.url.startsWith('/api');
  1097. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1098. return next();
  1099. } else {
  1100. res.writeHead(301, { Location: '/' });
  1101. return res.end();
  1102. }
  1103. });
  1104. /**
  1105. * @operation get_current_user
  1106. *
  1107. * @summary returns the current user
  1108. * @return_type Users
  1109. */
  1110. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1111. try {
  1112. Authentication.checkLoggedIn(req.userId);
  1113. const data = Meteor.users.findOne({ _id: req.userId });
  1114. delete data.services;
  1115. JsonRoutes.sendResult(res, {
  1116. code: 200,
  1117. data,
  1118. });
  1119. } catch (error) {
  1120. JsonRoutes.sendResult(res, {
  1121. code: 200,
  1122. data: error,
  1123. });
  1124. }
  1125. });
  1126. /**
  1127. * @operation get_all_users
  1128. *
  1129. * @summary return all the users
  1130. *
  1131. * @description Only the admin user (the first user) can call the REST API.
  1132. * @return_type [{ _id: string,
  1133. * username: string}]
  1134. */
  1135. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1136. try {
  1137. Authentication.checkUserId(req.userId);
  1138. JsonRoutes.sendResult(res, {
  1139. code: 200,
  1140. data: Meteor.users.find({}).map(function(doc) {
  1141. return { _id: doc._id, username: doc.username };
  1142. }),
  1143. });
  1144. } catch (error) {
  1145. JsonRoutes.sendResult(res, {
  1146. code: 200,
  1147. data: error,
  1148. });
  1149. }
  1150. });
  1151. /**
  1152. * @operation get_user
  1153. *
  1154. * @summary get a given user
  1155. *
  1156. * @description Only the admin user (the first user) can call the REST API.
  1157. *
  1158. * @param {string} userId the user ID
  1159. * @return_type Users
  1160. */
  1161. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1162. try {
  1163. Authentication.checkUserId(req.userId);
  1164. const id = req.params.userId;
  1165. JsonRoutes.sendResult(res, {
  1166. code: 200,
  1167. data: Meteor.users.findOne({ _id: id }),
  1168. });
  1169. } catch (error) {
  1170. JsonRoutes.sendResult(res, {
  1171. code: 200,
  1172. data: error,
  1173. });
  1174. }
  1175. });
  1176. /**
  1177. * @operation edit_user
  1178. *
  1179. * @summary edit a given user
  1180. *
  1181. * @description Only the admin user (the first user) can call the REST API.
  1182. *
  1183. * Possible values for *action*:
  1184. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1185. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1186. * - `enableLogin`: Enable a user
  1187. *
  1188. * @param {string} userId the user ID
  1189. * @param {string} action the action
  1190. * @return_type {_id: string,
  1191. * title: string}
  1192. */
  1193. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1194. try {
  1195. Authentication.checkUserId(req.userId);
  1196. const id = req.params.userId;
  1197. const action = req.body.action;
  1198. let data = Meteor.users.findOne({ _id: id });
  1199. if (data !== undefined) {
  1200. if (action === 'takeOwnership') {
  1201. data = Boards.find({
  1202. 'members.userId': id,
  1203. 'members.isAdmin': true,
  1204. }).map(function(board) {
  1205. if (board.hasMember(req.userId)) {
  1206. board.removeMember(req.userId);
  1207. }
  1208. board.changeOwnership(id, req.userId);
  1209. return {
  1210. _id: board._id,
  1211. title: board.title,
  1212. };
  1213. });
  1214. } else {
  1215. if (action === 'disableLogin' && id !== req.userId) {
  1216. Users.update(
  1217. { _id: id },
  1218. {
  1219. $set: {
  1220. loginDisabled: true,
  1221. 'services.resume.loginTokens': '',
  1222. },
  1223. },
  1224. );
  1225. } else if (action === 'enableLogin') {
  1226. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1227. }
  1228. data = Meteor.users.findOne({ _id: id });
  1229. }
  1230. }
  1231. JsonRoutes.sendResult(res, {
  1232. code: 200,
  1233. data,
  1234. });
  1235. } catch (error) {
  1236. JsonRoutes.sendResult(res, {
  1237. code: 200,
  1238. data: error,
  1239. });
  1240. }
  1241. });
  1242. /**
  1243. * @operation add_board_member
  1244. * @tag Boards
  1245. *
  1246. * @summary Add New Board Member with Role
  1247. *
  1248. * @description Only the admin user (the first user) can call the REST API.
  1249. *
  1250. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1251. * to later change the permissions.
  1252. *
  1253. * @param {string} boardId the board ID
  1254. * @param {string} userId the user ID
  1255. * @param {boolean} isAdmin is the user an admin of the board
  1256. * @param {boolean} isNoComments disable comments
  1257. * @param {boolean} isCommentOnly only enable comments
  1258. * @return_type {_id: string,
  1259. * title: string}
  1260. */
  1261. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1262. req,
  1263. res,
  1264. ) {
  1265. try {
  1266. Authentication.checkUserId(req.userId);
  1267. const userId = req.params.userId;
  1268. const boardId = req.params.boardId;
  1269. const action = req.body.action;
  1270. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1271. let data = Meteor.users.findOne({ _id: userId });
  1272. if (data !== undefined) {
  1273. if (action === 'add') {
  1274. data = Boards.find({
  1275. _id: boardId,
  1276. }).map(function(board) {
  1277. if (!board.hasMember(userId)) {
  1278. board.addMember(userId);
  1279. function isTrue(data) {
  1280. return data.toLowerCase() === 'true';
  1281. }
  1282. board.setMemberPermission(
  1283. userId,
  1284. isTrue(isAdmin),
  1285. isTrue(isNoComments),
  1286. isTrue(isCommentOnly),
  1287. userId,
  1288. );
  1289. }
  1290. return {
  1291. _id: board._id,
  1292. title: board.title,
  1293. };
  1294. });
  1295. }
  1296. }
  1297. JsonRoutes.sendResult(res, {
  1298. code: 200,
  1299. data: query,
  1300. });
  1301. } catch (error) {
  1302. JsonRoutes.sendResult(res, {
  1303. code: 200,
  1304. data: error,
  1305. });
  1306. }
  1307. });
  1308. /**
  1309. * @operation remove_board_member
  1310. * @tag Boards
  1311. *
  1312. * @summary Remove Member from Board
  1313. *
  1314. * @description Only the admin user (the first user) can call the REST API.
  1315. *
  1316. * @param {string} boardId the board ID
  1317. * @param {string} userId the user ID
  1318. * @param {string} action the action (needs to be `remove`)
  1319. * @return_type {_id: string,
  1320. * title: string}
  1321. */
  1322. JsonRoutes.add(
  1323. 'POST',
  1324. '/api/boards/:boardId/members/:userId/remove',
  1325. function(req, res) {
  1326. try {
  1327. Authentication.checkUserId(req.userId);
  1328. const userId = req.params.userId;
  1329. const boardId = req.params.boardId;
  1330. const action = req.body.action;
  1331. let data = Meteor.users.findOne({ _id: userId });
  1332. if (data !== undefined) {
  1333. if (action === 'remove') {
  1334. data = Boards.find({
  1335. _id: boardId,
  1336. }).map(function(board) {
  1337. if (board.hasMember(userId)) {
  1338. board.removeMember(userId);
  1339. }
  1340. return {
  1341. _id: board._id,
  1342. title: board.title,
  1343. };
  1344. });
  1345. }
  1346. }
  1347. JsonRoutes.sendResult(res, {
  1348. code: 200,
  1349. data: query,
  1350. });
  1351. } catch (error) {
  1352. JsonRoutes.sendResult(res, {
  1353. code: 200,
  1354. data: error,
  1355. });
  1356. }
  1357. },
  1358. );
  1359. /**
  1360. * @operation new_user
  1361. *
  1362. * @summary Create a new user
  1363. *
  1364. * @description Only the admin user (the first user) can call the REST API.
  1365. *
  1366. * @param {string} username the new username
  1367. * @param {string} email the email of the new user
  1368. * @param {string} password the password of the new user
  1369. * @return_type {_id: string}
  1370. */
  1371. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1372. try {
  1373. Authentication.checkUserId(req.userId);
  1374. const id = Accounts.createUser({
  1375. username: req.body.username,
  1376. email: req.body.email,
  1377. password: req.body.password,
  1378. from: 'admin',
  1379. });
  1380. JsonRoutes.sendResult(res, {
  1381. code: 200,
  1382. data: {
  1383. _id: id,
  1384. },
  1385. });
  1386. } catch (error) {
  1387. JsonRoutes.sendResult(res, {
  1388. code: 200,
  1389. data: error,
  1390. });
  1391. }
  1392. });
  1393. /**
  1394. * @operation delete_user
  1395. *
  1396. * @summary Delete a user
  1397. *
  1398. * @description Only the admin user (the first user) can call the REST API.
  1399. *
  1400. * @param {string} userId the ID of the user to delete
  1401. * @return_type {_id: string}
  1402. */
  1403. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1404. try {
  1405. Authentication.checkUserId(req.userId);
  1406. const id = req.params.userId;
  1407. Meteor.users.remove({ _id: id });
  1408. JsonRoutes.sendResult(res, {
  1409. code: 200,
  1410. data: {
  1411. _id: id,
  1412. },
  1413. });
  1414. } catch (error) {
  1415. JsonRoutes.sendResult(res, {
  1416. code: 200,
  1417. data: error,
  1418. });
  1419. }
  1420. });
  1421. }
  1422. export default Users;