users.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  1. var nodemailer = require('nodemailer');
  2. import { SyncedCron } from 'meteor/percolate:synced-cron';
  3. import ImpersonatedUsers from './impersonatedUsers';
  4. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  5. // in the package definition.
  6. const isSandstorm =
  7. Meteor.settings && Meteor.settings.public && Meteor.settings.public.sandstorm;
  8. Users = Meteor.users;
  9. const allowedSortValues = [
  10. '-modifiedAt',
  11. 'modifiedAt',
  12. '-title',
  13. 'title',
  14. '-sort',
  15. 'sort',
  16. ];
  17. const defaultSortBy = allowedSortValues[0];
  18. /**
  19. * A User in wekan
  20. */
  21. Users.attachSchema(
  22. new SimpleSchema({
  23. username: {
  24. /**
  25. * the username of the user
  26. */
  27. type: String,
  28. optional: true,
  29. // eslint-disable-next-line consistent-return
  30. autoValue() {
  31. if (this.isInsert && !this.isSet) {
  32. const name = this.field('profile.fullname');
  33. if (name.isSet) {
  34. return name.value.toLowerCase().replace(/\s/g, '');
  35. }
  36. }
  37. },
  38. },
  39. orgs: {
  40. /**
  41. * the list of organizations that a user belongs to
  42. */
  43. type: [Object],
  44. optional: true,
  45. },
  46. 'orgs.$.orgId':{
  47. /**
  48. * The uniq ID of the organization
  49. */
  50. type: String,
  51. },
  52. 'orgs.$.orgDisplayName':{
  53. /**
  54. * The display name of the organization
  55. */
  56. type: String,
  57. },
  58. teams: {
  59. /**
  60. * the list of teams that a user belongs to
  61. */
  62. type: [Object],
  63. optional: true,
  64. },
  65. 'teams.$.teamId':{
  66. /**
  67. * The uniq ID of the team
  68. */
  69. type: String,
  70. },
  71. 'teams.$.teamDisplayName':{
  72. /**
  73. * The display name of the team
  74. */
  75. type: String,
  76. },
  77. emails: {
  78. /**
  79. * the list of emails attached to a user
  80. */
  81. type: [Object],
  82. optional: true,
  83. },
  84. 'emails.$.address': {
  85. /**
  86. * The email address
  87. */
  88. type: String,
  89. regEx: SimpleSchema.RegEx.Email,
  90. },
  91. 'emails.$.verified': {
  92. /**
  93. * Has the email been verified
  94. */
  95. type: Boolean,
  96. },
  97. createdAt: {
  98. /**
  99. * creation date of the user
  100. */
  101. type: Date,
  102. // eslint-disable-next-line consistent-return
  103. autoValue() {
  104. if (this.isInsert) {
  105. return new Date();
  106. } else if (this.isUpsert) {
  107. return {
  108. $setOnInsert: new Date(),
  109. };
  110. } else {
  111. this.unset();
  112. }
  113. },
  114. },
  115. modifiedAt: {
  116. type: Date,
  117. denyUpdate: false,
  118. // eslint-disable-next-line consistent-return
  119. autoValue() {
  120. if (this.isInsert || this.isUpsert || this.isUpdate) {
  121. return new Date();
  122. } else {
  123. this.unset();
  124. }
  125. },
  126. },
  127. profile: {
  128. /**
  129. * profile settings
  130. */
  131. type: Object,
  132. optional: true,
  133. // eslint-disable-next-line consistent-return
  134. autoValue() {
  135. if (this.isInsert && !this.isSet) {
  136. return {
  137. boardView: 'board-view-swimlanes',
  138. };
  139. }
  140. },
  141. },
  142. 'profile.avatarUrl': {
  143. /**
  144. * URL of the avatar of the user
  145. */
  146. type: String,
  147. optional: true,
  148. },
  149. 'profile.emailBuffer': {
  150. /**
  151. * list of email buffers of the user
  152. */
  153. type: [String],
  154. optional: true,
  155. },
  156. 'profile.fullname': {
  157. /**
  158. * full name of the user
  159. */
  160. type: String,
  161. optional: true,
  162. },
  163. 'profile.showDesktopDragHandles': {
  164. /**
  165. * does the user want to show desktop drag handles?
  166. */
  167. type: Boolean,
  168. optional: true,
  169. },
  170. 'profile.hideCheckedItems': {
  171. /**
  172. * does the user want to hide checked checklist items?
  173. */
  174. type: Boolean,
  175. optional: true,
  176. },
  177. 'profile.cardMaximized': {
  178. /**
  179. * has user clicked maximize card?
  180. */
  181. type: Boolean,
  182. optional: true,
  183. },
  184. 'profile.hiddenSystemMessages': {
  185. /**
  186. * does the user want to hide system messages?
  187. */
  188. type: Boolean,
  189. optional: true,
  190. },
  191. 'profile.hiddenMinicardLabelText': {
  192. /**
  193. * does the user want to hide minicard label texts?
  194. */
  195. type: Boolean,
  196. optional: true,
  197. },
  198. 'profile.initials': {
  199. /**
  200. * initials of the user
  201. */
  202. type: String,
  203. optional: true,
  204. },
  205. 'profile.invitedBoards': {
  206. /**
  207. * board IDs the user has been invited to
  208. */
  209. type: [String],
  210. optional: true,
  211. },
  212. 'profile.language': {
  213. /**
  214. * language of the user
  215. */
  216. type: String,
  217. optional: true,
  218. },
  219. 'profile.notifications': {
  220. /**
  221. * enabled notifications for the user
  222. */
  223. type: [Object],
  224. optional: true,
  225. },
  226. 'profile.notifications.$.activity': {
  227. /**
  228. * The id of the activity this notification references
  229. */
  230. type: String,
  231. },
  232. 'profile.notifications.$.read': {
  233. /**
  234. * the date on which this notification was read
  235. */
  236. type: Date,
  237. optional: true,
  238. },
  239. 'profile.showCardsCountAt': {
  240. /**
  241. * showCardCountAt field of the user
  242. */
  243. type: Number,
  244. optional: true,
  245. },
  246. 'profile.startDayOfWeek': {
  247. /**
  248. * startDayOfWeek field of the user
  249. */
  250. type: Number,
  251. optional: true,
  252. },
  253. 'profile.starredBoards': {
  254. /**
  255. * list of starred board IDs
  256. */
  257. type: [String],
  258. optional: true,
  259. },
  260. 'profile.icode': {
  261. /**
  262. * icode
  263. */
  264. type: String,
  265. optional: true,
  266. },
  267. 'profile.boardView': {
  268. /**
  269. * boardView field of the user
  270. */
  271. type: String,
  272. optional: true,
  273. allowedValues: [
  274. 'board-view-swimlanes',
  275. 'board-view-lists',
  276. 'board-view-cal',
  277. ],
  278. },
  279. 'profile.listSortBy': {
  280. /**
  281. * default sort list for user
  282. */
  283. type: String,
  284. optional: true,
  285. defaultValue: defaultSortBy,
  286. allowedValues: allowedSortValues,
  287. },
  288. 'profile.templatesBoardId': {
  289. /**
  290. * Reference to the templates board
  291. */
  292. type: String,
  293. defaultValue: '',
  294. },
  295. 'profile.cardTemplatesSwimlaneId': {
  296. /**
  297. * Reference to the card templates swimlane Id
  298. */
  299. type: String,
  300. defaultValue: '',
  301. },
  302. 'profile.listTemplatesSwimlaneId': {
  303. /**
  304. * Reference to the list templates swimlane Id
  305. */
  306. type: String,
  307. defaultValue: '',
  308. },
  309. 'profile.boardTemplatesSwimlaneId': {
  310. /**
  311. * Reference to the board templates swimlane Id
  312. */
  313. type: String,
  314. defaultValue: '',
  315. },
  316. services: {
  317. /**
  318. * services field of the user
  319. */
  320. type: Object,
  321. optional: true,
  322. blackbox: true,
  323. },
  324. heartbeat: {
  325. /**
  326. * last time the user has been seen
  327. */
  328. type: Date,
  329. optional: true,
  330. },
  331. isAdmin: {
  332. /**
  333. * is the user an admin of the board?
  334. */
  335. type: Boolean,
  336. optional: true,
  337. },
  338. createdThroughApi: {
  339. /**
  340. * was the user created through the API?
  341. */
  342. type: Boolean,
  343. optional: true,
  344. },
  345. loginDisabled: {
  346. /**
  347. * loginDisabled field of the user
  348. */
  349. type: Boolean,
  350. optional: true,
  351. },
  352. authenticationMethod: {
  353. /**
  354. * authentication method of the user
  355. */
  356. type: String,
  357. optional: false,
  358. defaultValue: 'password',
  359. },
  360. sessionData: {
  361. /**
  362. * profile settings
  363. */
  364. type: Object,
  365. optional: true,
  366. // eslint-disable-next-line consistent-return
  367. autoValue() {
  368. if (this.isInsert && !this.isSet) {
  369. return {};
  370. }
  371. },
  372. },
  373. 'sessionData.totalHits': {
  374. /**
  375. * Total hits from last searchquery['members.userId'] = Meteor.userId();
  376. * last hit that was returned
  377. */
  378. type: Number,
  379. optional: true,
  380. },
  381. importUsernames: {
  382. /**
  383. * username for imported
  384. */
  385. type: [String],
  386. optional: true,
  387. },
  388. }),
  389. );
  390. Users.allow({
  391. update(userId, doc) {
  392. const user = Users.findOne({
  393. _id: userId,
  394. });
  395. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  396. return true;
  397. if (!user) {
  398. return false;
  399. }
  400. return doc._id === userId;
  401. },
  402. remove(userId, doc) {
  403. const adminsNumber = Users.find({
  404. isAdmin: true,
  405. }).count();
  406. const { isAdmin } = Users.findOne(
  407. {
  408. _id: userId,
  409. },
  410. {
  411. fields: {
  412. isAdmin: 1,
  413. },
  414. },
  415. );
  416. // Prevents remove of the only one administrator
  417. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  418. return false;
  419. }
  420. // If it's the user or an admin
  421. return userId === doc._id || isAdmin;
  422. },
  423. fetch: [],
  424. });
  425. // Search a user in the complete server database by its name or username. This
  426. // is used for instance to add a new user to a board.
  427. const searchInFields = ['username', 'profile.fullname'];
  428. Users.initEasySearch(searchInFields, {
  429. use: 'mongo-db',
  430. returnFields: [...searchInFields, 'profile.avatarUrl'],
  431. });
  432. Users.safeFields = {
  433. _id: 1,
  434. username: 1,
  435. 'profile.fullname': 1,
  436. 'profile.avatarUrl': 1,
  437. 'profile.initials': 1,
  438. orgs: 1,
  439. teams: 1,
  440. };
  441. if (Meteor.isClient) {
  442. Users.helpers({
  443. isBoardMember() {
  444. const board = Boards.findOne(Session.get('currentBoard'));
  445. return board && board.hasMember(this._id);
  446. },
  447. isNotNoComments() {
  448. const board = Boards.findOne(Session.get('currentBoard'));
  449. return (
  450. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  451. );
  452. },
  453. isNoComments() {
  454. const board = Boards.findOne(Session.get('currentBoard'));
  455. return board && board.hasNoComments(this._id);
  456. },
  457. isNotCommentOnly() {
  458. const board = Boards.findOne(Session.get('currentBoard'));
  459. return (
  460. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  461. );
  462. },
  463. isCommentOnly() {
  464. const board = Boards.findOne(Session.get('currentBoard'));
  465. return board && board.hasCommentOnly(this._id);
  466. },
  467. isNotWorker() {
  468. const board = Boards.findOne(Session.get('currentBoard'));
  469. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  470. },
  471. isWorker() {
  472. const board = Boards.findOne(Session.get('currentBoard'));
  473. return board && board.hasWorker(this._id);
  474. },
  475. isBoardAdmin(boardId = Session.get('currentBoard')) {
  476. const board = Boards.findOne(boardId);
  477. return board && board.hasAdmin(this._id);
  478. },
  479. });
  480. }
  481. Users.parseImportUsernames = (usernamesString) => {
  482. return usernamesString.trim().split(new RegExp('\\s*[,;]\\s*'));
  483. };
  484. Users.helpers({
  485. importUsernamesString() {
  486. if (this.importUsernames) {
  487. return this.importUsernames.join(', ');
  488. }
  489. return '';
  490. },
  491. orgsUserBelongs() {
  492. if (this.orgs) {
  493. return this.orgs.map(function(org){return org.orgDisplayName}).join(',');
  494. }
  495. return '';
  496. },
  497. orgIdsUserBelongs() {
  498. if (this.orgs) {
  499. return this.orgs.map(function(org){return org.orgId}).join(',');
  500. }
  501. return '';
  502. },
  503. teamsUserBelongs() {
  504. if (this.teams) {
  505. return this.teams.map(function(team){ return team.teamDisplayName}).join(',');
  506. }
  507. return '';
  508. },
  509. teamIdsUserBelongs() {
  510. if (this.teams) {
  511. return this.teams.map(function(team){ return team.teamId}).join(',');
  512. }
  513. return '';
  514. },
  515. boards() {
  516. return Boards.find(
  517. {
  518. 'members.userId': this._id,
  519. },
  520. {
  521. sort: {
  522. sort: 1 /* boards default sorting */,
  523. },
  524. },
  525. );
  526. },
  527. starredBoards() {
  528. const { starredBoards = [] } = this.profile || {};
  529. return Boards.find(
  530. {
  531. archived: false,
  532. _id: {
  533. $in: starredBoards,
  534. },
  535. },
  536. {
  537. sort: {
  538. sort: 1 /* boards default sorting */,
  539. },
  540. },
  541. );
  542. },
  543. hasStarred(boardId) {
  544. const { starredBoards = [] } = this.profile || {};
  545. return _.contains(starredBoards, boardId);
  546. },
  547. invitedBoards() {
  548. const { invitedBoards = [] } = this.profile || {};
  549. return Boards.find(
  550. {
  551. archived: false,
  552. _id: {
  553. $in: invitedBoards,
  554. },
  555. },
  556. {
  557. sort: {
  558. sort: 1 /* boards default sorting */,
  559. },
  560. },
  561. );
  562. },
  563. isInvitedTo(boardId) {
  564. const { invitedBoards = [] } = this.profile || {};
  565. return _.contains(invitedBoards, boardId);
  566. },
  567. _getListSortBy() {
  568. const profile = this.profile || {};
  569. const sortBy = profile.listSortBy || defaultSortBy;
  570. const keyPattern = /^(-{0,1})(.*$)/;
  571. const ret = [];
  572. if (keyPattern.exec(sortBy)) {
  573. ret[0] = RegExp.$2;
  574. ret[1] = RegExp.$1 ? -1 : 1;
  575. }
  576. return ret;
  577. },
  578. hasSortBy() {
  579. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  580. return !this.hasShowDesktopDragHandles();
  581. },
  582. getListSortBy() {
  583. return this._getListSortBy()[0];
  584. },
  585. getListSortTypes() {
  586. return allowedSortValues;
  587. },
  588. getListSortByDirection() {
  589. return this._getListSortBy()[1];
  590. },
  591. hasTag(tag) {
  592. const { tags = [] } = this.profile || {};
  593. return _.contains(tags, tag);
  594. },
  595. hasNotification(activityId) {
  596. const { notifications = [] } = this.profile || {};
  597. return _.contains(notifications, activityId);
  598. },
  599. notifications() {
  600. const { notifications = [] } = this.profile || {};
  601. for (const index in notifications) {
  602. if (!notifications.hasOwnProperty(index)) continue;
  603. const notification = notifications[index];
  604. // this preserves their db sort order for editing
  605. notification.dbIndex = index;
  606. notification.activity = Activities.findOne(notification.activity);
  607. }
  608. // this sorts them newest to oldest to match Trello's behavior
  609. notifications.reverse();
  610. return notifications;
  611. },
  612. hasShowDesktopDragHandles() {
  613. const profile = this.profile || {};
  614. return profile.showDesktopDragHandles || false;
  615. },
  616. hasHideCheckedItems() {
  617. const profile = this.profile || {};
  618. return profile.hideCheckedItems || false;
  619. },
  620. hasHiddenSystemMessages() {
  621. const profile = this.profile || {};
  622. return profile.hiddenSystemMessages || false;
  623. },
  624. hasCardMaximized() {
  625. const profile = this.profile || {};
  626. return profile.cardMaximized || false;
  627. },
  628. hasHiddenMinicardLabelText() {
  629. const profile = this.profile || {};
  630. return profile.hiddenMinicardLabelText || false;
  631. },
  632. getEmailBuffer() {
  633. const { emailBuffer = [] } = this.profile || {};
  634. return emailBuffer;
  635. },
  636. getInitials() {
  637. const profile = this.profile || {};
  638. if (profile.initials) return profile.initials;
  639. else if (profile.fullname) {
  640. return profile.fullname
  641. .split(/\s+/)
  642. .reduce((memo, word) => {
  643. return memo + word[0];
  644. }, '')
  645. .toUpperCase();
  646. } else {
  647. return this.username[0].toUpperCase();
  648. }
  649. },
  650. getLimitToShowCardsCount() {
  651. const profile = this.profile || {};
  652. return profile.showCardsCountAt;
  653. },
  654. getName() {
  655. const profile = this.profile || {};
  656. return profile.fullname || this.username;
  657. },
  658. getLanguage() {
  659. const profile = this.profile || {};
  660. return profile.language || 'en';
  661. },
  662. getStartDayOfWeek() {
  663. const profile = this.profile || {};
  664. if (typeof profile.startDayOfWeek === 'undefined') {
  665. // default is 'Monday' (1)
  666. return 1;
  667. }
  668. return profile.startDayOfWeek;
  669. },
  670. getTemplatesBoardId() {
  671. return (this.profile || {}).templatesBoardId;
  672. },
  673. getTemplatesBoardSlug() {
  674. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  675. },
  676. remove() {
  677. User.remove({
  678. _id: this._id,
  679. });
  680. },
  681. });
  682. Users.mutations({
  683. toggleBoardStar(boardId) {
  684. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  685. return {
  686. [queryKind]: {
  687. 'profile.starredBoards': boardId,
  688. },
  689. };
  690. },
  691. addInvite(boardId) {
  692. return {
  693. $addToSet: {
  694. 'profile.invitedBoards': boardId,
  695. },
  696. };
  697. },
  698. removeInvite(boardId) {
  699. return {
  700. $pull: {
  701. 'profile.invitedBoards': boardId,
  702. },
  703. };
  704. },
  705. addTag(tag) {
  706. return {
  707. $addToSet: {
  708. 'profile.tags': tag,
  709. },
  710. };
  711. },
  712. removeTag(tag) {
  713. return {
  714. $pull: {
  715. 'profile.tags': tag,
  716. },
  717. };
  718. },
  719. toggleTag(tag) {
  720. if (this.hasTag(tag)) this.removeTag(tag);
  721. else this.addTag(tag);
  722. },
  723. setListSortBy(value) {
  724. return {
  725. $set: {
  726. 'profile.listSortBy': value,
  727. },
  728. };
  729. },
  730. setName(value) {
  731. return {
  732. $set: {
  733. 'profile.fullname': value,
  734. },
  735. };
  736. },
  737. toggleDesktopHandles(value = false) {
  738. return {
  739. $set: {
  740. 'profile.showDesktopDragHandles': !value,
  741. },
  742. };
  743. },
  744. toggleHideCheckedItems() {
  745. const value = this.hasHideCheckedItems();
  746. return {
  747. $set: {
  748. 'profile.hideCheckedItems': !value,
  749. },
  750. };
  751. },
  752. toggleSystem(value = false) {
  753. return {
  754. $set: {
  755. 'profile.hiddenSystemMessages': !value,
  756. },
  757. };
  758. },
  759. toggleCardMaximized(value = false) {
  760. return {
  761. $set: {
  762. 'profile.cardMaximized': !value,
  763. },
  764. };
  765. },
  766. toggleLabelText(value = false) {
  767. return {
  768. $set: {
  769. 'profile.hiddenMinicardLabelText': !value,
  770. },
  771. };
  772. },
  773. addNotification(activityId) {
  774. return {
  775. $addToSet: {
  776. 'profile.notifications': {
  777. activity: activityId,
  778. },
  779. },
  780. };
  781. },
  782. removeNotification(activityId) {
  783. return {
  784. $pull: {
  785. 'profile.notifications': {
  786. activity: activityId,
  787. },
  788. },
  789. };
  790. },
  791. addEmailBuffer(text) {
  792. return {
  793. $addToSet: {
  794. 'profile.emailBuffer': text,
  795. },
  796. };
  797. },
  798. clearEmailBuffer() {
  799. return {
  800. $set: {
  801. 'profile.emailBuffer': [],
  802. },
  803. };
  804. },
  805. setAvatarUrl(avatarUrl) {
  806. return {
  807. $set: {
  808. 'profile.avatarUrl': avatarUrl,
  809. },
  810. };
  811. },
  812. setShowCardsCountAt(limit) {
  813. return {
  814. $set: {
  815. 'profile.showCardsCountAt': limit,
  816. },
  817. };
  818. },
  819. setStartDayOfWeek(startDay) {
  820. return {
  821. $set: {
  822. 'profile.startDayOfWeek': startDay,
  823. },
  824. };
  825. },
  826. setBoardView(view) {
  827. return {
  828. $set: {
  829. 'profile.boardView': view,
  830. },
  831. };
  832. },
  833. });
  834. Meteor.methods({
  835. setListSortBy(value) {
  836. check(value, String);
  837. Meteor.user().setListSortBy(value);
  838. },
  839. toggleDesktopDragHandles() {
  840. const user = Meteor.user();
  841. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  842. },
  843. toggleHideCheckedItems() {
  844. const user = Meteor.user();
  845. user.toggleHideCheckedItems();
  846. },
  847. toggleSystemMessages() {
  848. const user = Meteor.user();
  849. user.toggleSystem(user.hasHiddenSystemMessages());
  850. },
  851. toggleCardMaximized() {
  852. const user = Meteor.user();
  853. user.toggleCardMaximized(user.hasCardMaximized());
  854. },
  855. toggleMinicardLabelText() {
  856. const user = Meteor.user();
  857. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  858. },
  859. changeLimitToShowCardsCount(limit) {
  860. check(limit, Number);
  861. Meteor.user().setShowCardsCountAt(limit);
  862. },
  863. changeStartDayOfWeek(startDay) {
  864. check(startDay, Number);
  865. Meteor.user().setStartDayOfWeek(startDay);
  866. },
  867. });
  868. if (Meteor.isServer) {
  869. Meteor.methods({
  870. setAllUsersHideSystemMessages() {
  871. if (Meteor.user() && Meteor.user().isAdmin) {
  872. // If setting is missing, add it
  873. Users.update(
  874. {
  875. 'profile.hiddenSystemMessages': {
  876. $exists: false,
  877. },
  878. },
  879. {
  880. $set: {
  881. 'profile.hiddenSystemMessages': true,
  882. },
  883. },
  884. {
  885. multi: true,
  886. },
  887. );
  888. // If setting is false, set it to true
  889. Users.update(
  890. {
  891. 'profile.hiddenSystemMessages': false,
  892. },
  893. {
  894. $set: {
  895. 'profile.hiddenSystemMessages': true,
  896. },
  897. },
  898. {
  899. multi: true,
  900. },
  901. );
  902. return true;
  903. } else {
  904. return false;
  905. }
  906. },
  907. setCreateUser(
  908. fullname,
  909. username,
  910. initials,
  911. password,
  912. isAdmin,
  913. isActive,
  914. email,
  915. importUsernames,
  916. userOrgsArray,
  917. userTeamsArray,
  918. ) {
  919. check(fullname, String);
  920. check(username, String);
  921. check(initials, String);
  922. check(password, String);
  923. check(isAdmin, String);
  924. check(isActive, String);
  925. check(email, String);
  926. check(importUsernames, Array);
  927. check(userOrgsArray, Array);
  928. check(userTeamsArray, Array);
  929. if (Meteor.user() && Meteor.user().isAdmin) {
  930. const nUsersWithUsername = Users.find({
  931. username,
  932. }).count();
  933. const nUsersWithEmail = Users.find({
  934. email,
  935. }).count();
  936. if (nUsersWithUsername > 0) {
  937. throw new Meteor.Error('username-already-taken');
  938. } else if (nUsersWithEmail > 0) {
  939. throw new Meteor.Error('email-already-taken');
  940. } else {
  941. Accounts.createUser({
  942. username,
  943. password,
  944. isAdmin,
  945. isActive,
  946. email: email.toLowerCase(),
  947. from: 'admin',
  948. });
  949. const user =
  950. Users.findOne(username) ||
  951. Users.findOne({
  952. username,
  953. });
  954. if (user) {
  955. Users.update(user._id, {
  956. $set: {
  957. 'profile.fullname': fullname,
  958. importUsernames,
  959. 'profile.initials': initials,
  960. orgs: userOrgsArray,
  961. teams: userTeamsArray,
  962. },
  963. });
  964. }
  965. }
  966. }
  967. },
  968. setUsername(username, userId) {
  969. check(username, String);
  970. check(userId, String);
  971. if (Meteor.user() && Meteor.user().isAdmin) {
  972. const nUsersWithUsername = Users.find({
  973. username,
  974. }).count();
  975. if (nUsersWithUsername > 0) {
  976. throw new Meteor.Error('username-already-taken');
  977. } else {
  978. Users.update(userId, {
  979. $set: {
  980. username,
  981. },
  982. });
  983. }
  984. }
  985. },
  986. setEmail(email, userId) {
  987. check(email, String);
  988. check(username, String);
  989. if (Meteor.user() && Meteor.user().isAdmin) {
  990. if (Array.isArray(email)) {
  991. email = email.shift();
  992. }
  993. const existingUser = Users.findOne(
  994. {
  995. 'emails.address': email,
  996. },
  997. {
  998. fields: {
  999. _id: 1,
  1000. },
  1001. },
  1002. );
  1003. if (existingUser) {
  1004. throw new Meteor.Error('email-already-taken');
  1005. } else {
  1006. Users.update(userId, {
  1007. $set: {
  1008. emails: [
  1009. {
  1010. address: email,
  1011. verified: false,
  1012. },
  1013. ],
  1014. },
  1015. });
  1016. }
  1017. }
  1018. },
  1019. setUsernameAndEmail(username, email, userId) {
  1020. check(username, String);
  1021. check(email, String);
  1022. check(userId, String);
  1023. if (Meteor.user() && Meteor.user().isAdmin) {
  1024. if (Array.isArray(email)) {
  1025. email = email.shift();
  1026. }
  1027. Meteor.call('setUsername', username, userId);
  1028. Meteor.call('setEmail', email, userId);
  1029. }
  1030. },
  1031. setPassword(newPassword, userId) {
  1032. check(userId, String);
  1033. check(newPassword, String);
  1034. if (Meteor.user() && Meteor.user().isAdmin) {
  1035. if (Meteor.user().isAdmin) {
  1036. Accounts.setPassword(userId, newPassword);
  1037. }
  1038. }
  1039. },
  1040. setEmailVerified(email, verified, userId) {
  1041. check(email, String);
  1042. check(verified, Boolean);
  1043. check(userId, String);
  1044. if (Meteor.user() && Meteor.user().isAdmin) {
  1045. Users.update(userId, {
  1046. $set: {
  1047. emails: [
  1048. {
  1049. address: email,
  1050. verified,
  1051. },
  1052. ],
  1053. },
  1054. });
  1055. }
  1056. },
  1057. setInitials(initials, userId) {
  1058. check(initials, String);
  1059. check(userId, String);
  1060. if (Meteor.user() && Meteor.user().isAdmin) {
  1061. Users.update(userId, {
  1062. $set: {
  1063. 'profile.initials': initials,
  1064. },
  1065. });
  1066. }
  1067. },
  1068. // we accept userId, username, email
  1069. inviteUserToBoard(username, boardId) {
  1070. check(username, String);
  1071. check(boardId, String);
  1072. const inviter = Meteor.user();
  1073. const board = Boards.findOne(boardId);
  1074. const allowInvite =
  1075. inviter &&
  1076. board &&
  1077. board.members &&
  1078. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  1079. _.where(board.members, {
  1080. userId: inviter._id,
  1081. })[0].isActive;
  1082. // GitHub issue 2060
  1083. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  1084. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  1085. this.unblock();
  1086. const posAt = username.indexOf('@');
  1087. let user = null;
  1088. if (posAt >= 0) {
  1089. user = Users.findOne({
  1090. emails: {
  1091. $elemMatch: {
  1092. address: username,
  1093. },
  1094. },
  1095. });
  1096. } else {
  1097. user =
  1098. Users.findOne(username) ||
  1099. Users.findOne({
  1100. username,
  1101. });
  1102. }
  1103. if (user) {
  1104. if (user._id === inviter._id)
  1105. throw new Meteor.Error('error-user-notAllowSelf');
  1106. } else {
  1107. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  1108. if (
  1109. Settings.findOne({
  1110. disableRegistration: true,
  1111. })
  1112. ) {
  1113. throw new Meteor.Error('error-user-notCreated');
  1114. }
  1115. // Set in lowercase email before creating account
  1116. const email = username.toLowerCase();
  1117. username = email.substring(0, posAt);
  1118. const newUserId = Accounts.createUser({
  1119. username,
  1120. email,
  1121. });
  1122. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  1123. // assume new user speak same language with inviter
  1124. if (inviter.profile && inviter.profile.language) {
  1125. Users.update(newUserId, {
  1126. $set: {
  1127. 'profile.language': inviter.profile.language,
  1128. },
  1129. });
  1130. }
  1131. Accounts.sendEnrollmentEmail(newUserId);
  1132. user = Users.findOne(newUserId);
  1133. }
  1134. board.addMember(user._id);
  1135. user.addInvite(boardId);
  1136. //Check if there is a subtasks board
  1137. if (board.subtasksDefaultBoardId) {
  1138. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  1139. //If there is, also add user to that board
  1140. if (subBoard) {
  1141. subBoard.addMember(user._id);
  1142. user.addInvite(subBoard._id);
  1143. }
  1144. }
  1145. try {
  1146. const params = {
  1147. user: user.username,
  1148. inviter: inviter.username,
  1149. board: board.title,
  1150. url: board.absoluteUrl(),
  1151. };
  1152. const lang = user.getLanguage();
  1153. if (process.env.MAIL_SERVICE !== '') {
  1154. let transporter = nodemailer.createTransport({
  1155. service: process.env.MAIL_SERVICE,
  1156. auth: {
  1157. user: process.env.MAIL_SERVICE_USER,
  1158. pass: process.env.MAIL_SERVICE_PASSWORD
  1159. },
  1160. })
  1161. let info = transporter.sendMail({
  1162. to: user.emails[0].address.toLowerCase(),
  1163. from: Accounts.emailTemplates.from,
  1164. subject: TAPi18n.__('email-invite-subject', params, lang),
  1165. text: TAPi18n.__('email-invite-text', params, lang),
  1166. })
  1167. } else {
  1168. Email.send({
  1169. to: user.emails[0].address.toLowerCase(),
  1170. from: Accounts.emailTemplates.from,
  1171. subject: TAPi18n.__('email-invite-subject', params, lang),
  1172. text: TAPi18n.__('email-invite-text', params, lang),
  1173. });
  1174. }
  1175. } catch (e) {
  1176. throw new Meteor.Error('email-fail', e.message);
  1177. }
  1178. return {
  1179. username: user.username,
  1180. email: user.emails[0].address,
  1181. };
  1182. },
  1183. impersonate(userId) {
  1184. check(userId, String);
  1185. if (!Meteor.users.findOne(userId))
  1186. throw new Meteor.Error(404, 'User not found');
  1187. if (!Meteor.user().isAdmin)
  1188. throw new Meteor.Error(403, 'Permission denied');
  1189. ImpersonatedUsers.insert({ adminId: Meteor.user()._id, userId: userId, reason: 'clickedImpersonate' });
  1190. this.setUserId(userId);
  1191. },
  1192. isImpersonated(userId) {
  1193. check(userId, String);
  1194. const isImpersonated = ImpersonatedUsers.findOne({
  1195. userId: userId,
  1196. });
  1197. return isImpersonated;
  1198. },
  1199. });
  1200. Accounts.onCreateUser((options, user) => {
  1201. const userCount = Users.find().count();
  1202. if (userCount === 0) {
  1203. user.isAdmin = true;
  1204. return user;
  1205. }
  1206. if (user.services.oidc) {
  1207. let email = user.services.oidc.email;
  1208. if (Array.isArray(email)) {
  1209. email = email.shift();
  1210. }
  1211. email = email.toLowerCase();
  1212. user.username = user.services.oidc.username;
  1213. user.emails = [
  1214. {
  1215. address: email,
  1216. verified: true,
  1217. },
  1218. ];
  1219. const initials = user.services.oidc.fullname
  1220. .split(/\s+/)
  1221. .reduce((memo, word) => {
  1222. return memo + word[0];
  1223. }, '')
  1224. .toUpperCase();
  1225. user.profile = {
  1226. initials,
  1227. fullname: user.services.oidc.fullname,
  1228. boardView: 'board-view-swimlanes',
  1229. };
  1230. user.authenticationMethod = 'oauth2';
  1231. // see if any existing user has this email address or username, otherwise create new
  1232. const existingUser = Meteor.users.findOne({
  1233. $or: [
  1234. {
  1235. 'emails.address': email,
  1236. },
  1237. {
  1238. username: user.username,
  1239. },
  1240. ],
  1241. });
  1242. if (!existingUser) return user;
  1243. // copy across new service info
  1244. const service = _.keys(user.services)[0];
  1245. existingUser.services[service] = user.services[service];
  1246. existingUser.emails = user.emails;
  1247. existingUser.username = user.username;
  1248. existingUser.profile = user.profile;
  1249. existingUser.authenticationMethod = user.authenticationMethod;
  1250. Meteor.users.remove({
  1251. _id: user._id,
  1252. });
  1253. Meteor.users.remove({
  1254. _id: existingUser._id,
  1255. }); // is going to be created again
  1256. return existingUser;
  1257. }
  1258. if (options.from === 'admin') {
  1259. user.createdThroughApi = true;
  1260. return user;
  1261. }
  1262. const disableRegistration = Settings.findOne().disableRegistration;
  1263. // If this is the first Authentication by the ldap and self registration disabled
  1264. if (disableRegistration && options && options.ldap) {
  1265. user.authenticationMethod = 'ldap';
  1266. return user;
  1267. }
  1268. // If self registration enabled
  1269. if (!disableRegistration) {
  1270. return user;
  1271. }
  1272. if (!options || !options.profile) {
  1273. throw new Meteor.Error(
  1274. 'error-invitation-code-blank',
  1275. 'The invitation code is required',
  1276. );
  1277. }
  1278. const invitationCode = InvitationCodes.findOne({
  1279. code: options.profile.invitationcode,
  1280. email: options.email,
  1281. valid: true,
  1282. });
  1283. if (!invitationCode) {
  1284. throw new Meteor.Error(
  1285. 'error-invitation-code-not-exist',
  1286. // eslint-disable-next-line quotes
  1287. "The invitation code doesn't exist",
  1288. );
  1289. } else {
  1290. user.profile = {
  1291. icode: options.profile.invitationcode,
  1292. };
  1293. user.profile.boardView = 'board-view-swimlanes';
  1294. // Deletes the invitation code after the user was created successfully.
  1295. setTimeout(
  1296. Meteor.bindEnvironment(() => {
  1297. InvitationCodes.remove({
  1298. _id: invitationCode._id,
  1299. });
  1300. }),
  1301. 200,
  1302. );
  1303. return user;
  1304. }
  1305. });
  1306. }
  1307. const addCronJob = _.debounce(
  1308. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  1309. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  1310. const envRemoveAge =
  1311. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  1312. // default notifications will be removed 2 days after they are read
  1313. const defaultRemoveAge = 2;
  1314. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  1315. SyncedCron.add({
  1316. name: 'notification_cleanup',
  1317. schedule: (parser) => parser.text('every 1 days'),
  1318. job: () => {
  1319. for (const user of Users.find()) {
  1320. if (!user.profile || !user.profile.notifications) continue;
  1321. for (const notification of user.profile.notifications) {
  1322. if (notification.read) {
  1323. const removeDate = new Date(notification.read);
  1324. removeDate.setDate(removeDate.getDate() + removeAge);
  1325. if (removeDate <= new Date()) {
  1326. user.removeNotification(notification.activity);
  1327. }
  1328. }
  1329. }
  1330. }
  1331. },
  1332. });
  1333. SyncedCron.start();
  1334. }),
  1335. 500,
  1336. );
  1337. if (Meteor.isServer) {
  1338. // Let mongoDB ensure username unicity
  1339. Meteor.startup(() => {
  1340. allowedSortValues.forEach((value) => {
  1341. Lists._collection._ensureIndex(value);
  1342. });
  1343. Users._collection._ensureIndex({
  1344. modifiedAt: -1,
  1345. });
  1346. Users._collection._ensureIndex(
  1347. {
  1348. username: 1,
  1349. },
  1350. {
  1351. unique: true,
  1352. },
  1353. );
  1354. Meteor.defer(() => {
  1355. addCronJob();
  1356. });
  1357. });
  1358. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1359. // if admin is removed, board is removed.
  1360. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1361. // to use that board, and not have board deleted.
  1362. // Someone can be later changed to be admin of board, by making change to database.
  1363. // TODO: Add UI for changing someone as board admin.
  1364. //Users.before.remove((userId, doc) => {
  1365. // Boards
  1366. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1367. // .forEach((board) => {
  1368. // // If only one admin for the board
  1369. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1370. // Boards.remove(board._id);
  1371. // }
  1372. // });
  1373. //});
  1374. // Each board document contains the de-normalized number of users that have
  1375. // starred it. If the user star or unstar a board, we need to update this
  1376. // counter.
  1377. // We need to run this code on the server only, otherwise the incrementation
  1378. // will be done twice.
  1379. Users.after.update(function (userId, user, fieldNames) {
  1380. // The `starredBoards` list is hosted on the `profile` field. If this
  1381. // field hasn't been modificated we don't need to run this hook.
  1382. if (!_.contains(fieldNames, 'profile')) return;
  1383. // To calculate a diff of board starred ids, we get both the previous
  1384. // and the newly board ids list
  1385. function getStarredBoardsIds(doc) {
  1386. return doc.profile && doc.profile.starredBoards;
  1387. }
  1388. const oldIds = getStarredBoardsIds(this.previous);
  1389. const newIds = getStarredBoardsIds(user);
  1390. // The _.difference(a, b) method returns the values from a that are not in
  1391. // b. We use it to find deleted and newly inserted ids by using it in one
  1392. // direction and then in the other.
  1393. function incrementBoards(boardsIds, inc) {
  1394. boardsIds.forEach((boardId) => {
  1395. Boards.update(boardId, {
  1396. $inc: {
  1397. stars: inc,
  1398. },
  1399. });
  1400. });
  1401. }
  1402. incrementBoards(_.difference(oldIds, newIds), -1);
  1403. incrementBoards(_.difference(newIds, oldIds), +1);
  1404. });
  1405. // Override getUserId so that we can TODO get the current userId
  1406. const fakeUserId = new Meteor.EnvironmentVariable();
  1407. const getUserId = CollectionHooks.getUserId;
  1408. CollectionHooks.getUserId = () => {
  1409. return fakeUserId.get() || getUserId();
  1410. };
  1411. if (!isSandstorm) {
  1412. Users.after.insert((userId, doc) => {
  1413. const fakeUser = {
  1414. extendAutoValueContext: {
  1415. userId: doc._id,
  1416. },
  1417. };
  1418. fakeUserId.withValue(doc._id, () => {
  1419. /*
  1420. // Insert the Welcome Board
  1421. Boards.insert({
  1422. title: TAPi18n.__('welcome-board'),
  1423. permission: 'private',
  1424. }, fakeUser, (err, boardId) => {
  1425. Swimlanes.insert({
  1426. title: TAPi18n.__('welcome-swimlane'),
  1427. boardId,
  1428. sort: 1,
  1429. }, fakeUser);
  1430. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1431. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1432. });
  1433. });
  1434. */
  1435. // Insert Template Container
  1436. const Future = require('fibers/future');
  1437. const future1 = new Future();
  1438. const future2 = new Future();
  1439. const future3 = new Future();
  1440. Boards.insert(
  1441. {
  1442. title: TAPi18n.__('templates'),
  1443. permission: 'private',
  1444. type: 'template-container',
  1445. },
  1446. fakeUser,
  1447. (err, boardId) => {
  1448. // Insert the reference to our templates board
  1449. Users.update(fakeUserId.get(), {
  1450. $set: {
  1451. 'profile.templatesBoardId': boardId,
  1452. },
  1453. });
  1454. // Insert the card templates swimlane
  1455. Swimlanes.insert(
  1456. {
  1457. title: TAPi18n.__('card-templates-swimlane'),
  1458. boardId,
  1459. sort: 1,
  1460. type: 'template-container',
  1461. },
  1462. fakeUser,
  1463. (err, swimlaneId) => {
  1464. // Insert the reference to out card templates swimlane
  1465. Users.update(fakeUserId.get(), {
  1466. $set: {
  1467. 'profile.cardTemplatesSwimlaneId': swimlaneId,
  1468. },
  1469. });
  1470. future1.return();
  1471. },
  1472. );
  1473. // Insert the list templates swimlane
  1474. Swimlanes.insert(
  1475. {
  1476. title: TAPi18n.__('list-templates-swimlane'),
  1477. boardId,
  1478. sort: 2,
  1479. type: 'template-container',
  1480. },
  1481. fakeUser,
  1482. (err, swimlaneId) => {
  1483. // Insert the reference to out list templates swimlane
  1484. Users.update(fakeUserId.get(), {
  1485. $set: {
  1486. 'profile.listTemplatesSwimlaneId': swimlaneId,
  1487. },
  1488. });
  1489. future2.return();
  1490. },
  1491. );
  1492. // Insert the board templates swimlane
  1493. Swimlanes.insert(
  1494. {
  1495. title: TAPi18n.__('board-templates-swimlane'),
  1496. boardId,
  1497. sort: 3,
  1498. type: 'template-container',
  1499. },
  1500. fakeUser,
  1501. (err, swimlaneId) => {
  1502. // Insert the reference to out board templates swimlane
  1503. Users.update(fakeUserId.get(), {
  1504. $set: {
  1505. 'profile.boardTemplatesSwimlaneId': swimlaneId,
  1506. },
  1507. });
  1508. future3.return();
  1509. },
  1510. );
  1511. },
  1512. );
  1513. // HACK
  1514. future1.wait();
  1515. future2.wait();
  1516. future3.wait();
  1517. // End of Insert Template Container
  1518. });
  1519. });
  1520. }
  1521. Users.after.insert((userId, doc) => {
  1522. // HACK
  1523. doc = Users.findOne({
  1524. _id: doc._id,
  1525. });
  1526. if (doc.createdThroughApi) {
  1527. // The admin user should be able to create a user despite disabling registration because
  1528. // it is two different things (registration and creation).
  1529. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1530. // the disableRegistration check.
  1531. // Issue : https://github.com/wekan/wekan/issues/1232
  1532. // PR : https://github.com/wekan/wekan/pull/1251
  1533. Users.update(doc._id, {
  1534. $set: {
  1535. createdThroughApi: '',
  1536. },
  1537. });
  1538. return;
  1539. }
  1540. //invite user to corresponding boards
  1541. const disableRegistration = Settings.findOne().disableRegistration;
  1542. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1543. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1544. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1545. const invitationCode = InvitationCodes.findOne({
  1546. code: doc.profile.icode,
  1547. valid: true,
  1548. });
  1549. if (!invitationCode) {
  1550. throw new Meteor.Error('error-invitation-code-not-exist');
  1551. } else {
  1552. invitationCode.boardsToBeInvited.forEach((boardId) => {
  1553. const board = Boards.findOne(boardId);
  1554. board.addMember(doc._id);
  1555. });
  1556. if (!doc.profile) {
  1557. doc.profile = {};
  1558. }
  1559. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1560. Users.update(doc._id, {
  1561. $set: {
  1562. profile: doc.profile,
  1563. },
  1564. });
  1565. InvitationCodes.update(invitationCode._id, {
  1566. $set: {
  1567. valid: false,
  1568. },
  1569. });
  1570. }
  1571. }
  1572. });
  1573. }
  1574. // USERS REST API
  1575. if (Meteor.isServer) {
  1576. // Middleware which checks that API is enabled.
  1577. JsonRoutes.Middleware.use(function (req, res, next) {
  1578. const api = req.url.startsWith('/api');
  1579. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1580. return next();
  1581. } else {
  1582. res.writeHead(301, {
  1583. Location: '/',
  1584. });
  1585. return res.end();
  1586. }
  1587. });
  1588. /**
  1589. * @operation get_current_user
  1590. *
  1591. * @summary returns the current user
  1592. * @return_type Users
  1593. */
  1594. JsonRoutes.add('GET', '/api/user', function (req, res) {
  1595. try {
  1596. Authentication.checkLoggedIn(req.userId);
  1597. const data = Meteor.users.findOne({
  1598. _id: req.userId,
  1599. });
  1600. delete data.services;
  1601. // get all boards where the user is member of
  1602. let boards = Boards.find(
  1603. {
  1604. type: 'board',
  1605. 'members.userId': req.userId,
  1606. },
  1607. {
  1608. fields: {
  1609. _id: 1,
  1610. members: 1,
  1611. },
  1612. },
  1613. );
  1614. boards = boards.map((b) => {
  1615. const u = b.members.find((m) => m.userId === req.userId);
  1616. delete u.userId;
  1617. u.boardId = b._id;
  1618. return u;
  1619. });
  1620. data.boards = boards;
  1621. JsonRoutes.sendResult(res, {
  1622. code: 200,
  1623. data,
  1624. });
  1625. } catch (error) {
  1626. JsonRoutes.sendResult(res, {
  1627. code: 200,
  1628. data: error,
  1629. });
  1630. }
  1631. });
  1632. /**
  1633. * @operation get_all_users
  1634. *
  1635. * @summary return all the users
  1636. *
  1637. * @description Only the admin user (the first user) can call the REST API.
  1638. * @return_type [{ _id: string,
  1639. * username: string}]
  1640. */
  1641. JsonRoutes.add('GET', '/api/users', function (req, res) {
  1642. try {
  1643. Authentication.checkUserId(req.userId);
  1644. JsonRoutes.sendResult(res, {
  1645. code: 200,
  1646. data: Meteor.users.find({}).map(function (doc) {
  1647. return {
  1648. _id: doc._id,
  1649. username: doc.username,
  1650. };
  1651. }),
  1652. });
  1653. } catch (error) {
  1654. JsonRoutes.sendResult(res, {
  1655. code: 200,
  1656. data: error,
  1657. });
  1658. }
  1659. });
  1660. /**
  1661. * @operation get_user
  1662. *
  1663. * @summary get a given user
  1664. *
  1665. * @description Only the admin user (the first user) can call the REST API.
  1666. *
  1667. * @param {string} userId the user ID or username
  1668. * @return_type Users
  1669. */
  1670. JsonRoutes.add('GET', '/api/users/:userId', function (req, res) {
  1671. try {
  1672. Authentication.checkUserId(req.userId);
  1673. let id = req.params.userId;
  1674. let user = Meteor.users.findOne({
  1675. _id: id,
  1676. });
  1677. if (!user) {
  1678. user = Meteor.users.findOne({
  1679. username: id,
  1680. });
  1681. id = user._id;
  1682. }
  1683. // get all boards where the user is member of
  1684. let boards = Boards.find(
  1685. {
  1686. type: 'board',
  1687. 'members.userId': id,
  1688. },
  1689. {
  1690. fields: {
  1691. _id: 1,
  1692. members: 1,
  1693. },
  1694. },
  1695. );
  1696. boards = boards.map((b) => {
  1697. const u = b.members.find((m) => m.userId === id);
  1698. delete u.userId;
  1699. u.boardId = b._id;
  1700. return u;
  1701. });
  1702. user.boards = boards;
  1703. JsonRoutes.sendResult(res, {
  1704. code: 200,
  1705. data: user,
  1706. });
  1707. } catch (error) {
  1708. JsonRoutes.sendResult(res, {
  1709. code: 200,
  1710. data: error,
  1711. });
  1712. }
  1713. });
  1714. /**
  1715. * @operation edit_user
  1716. *
  1717. * @summary edit a given user
  1718. *
  1719. * @description Only the admin user (the first user) can call the REST API.
  1720. *
  1721. * Possible values for *action*:
  1722. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1723. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1724. * - `enableLogin`: Enable a user
  1725. *
  1726. * @param {string} userId the user ID
  1727. * @param {string} action the action
  1728. * @return_type {_id: string,
  1729. * title: string}
  1730. */
  1731. JsonRoutes.add('PUT', '/api/users/:userId', function (req, res) {
  1732. try {
  1733. Authentication.checkUserId(req.userId);
  1734. const id = req.params.userId;
  1735. const action = req.body.action;
  1736. let data = Meteor.users.findOne({
  1737. _id: id,
  1738. });
  1739. if (data !== undefined) {
  1740. if (action === 'takeOwnership') {
  1741. data = Boards.find(
  1742. {
  1743. 'members.userId': id,
  1744. 'members.isAdmin': true,
  1745. },
  1746. {
  1747. sort: {
  1748. sort: 1 /* boards default sorting */,
  1749. },
  1750. },
  1751. ).map(function (board) {
  1752. if (board.hasMember(req.userId)) {
  1753. board.removeMember(req.userId);
  1754. }
  1755. board.changeOwnership(id, req.userId);
  1756. return {
  1757. _id: board._id,
  1758. title: board.title,
  1759. };
  1760. });
  1761. } else {
  1762. if (action === 'disableLogin' && id !== req.userId) {
  1763. Users.update(
  1764. {
  1765. _id: id,
  1766. },
  1767. {
  1768. $set: {
  1769. loginDisabled: true,
  1770. 'services.resume.loginTokens': '',
  1771. },
  1772. },
  1773. );
  1774. } else if (action === 'enableLogin') {
  1775. Users.update(
  1776. {
  1777. _id: id,
  1778. },
  1779. {
  1780. $set: {
  1781. loginDisabled: '',
  1782. },
  1783. },
  1784. );
  1785. }
  1786. data = Meteor.users.findOne({
  1787. _id: id,
  1788. });
  1789. }
  1790. }
  1791. JsonRoutes.sendResult(res, {
  1792. code: 200,
  1793. data,
  1794. });
  1795. } catch (error) {
  1796. JsonRoutes.sendResult(res, {
  1797. code: 200,
  1798. data: error,
  1799. });
  1800. }
  1801. });
  1802. /**
  1803. * @operation add_board_member
  1804. * @tag Boards
  1805. *
  1806. * @summary Add New Board Member with Role
  1807. *
  1808. * @description Only the admin user (the first user) can call the REST API.
  1809. *
  1810. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1811. * to later change the permissions.
  1812. *
  1813. * @param {string} boardId the board ID
  1814. * @param {string} userId the user ID
  1815. * @param {boolean} isAdmin is the user an admin of the board
  1816. * @param {boolean} isNoComments disable comments
  1817. * @param {boolean} isCommentOnly only enable comments
  1818. * @return_type {_id: string,
  1819. * title: string}
  1820. */
  1821. JsonRoutes.add(
  1822. 'POST',
  1823. '/api/boards/:boardId/members/:userId/add',
  1824. function (req, res) {
  1825. try {
  1826. Authentication.checkUserId(req.userId);
  1827. const userId = req.params.userId;
  1828. const boardId = req.params.boardId;
  1829. const action = req.body.action;
  1830. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1831. let data = Meteor.users.findOne({
  1832. _id: userId,
  1833. });
  1834. if (data !== undefined) {
  1835. if (action === 'add') {
  1836. data = Boards.find({
  1837. _id: boardId,
  1838. }).map(function (board) {
  1839. if (!board.hasMember(userId)) {
  1840. board.addMember(userId);
  1841. function isTrue(data) {
  1842. return data.toLowerCase() === 'true';
  1843. }
  1844. board.setMemberPermission(
  1845. userId,
  1846. isTrue(isAdmin),
  1847. isTrue(isNoComments),
  1848. isTrue(isCommentOnly),
  1849. userId,
  1850. );
  1851. }
  1852. return {
  1853. _id: board._id,
  1854. title: board.title,
  1855. };
  1856. });
  1857. }
  1858. }
  1859. JsonRoutes.sendResult(res, {
  1860. code: 200,
  1861. data: query,
  1862. });
  1863. } catch (error) {
  1864. JsonRoutes.sendResult(res, {
  1865. code: 200,
  1866. data: error,
  1867. });
  1868. }
  1869. },
  1870. );
  1871. /**
  1872. * @operation remove_board_member
  1873. * @tag Boards
  1874. *
  1875. * @summary Remove Member from Board
  1876. *
  1877. * @description Only the admin user (the first user) can call the REST API.
  1878. *
  1879. * @param {string} boardId the board ID
  1880. * @param {string} userId the user ID
  1881. * @param {string} action the action (needs to be `remove`)
  1882. * @return_type {_id: string,
  1883. * title: string}
  1884. */
  1885. JsonRoutes.add(
  1886. 'POST',
  1887. '/api/boards/:boardId/members/:userId/remove',
  1888. function (req, res) {
  1889. try {
  1890. Authentication.checkUserId(req.userId);
  1891. const userId = req.params.userId;
  1892. const boardId = req.params.boardId;
  1893. const action = req.body.action;
  1894. let data = Meteor.users.findOne({
  1895. _id: userId,
  1896. });
  1897. if (data !== undefined) {
  1898. if (action === 'remove') {
  1899. data = Boards.find({
  1900. _id: boardId,
  1901. }).map(function (board) {
  1902. if (board.hasMember(userId)) {
  1903. board.removeMember(userId);
  1904. }
  1905. return {
  1906. _id: board._id,
  1907. title: board.title,
  1908. };
  1909. });
  1910. }
  1911. }
  1912. JsonRoutes.sendResult(res, {
  1913. code: 200,
  1914. data: query,
  1915. });
  1916. } catch (error) {
  1917. JsonRoutes.sendResult(res, {
  1918. code: 200,
  1919. data: error,
  1920. });
  1921. }
  1922. },
  1923. );
  1924. /**
  1925. * @operation new_user
  1926. *
  1927. * @summary Create a new user
  1928. *
  1929. * @description Only the admin user (the first user) can call the REST API.
  1930. *
  1931. * @param {string} username the new username
  1932. * @param {string} email the email of the new user
  1933. * @param {string} password the password of the new user
  1934. * @return_type {_id: string}
  1935. */
  1936. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  1937. try {
  1938. Authentication.checkUserId(req.userId);
  1939. const id = Accounts.createUser({
  1940. username: req.body.username,
  1941. email: req.body.email,
  1942. password: req.body.password,
  1943. from: 'admin',
  1944. });
  1945. JsonRoutes.sendResult(res, {
  1946. code: 200,
  1947. data: {
  1948. _id: id,
  1949. },
  1950. });
  1951. } catch (error) {
  1952. JsonRoutes.sendResult(res, {
  1953. code: 200,
  1954. data: error,
  1955. });
  1956. }
  1957. });
  1958. /**
  1959. * @operation delete_user
  1960. *
  1961. * @summary Delete a user
  1962. *
  1963. * @description Only the admin user (the first user) can call the REST API.
  1964. *
  1965. * @param {string} userId the ID of the user to delete
  1966. * @return_type {_id: string}
  1967. */
  1968. JsonRoutes.add('DELETE', '/api/users/:userId', function (req, res) {
  1969. try {
  1970. Authentication.checkUserId(req.userId);
  1971. const id = req.params.userId;
  1972. // Delete user is enabled, but is still has bug of leaving empty user avatars
  1973. // to boards: boards members, card members and assignees have
  1974. // empty users. So it would be better to delete user from all boards before
  1975. // deleting user.
  1976. // See:
  1977. // - wekan/client/components/settings/peopleBody.jade deleteButton
  1978. // - wekan/client/components/settings/peopleBody.js deleteButton
  1979. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  1980. // that does now remove member from board, card members and assignees correctly,
  1981. // but that should be used to remove user from all boards similarly
  1982. // - wekan/models/users.js Delete is not enabled
  1983. Meteor.users.remove({ _id: id });
  1984. JsonRoutes.sendResult(res, {
  1985. code: 200,
  1986. data: {
  1987. _id: id,
  1988. },
  1989. });
  1990. } catch (error) {
  1991. JsonRoutes.sendResult(res, {
  1992. code: 200,
  1993. data: error,
  1994. });
  1995. }
  1996. });
  1997. /**
  1998. * @operation create_user_token
  1999. *
  2000. * @summary Create a user token
  2001. *
  2002. * @description Only the admin user (the first user) can call the REST API.
  2003. *
  2004. * @param {string} userId the ID of the user to create token for.
  2005. * @return_type {_id: string}
  2006. */
  2007. JsonRoutes.add('POST', '/api/createtoken/:userId', function (req, res) {
  2008. try {
  2009. Authentication.checkUserId(req.userId);
  2010. const id = req.params.userId;
  2011. const token = Accounts._generateStampedLoginToken();
  2012. Accounts._insertLoginToken(id, token);
  2013. JsonRoutes.sendResult(res, {
  2014. code: 200,
  2015. data: {
  2016. _id: id,
  2017. authToken: token.token,
  2018. },
  2019. });
  2020. } catch (error) {
  2021. JsonRoutes.sendResult(res, {
  2022. code: 200,
  2023. data: error,
  2024. });
  2025. }
  2026. });
  2027. }
  2028. export default Users;