users.js 48 KB

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