users.js 61 KB

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