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', 'emails.address'];
  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. authenticationMethod: 1,
  441. };
  442. if (Meteor.isClient) {
  443. Users.helpers({
  444. isBoardMember() {
  445. const board = Boards.findOne(Session.get('currentBoard'));
  446. return board && board.hasMember(this._id);
  447. },
  448. isNotNoComments() {
  449. const board = Boards.findOne(Session.get('currentBoard'));
  450. return (
  451. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  452. );
  453. },
  454. isNoComments() {
  455. const board = Boards.findOne(Session.get('currentBoard'));
  456. return board && board.hasNoComments(this._id);
  457. },
  458. isNotCommentOnly() {
  459. const board = Boards.findOne(Session.get('currentBoard'));
  460. return (
  461. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  462. );
  463. },
  464. isCommentOnly() {
  465. const board = Boards.findOne(Session.get('currentBoard'));
  466. return board && board.hasCommentOnly(this._id);
  467. },
  468. isNotWorker() {
  469. const board = Boards.findOne(Session.get('currentBoard'));
  470. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  471. },
  472. isWorker() {
  473. const board = Boards.findOne(Session.get('currentBoard'));
  474. return board && board.hasWorker(this._id);
  475. },
  476. isBoardAdmin(boardId = Session.get('currentBoard')) {
  477. const board = Boards.findOne(boardId);
  478. return board && board.hasAdmin(this._id);
  479. },
  480. });
  481. }
  482. Users.parseImportUsernames = (usernamesString) => {
  483. return usernamesString.trim().split(new RegExp('\\s*[,;]\\s*'));
  484. };
  485. Users.helpers({
  486. importUsernamesString() {
  487. if (this.importUsernames) {
  488. return this.importUsernames.join(', ');
  489. }
  490. return '';
  491. },
  492. orgsUserBelongs() {
  493. if (this.orgs) {
  494. return this.orgs.map(function(org){return org.orgDisplayName}).join(',');
  495. }
  496. return '';
  497. },
  498. orgIdsUserBelongs() {
  499. if (this.orgs) {
  500. return this.orgs.map(function(org){return org.orgId}).join(',');
  501. }
  502. return '';
  503. },
  504. teamsUserBelongs() {
  505. if (this.teams) {
  506. return this.teams.map(function(team){ return team.teamDisplayName}).join(',');
  507. }
  508. return '';
  509. },
  510. teamIdsUserBelongs() {
  511. if (this.teams) {
  512. return this.teams.map(function(team){ return team.teamId}).join(',');
  513. }
  514. return '';
  515. },
  516. boards() {
  517. return Boards.find(
  518. {
  519. 'members.userId': this._id,
  520. },
  521. {
  522. sort: {
  523. sort: 1 /* boards default sorting */,
  524. },
  525. },
  526. );
  527. },
  528. starredBoards() {
  529. const { starredBoards = [] } = this.profile || {};
  530. return Boards.find(
  531. {
  532. archived: false,
  533. _id: {
  534. $in: starredBoards,
  535. },
  536. },
  537. {
  538. sort: {
  539. sort: 1 /* boards default sorting */,
  540. },
  541. },
  542. );
  543. },
  544. hasStarred(boardId) {
  545. const { starredBoards = [] } = this.profile || {};
  546. return _.contains(starredBoards, boardId);
  547. },
  548. invitedBoards() {
  549. const { invitedBoards = [] } = this.profile || {};
  550. return Boards.find(
  551. {
  552. archived: false,
  553. _id: {
  554. $in: invitedBoards,
  555. },
  556. },
  557. {
  558. sort: {
  559. sort: 1 /* boards default sorting */,
  560. },
  561. },
  562. );
  563. },
  564. isInvitedTo(boardId) {
  565. const { invitedBoards = [] } = this.profile || {};
  566. return _.contains(invitedBoards, boardId);
  567. },
  568. _getListSortBy() {
  569. const profile = this.profile || {};
  570. const sortBy = profile.listSortBy || defaultSortBy;
  571. const keyPattern = /^(-{0,1})(.*$)/;
  572. const ret = [];
  573. if (keyPattern.exec(sortBy)) {
  574. ret[0] = RegExp.$2;
  575. ret[1] = RegExp.$1 ? -1 : 1;
  576. }
  577. return ret;
  578. },
  579. hasSortBy() {
  580. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  581. return !this.hasShowDesktopDragHandles();
  582. },
  583. getListSortBy() {
  584. return this._getListSortBy()[0];
  585. },
  586. getListSortTypes() {
  587. return allowedSortValues;
  588. },
  589. getListSortByDirection() {
  590. return this._getListSortBy()[1];
  591. },
  592. hasTag(tag) {
  593. const { tags = [] } = this.profile || {};
  594. return _.contains(tags, tag);
  595. },
  596. hasNotification(activityId) {
  597. const { notifications = [] } = this.profile || {};
  598. return _.contains(notifications, activityId);
  599. },
  600. notifications() {
  601. const { notifications = [] } = this.profile || {};
  602. for (const index in notifications) {
  603. if (!notifications.hasOwnProperty(index)) continue;
  604. const notification = notifications[index];
  605. // this preserves their db sort order for editing
  606. notification.dbIndex = index;
  607. notification.activity = Activities.findOne(notification.activity);
  608. }
  609. // this sorts them newest to oldest to match Trello's behavior
  610. notifications.reverse();
  611. return notifications;
  612. },
  613. hasShowDesktopDragHandles() {
  614. const profile = this.profile || {};
  615. return profile.showDesktopDragHandles || false;
  616. },
  617. hasHideCheckedItems() {
  618. const profile = this.profile || {};
  619. return profile.hideCheckedItems || false;
  620. },
  621. hasHiddenSystemMessages() {
  622. const profile = this.profile || {};
  623. return profile.hiddenSystemMessages || false;
  624. },
  625. hasCardMaximized() {
  626. const profile = this.profile || {};
  627. return profile.cardMaximized || false;
  628. },
  629. hasHiddenMinicardLabelText() {
  630. const profile = this.profile || {};
  631. return profile.hiddenMinicardLabelText || false;
  632. },
  633. getEmailBuffer() {
  634. const { emailBuffer = [] } = this.profile || {};
  635. return emailBuffer;
  636. },
  637. getInitials() {
  638. const profile = this.profile || {};
  639. if (profile.initials) return profile.initials;
  640. else if (profile.fullname) {
  641. return profile.fullname
  642. .split(/\s+/)
  643. .reduce((memo, word) => {
  644. return memo + word[0];
  645. }, '')
  646. .toUpperCase();
  647. } else {
  648. return this.username[0].toUpperCase();
  649. }
  650. },
  651. getLimitToShowCardsCount() {
  652. const profile = this.profile || {};
  653. return profile.showCardsCountAt;
  654. },
  655. getName() {
  656. const profile = this.profile || {};
  657. return profile.fullname || this.username;
  658. },
  659. getLanguage() {
  660. const profile = this.profile || {};
  661. return profile.language || 'en';
  662. },
  663. getStartDayOfWeek() {
  664. const profile = this.profile || {};
  665. if (typeof profile.startDayOfWeek === 'undefined') {
  666. // default is 'Monday' (1)
  667. return 1;
  668. }
  669. return profile.startDayOfWeek;
  670. },
  671. getTemplatesBoardId() {
  672. return (this.profile || {}).templatesBoardId;
  673. },
  674. getTemplatesBoardSlug() {
  675. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  676. },
  677. remove() {
  678. User.remove({
  679. _id: this._id,
  680. });
  681. },
  682. });
  683. Users.mutations({
  684. toggleBoardStar(boardId) {
  685. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  686. return {
  687. [queryKind]: {
  688. 'profile.starredBoards': boardId,
  689. },
  690. };
  691. },
  692. addInvite(boardId) {
  693. return {
  694. $addToSet: {
  695. 'profile.invitedBoards': boardId,
  696. },
  697. };
  698. },
  699. removeInvite(boardId) {
  700. return {
  701. $pull: {
  702. 'profile.invitedBoards': boardId,
  703. },
  704. };
  705. },
  706. addTag(tag) {
  707. return {
  708. $addToSet: {
  709. 'profile.tags': tag,
  710. },
  711. };
  712. },
  713. removeTag(tag) {
  714. return {
  715. $pull: {
  716. 'profile.tags': tag,
  717. },
  718. };
  719. },
  720. toggleTag(tag) {
  721. if (this.hasTag(tag)) this.removeTag(tag);
  722. else this.addTag(tag);
  723. },
  724. setListSortBy(value) {
  725. return {
  726. $set: {
  727. 'profile.listSortBy': value,
  728. },
  729. };
  730. },
  731. setName(value) {
  732. return {
  733. $set: {
  734. 'profile.fullname': value,
  735. },
  736. };
  737. },
  738. toggleDesktopHandles(value = false) {
  739. return {
  740. $set: {
  741. 'profile.showDesktopDragHandles': !value,
  742. },
  743. };
  744. },
  745. toggleHideCheckedItems() {
  746. const value = this.hasHideCheckedItems();
  747. return {
  748. $set: {
  749. 'profile.hideCheckedItems': !value,
  750. },
  751. };
  752. },
  753. toggleSystem(value = false) {
  754. return {
  755. $set: {
  756. 'profile.hiddenSystemMessages': !value,
  757. },
  758. };
  759. },
  760. toggleCardMaximized(value = false) {
  761. return {
  762. $set: {
  763. 'profile.cardMaximized': !value,
  764. },
  765. };
  766. },
  767. toggleLabelText(value = false) {
  768. return {
  769. $set: {
  770. 'profile.hiddenMinicardLabelText': !value,
  771. },
  772. };
  773. },
  774. addNotification(activityId) {
  775. return {
  776. $addToSet: {
  777. 'profile.notifications': {
  778. activity: activityId,
  779. },
  780. },
  781. };
  782. },
  783. removeNotification(activityId) {
  784. return {
  785. $pull: {
  786. 'profile.notifications': {
  787. activity: activityId,
  788. },
  789. },
  790. };
  791. },
  792. addEmailBuffer(text) {
  793. return {
  794. $addToSet: {
  795. 'profile.emailBuffer': text,
  796. },
  797. };
  798. },
  799. clearEmailBuffer() {
  800. return {
  801. $set: {
  802. 'profile.emailBuffer': [],
  803. },
  804. };
  805. },
  806. setAvatarUrl(avatarUrl) {
  807. return {
  808. $set: {
  809. 'profile.avatarUrl': avatarUrl,
  810. },
  811. };
  812. },
  813. setShowCardsCountAt(limit) {
  814. return {
  815. $set: {
  816. 'profile.showCardsCountAt': limit,
  817. },
  818. };
  819. },
  820. setStartDayOfWeek(startDay) {
  821. return {
  822. $set: {
  823. 'profile.startDayOfWeek': startDay,
  824. },
  825. };
  826. },
  827. setBoardView(view) {
  828. return {
  829. $set: {
  830. 'profile.boardView': view,
  831. },
  832. };
  833. },
  834. });
  835. Meteor.methods({
  836. setListSortBy(value) {
  837. check(value, String);
  838. Meteor.user().setListSortBy(value);
  839. },
  840. toggleDesktopDragHandles() {
  841. const user = Meteor.user();
  842. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  843. },
  844. toggleHideCheckedItems() {
  845. const user = Meteor.user();
  846. user.toggleHideCheckedItems();
  847. },
  848. toggleSystemMessages() {
  849. const user = Meteor.user();
  850. user.toggleSystem(user.hasHiddenSystemMessages());
  851. },
  852. toggleCardMaximized() {
  853. const user = Meteor.user();
  854. user.toggleCardMaximized(user.hasCardMaximized());
  855. },
  856. toggleMinicardLabelText() {
  857. const user = Meteor.user();
  858. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  859. },
  860. changeLimitToShowCardsCount(limit) {
  861. check(limit, Number);
  862. Meteor.user().setShowCardsCountAt(limit);
  863. },
  864. changeStartDayOfWeek(startDay) {
  865. check(startDay, Number);
  866. Meteor.user().setStartDayOfWeek(startDay);
  867. },
  868. });
  869. if (Meteor.isServer) {
  870. Meteor.methods({
  871. setAllUsersHideSystemMessages() {
  872. if (Meteor.user() && Meteor.user().isAdmin) {
  873. // If setting is missing, add it
  874. Users.update(
  875. {
  876. 'profile.hiddenSystemMessages': {
  877. $exists: false,
  878. },
  879. },
  880. {
  881. $set: {
  882. 'profile.hiddenSystemMessages': true,
  883. },
  884. },
  885. {
  886. multi: true,
  887. },
  888. );
  889. // If setting is false, set it to true
  890. Users.update(
  891. {
  892. 'profile.hiddenSystemMessages': false,
  893. },
  894. {
  895. $set: {
  896. 'profile.hiddenSystemMessages': true,
  897. },
  898. },
  899. {
  900. multi: true,
  901. },
  902. );
  903. return true;
  904. } else {
  905. return false;
  906. }
  907. },
  908. setCreateUser(
  909. fullname,
  910. username,
  911. initials,
  912. password,
  913. isAdmin,
  914. isActive,
  915. email,
  916. importUsernames,
  917. userOrgsArray,
  918. userTeamsArray,
  919. ) {
  920. check(fullname, String);
  921. check(username, String);
  922. check(initials, String);
  923. check(password, String);
  924. check(isAdmin, String);
  925. check(isActive, String);
  926. check(email, String);
  927. check(importUsernames, Array);
  928. check(userOrgsArray, Array);
  929. check(userTeamsArray, Array);
  930. if (Meteor.user() && Meteor.user().isAdmin) {
  931. const nUsersWithUsername = Users.find({
  932. username,
  933. }).count();
  934. const nUsersWithEmail = Users.find({
  935. email,
  936. }).count();
  937. if (nUsersWithUsername > 0) {
  938. throw new Meteor.Error('username-already-taken');
  939. } else if (nUsersWithEmail > 0) {
  940. throw new Meteor.Error('email-already-taken');
  941. } else {
  942. Accounts.createUser({
  943. username,
  944. password,
  945. isAdmin,
  946. isActive,
  947. email: email.toLowerCase(),
  948. from: 'admin',
  949. });
  950. const user =
  951. Users.findOne(username) ||
  952. Users.findOne({
  953. username,
  954. });
  955. if (user) {
  956. Users.update(user._id, {
  957. $set: {
  958. 'profile.fullname': fullname,
  959. importUsernames,
  960. 'profile.initials': initials,
  961. orgs: userOrgsArray,
  962. teams: userTeamsArray,
  963. },
  964. });
  965. }
  966. }
  967. }
  968. },
  969. setUsername(username, userId) {
  970. check(username, String);
  971. check(userId, String);
  972. if (Meteor.user() && Meteor.user().isAdmin) {
  973. const nUsersWithUsername = Users.find({
  974. username,
  975. }).count();
  976. if (nUsersWithUsername > 0) {
  977. throw new Meteor.Error('username-already-taken');
  978. } else {
  979. Users.update(userId, {
  980. $set: {
  981. username,
  982. },
  983. });
  984. }
  985. }
  986. },
  987. setEmail(email, userId) {
  988. check(email, String);
  989. check(username, String);
  990. if (Meteor.user() && Meteor.user().isAdmin) {
  991. if (Array.isArray(email)) {
  992. email = email.shift();
  993. }
  994. const existingUser = Users.findOne(
  995. {
  996. 'emails.address': email,
  997. },
  998. {
  999. fields: {
  1000. _id: 1,
  1001. },
  1002. },
  1003. );
  1004. if (existingUser) {
  1005. throw new Meteor.Error('email-already-taken');
  1006. } else {
  1007. Users.update(userId, {
  1008. $set: {
  1009. emails: [
  1010. {
  1011. address: email,
  1012. verified: false,
  1013. },
  1014. ],
  1015. },
  1016. });
  1017. }
  1018. }
  1019. },
  1020. setUsernameAndEmail(username, email, userId) {
  1021. check(username, String);
  1022. check(email, String);
  1023. check(userId, String);
  1024. if (Meteor.user() && Meteor.user().isAdmin) {
  1025. if (Array.isArray(email)) {
  1026. email = email.shift();
  1027. }
  1028. Meteor.call('setUsername', username, userId);
  1029. Meteor.call('setEmail', email, userId);
  1030. }
  1031. },
  1032. setPassword(newPassword, userId) {
  1033. check(userId, String);
  1034. check(newPassword, String);
  1035. if (Meteor.user() && Meteor.user().isAdmin) {
  1036. if (Meteor.user().isAdmin) {
  1037. Accounts.setPassword(userId, newPassword);
  1038. }
  1039. }
  1040. },
  1041. setEmailVerified(email, verified, userId) {
  1042. check(email, String);
  1043. check(verified, Boolean);
  1044. check(userId, String);
  1045. if (Meteor.user() && Meteor.user().isAdmin) {
  1046. Users.update(userId, {
  1047. $set: {
  1048. emails: [
  1049. {
  1050. address: email,
  1051. verified,
  1052. },
  1053. ],
  1054. },
  1055. });
  1056. }
  1057. },
  1058. setInitials(initials, userId) {
  1059. check(initials, String);
  1060. check(userId, String);
  1061. if (Meteor.user() && Meteor.user().isAdmin) {
  1062. Users.update(userId, {
  1063. $set: {
  1064. 'profile.initials': initials,
  1065. },
  1066. });
  1067. }
  1068. },
  1069. // we accept userId, username, email
  1070. inviteUserToBoard(username, boardId) {
  1071. check(username, String);
  1072. check(boardId, String);
  1073. const inviter = Meteor.user();
  1074. const board = Boards.findOne(boardId);
  1075. const allowInvite =
  1076. inviter &&
  1077. board &&
  1078. board.members &&
  1079. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  1080. _.where(board.members, {
  1081. userId: inviter._id,
  1082. })[0].isActive;
  1083. // GitHub issue 2060
  1084. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  1085. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  1086. this.unblock();
  1087. const posAt = username.indexOf('@');
  1088. let user = null;
  1089. if (posAt >= 0) {
  1090. user = Users.findOne({
  1091. emails: {
  1092. $elemMatch: {
  1093. address: username,
  1094. },
  1095. },
  1096. });
  1097. } else {
  1098. user =
  1099. Users.findOne(username) ||
  1100. Users.findOne({
  1101. username,
  1102. });
  1103. }
  1104. if (user) {
  1105. if (user._id === inviter._id)
  1106. throw new Meteor.Error('error-user-notAllowSelf');
  1107. } else {
  1108. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  1109. if (
  1110. Settings.findOne({
  1111. disableRegistration: true,
  1112. })
  1113. ) {
  1114. throw new Meteor.Error('error-user-notCreated');
  1115. }
  1116. // Set in lowercase email before creating account
  1117. const email = username.toLowerCase();
  1118. username = email.substring(0, posAt);
  1119. const newUserId = Accounts.createUser({
  1120. username,
  1121. email,
  1122. });
  1123. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  1124. // assume new user speak same language with inviter
  1125. if (inviter.profile && inviter.profile.language) {
  1126. Users.update(newUserId, {
  1127. $set: {
  1128. 'profile.language': inviter.profile.language,
  1129. },
  1130. });
  1131. }
  1132. Accounts.sendEnrollmentEmail(newUserId);
  1133. user = Users.findOne(newUserId);
  1134. }
  1135. board.addMember(user._id);
  1136. user.addInvite(boardId);
  1137. //Check if there is a subtasks board
  1138. if (board.subtasksDefaultBoardId) {
  1139. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  1140. //If there is, also add user to that board
  1141. if (subBoard) {
  1142. subBoard.addMember(user._id);
  1143. user.addInvite(subBoard._id);
  1144. }
  1145. }
  1146. try {
  1147. const params = {
  1148. user: user.username,
  1149. inviter: inviter.username,
  1150. board: board.title,
  1151. url: board.absoluteUrl(),
  1152. };
  1153. const lang = user.getLanguage();
  1154. if (process.env.MAIL_SERVICE !== '') {
  1155. let transporter = nodemailer.createTransport({
  1156. service: process.env.MAIL_SERVICE,
  1157. auth: {
  1158. user: process.env.MAIL_SERVICE_USER,
  1159. pass: process.env.MAIL_SERVICE_PASSWORD
  1160. },
  1161. })
  1162. let info = transporter.sendMail({
  1163. to: user.emails[0].address.toLowerCase(),
  1164. from: Accounts.emailTemplates.from,
  1165. subject: TAPi18n.__('email-invite-subject', params, lang),
  1166. text: TAPi18n.__('email-invite-text', params, lang),
  1167. })
  1168. } else {
  1169. Email.send({
  1170. to: user.emails[0].address.toLowerCase(),
  1171. from: Accounts.emailTemplates.from,
  1172. subject: TAPi18n.__('email-invite-subject', params, lang),
  1173. text: TAPi18n.__('email-invite-text', params, lang),
  1174. });
  1175. }
  1176. } catch (e) {
  1177. throw new Meteor.Error('email-fail', e.message);
  1178. }
  1179. return {
  1180. username: user.username,
  1181. email: user.emails[0].address,
  1182. };
  1183. },
  1184. impersonate(userId) {
  1185. check(userId, String);
  1186. if (!Meteor.users.findOne(userId))
  1187. throw new Meteor.Error(404, 'User not found');
  1188. if (!Meteor.user().isAdmin)
  1189. throw new Meteor.Error(403, 'Permission denied');
  1190. ImpersonatedUsers.insert({ adminId: Meteor.user()._id, userId: userId, reason: 'clickedImpersonate' });
  1191. this.setUserId(userId);
  1192. },
  1193. isImpersonated(userId) {
  1194. check(userId, String);
  1195. const isImpersonated = ImpersonatedUsers.findOne({
  1196. userId: userId,
  1197. });
  1198. return isImpersonated;
  1199. },
  1200. });
  1201. Accounts.onCreateUser((options, user) => {
  1202. const userCount = Users.find().count();
  1203. if (userCount === 0) {
  1204. user.isAdmin = true;
  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;