users.js 56 KB

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