users.js 57 KB

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