users.js 54 KB

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