users.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797
  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. setCreateUser(
  739. fullname,
  740. username,
  741. password,
  742. isAdmin,
  743. isActive,
  744. email,
  745. importUsernames,
  746. ) {
  747. if (Meteor.user() && Meteor.user().isAdmin) {
  748. check(fullname, String);
  749. check(username, String);
  750. check(password, String);
  751. check(isAdmin, String);
  752. check(isActive, String);
  753. check(email, String);
  754. check(importUsernames, Array);
  755. const nUsersWithUsername = Users.find({ username }).count();
  756. const nUsersWithEmail = Users.find({ email }).count();
  757. if (nUsersWithUsername > 0) {
  758. throw new Meteor.Error('username-already-taken');
  759. } else if (nUsersWithEmail > 0) {
  760. throw new Meteor.Error('email-already-taken');
  761. } else {
  762. Accounts.createUser({
  763. username,
  764. password,
  765. isAdmin,
  766. isActive,
  767. email: email.toLowerCase(),
  768. from: 'admin',
  769. });
  770. const user = Users.findOne(username) || Users.findOne({ username });
  771. if (user) {
  772. Users.update(user._id, {
  773. $set: { 'profile.fullname': fullname, importUsernames },
  774. });
  775. }
  776. }
  777. }
  778. },
  779. setUsername(username, userId) {
  780. if (Meteor.user() && Meteor.user().isAdmin) {
  781. check(username, String);
  782. check(userId, String);
  783. const nUsersWithUsername = Users.find({ username }).count();
  784. if (nUsersWithUsername > 0) {
  785. throw new Meteor.Error('username-already-taken');
  786. } else {
  787. Users.update(userId, { $set: { username } });
  788. }
  789. }
  790. },
  791. setEmail(email, userId) {
  792. if (Meteor.user() && Meteor.user().isAdmin) {
  793. if (Array.isArray(email)) {
  794. email = email.shift();
  795. }
  796. check(email, String);
  797. const existingUser = Users.findOne(
  798. { 'emails.address': email },
  799. { fields: { _id: 1 } },
  800. );
  801. if (existingUser) {
  802. throw new Meteor.Error('email-already-taken');
  803. } else {
  804. Users.update(userId, {
  805. $set: {
  806. emails: [
  807. {
  808. address: email,
  809. verified: false,
  810. },
  811. ],
  812. },
  813. });
  814. }
  815. }
  816. },
  817. setUsernameAndEmail(username, email, userId) {
  818. if (Meteor.user() && Meteor.user().isAdmin) {
  819. check(username, String);
  820. if (Array.isArray(email)) {
  821. email = email.shift();
  822. }
  823. check(email, String);
  824. check(userId, String);
  825. Meteor.call('setUsername', username, userId);
  826. Meteor.call('setEmail', email, userId);
  827. }
  828. },
  829. setPassword(newPassword, userId) {
  830. if (Meteor.user() && Meteor.user().isAdmin) {
  831. check(userId, String);
  832. check(newPassword, String);
  833. if (Meteor.user().isAdmin) {
  834. Accounts.setPassword(userId, newPassword);
  835. }
  836. }
  837. },
  838. setEmailVerified(email, verified, userId) {
  839. if (Meteor.user() && Meteor.user().isAdmin) {
  840. check(email, String);
  841. check(verified, Boolean);
  842. check(userId, String);
  843. Users.update(userId, {
  844. $set: {
  845. emails: [
  846. {
  847. address: email,
  848. verified,
  849. },
  850. ],
  851. },
  852. });
  853. }
  854. },
  855. setInitials(initials, userId) {
  856. if (Meteor.user() && Meteor.user().isAdmin) {
  857. check(initials, String);
  858. check(userId, String);
  859. Users.update(userId, {
  860. $set: {
  861. 'profile.initials': initials,
  862. },
  863. });
  864. }
  865. },
  866. // we accept userId, username, email
  867. inviteUserToBoard(username, boardId) {
  868. check(username, String);
  869. check(boardId, String);
  870. const inviter = Meteor.user();
  871. const board = Boards.findOne(boardId);
  872. const allowInvite =
  873. inviter &&
  874. board &&
  875. board.members &&
  876. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  877. _.where(board.members, { userId: inviter._id })[0].isActive;
  878. // GitHub issue 2060
  879. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  880. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  881. this.unblock();
  882. const posAt = username.indexOf('@');
  883. let user = null;
  884. if (posAt >= 0) {
  885. user = Users.findOne({ emails: { $elemMatch: { address: username } } });
  886. } else {
  887. user = Users.findOne(username) || Users.findOne({ username });
  888. }
  889. if (user) {
  890. if (user._id === inviter._id)
  891. throw new Meteor.Error('error-user-notAllowSelf');
  892. } else {
  893. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  894. if (Settings.findOne({ disableRegistration: true })) {
  895. throw new Meteor.Error('error-user-notCreated');
  896. }
  897. // Set in lowercase email before creating account
  898. const email = username.toLowerCase();
  899. username = email.substring(0, posAt);
  900. const newUserId = Accounts.createUser({ username, email });
  901. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  902. // assume new user speak same language with inviter
  903. if (inviter.profile && inviter.profile.language) {
  904. Users.update(newUserId, {
  905. $set: {
  906. 'profile.language': inviter.profile.language,
  907. },
  908. });
  909. }
  910. Accounts.sendEnrollmentEmail(newUserId);
  911. user = Users.findOne(newUserId);
  912. }
  913. board.addMember(user._id);
  914. user.addInvite(boardId);
  915. //Check if there is a subtasks board
  916. if (board.subtasksDefaultBoardId) {
  917. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  918. //If there is, also add user to that board
  919. if (subBoard) {
  920. subBoard.addMember(user._id);
  921. user.addInvite(subBoard._id);
  922. }
  923. }
  924. try {
  925. const params = {
  926. user: user.username,
  927. inviter: inviter.username,
  928. board: board.title,
  929. url: board.absoluteUrl(),
  930. };
  931. const lang = user.getLanguage();
  932. Email.send({
  933. to: user.emails[0].address.toLowerCase(),
  934. from: Accounts.emailTemplates.from,
  935. subject: TAPi18n.__('email-invite-subject', params, lang),
  936. text: TAPi18n.__('email-invite-text', params, lang),
  937. });
  938. } catch (e) {
  939. throw new Meteor.Error('email-fail', e.message);
  940. }
  941. return { username: user.username, email: user.emails[0].address };
  942. },
  943. impersonate(userId) {
  944. check(userId, String);
  945. if (!Meteor.users.findOne(userId))
  946. throw new Meteor.Error(404, 'User not found');
  947. if (!Meteor.user().isAdmin)
  948. throw new Meteor.Error(403, 'Permission denied');
  949. this.setUserId(userId);
  950. },
  951. });
  952. Accounts.onCreateUser((options, user) => {
  953. const userCount = Users.find().count();
  954. if (userCount === 0) {
  955. user.isAdmin = true;
  956. return user;
  957. }
  958. if (user.services.oidc) {
  959. let email = user.services.oidc.email;
  960. if (Array.isArray(email)) {
  961. email = email.shift();
  962. }
  963. email = email.toLowerCase();
  964. user.username = user.services.oidc.username;
  965. user.emails = [{ address: email, verified: true }];
  966. const initials = user.services.oidc.fullname
  967. .split(/\s+/)
  968. .reduce((memo, word) => {
  969. return memo + word[0];
  970. }, '')
  971. .toUpperCase();
  972. user.profile = {
  973. initials,
  974. fullname: user.services.oidc.fullname,
  975. boardView: 'board-view-swimlanes',
  976. };
  977. user.authenticationMethod = 'oauth2';
  978. // see if any existing user has this email address or username, otherwise create new
  979. const existingUser = Meteor.users.findOne({
  980. $or: [{ 'emails.address': email }, { username: user.username }],
  981. });
  982. if (!existingUser) return user;
  983. // copy across new service info
  984. const service = _.keys(user.services)[0];
  985. existingUser.services[service] = user.services[service];
  986. existingUser.emails = user.emails;
  987. existingUser.username = user.username;
  988. existingUser.profile = user.profile;
  989. existingUser.authenticationMethod = user.authenticationMethod;
  990. Meteor.users.remove({ _id: user._id });
  991. Meteor.users.remove({ _id: existingUser._id }); // is going to be created again
  992. return existingUser;
  993. }
  994. if (options.from === 'admin') {
  995. user.createdThroughApi = true;
  996. return user;
  997. }
  998. const disableRegistration = Settings.findOne().disableRegistration;
  999. // If this is the first Authentication by the ldap and self registration disabled
  1000. if (disableRegistration && options && options.ldap) {
  1001. user.authenticationMethod = 'ldap';
  1002. return user;
  1003. }
  1004. // If self registration enabled
  1005. if (!disableRegistration) {
  1006. return user;
  1007. }
  1008. if (!options || !options.profile) {
  1009. throw new Meteor.Error(
  1010. 'error-invitation-code-blank',
  1011. 'The invitation code is required',
  1012. );
  1013. }
  1014. const invitationCode = InvitationCodes.findOne({
  1015. code: options.profile.invitationcode,
  1016. email: options.email,
  1017. valid: true,
  1018. });
  1019. if (!invitationCode) {
  1020. throw new Meteor.Error(
  1021. 'error-invitation-code-not-exist',
  1022. // eslint-disable-next-line quotes
  1023. "The invitation code doesn't exist",
  1024. );
  1025. } else {
  1026. user.profile = { icode: options.profile.invitationcode };
  1027. user.profile.boardView = 'board-view-swimlanes';
  1028. // Deletes the invitation code after the user was created successfully.
  1029. setTimeout(
  1030. Meteor.bindEnvironment(() => {
  1031. InvitationCodes.remove({ _id: invitationCode._id });
  1032. }),
  1033. 200,
  1034. );
  1035. return user;
  1036. }
  1037. });
  1038. }
  1039. const addCronJob = _.debounce(
  1040. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  1041. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  1042. const envRemoveAge =
  1043. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  1044. // default notifications will be removed 2 days after they are read
  1045. const defaultRemoveAge = 2;
  1046. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  1047. SyncedCron.add({
  1048. name: 'notification_cleanup',
  1049. schedule: parser => parser.text('every 1 days'),
  1050. job: () => {
  1051. for (const user of Users.find()) {
  1052. if (!user.profile || !user.profile.notifications) continue;
  1053. for (const notification of user.profile.notifications) {
  1054. if (notification.read) {
  1055. const removeDate = new Date(notification.read);
  1056. removeDate.setDate(removeDate.getDate() + removeAge);
  1057. if (removeDate <= new Date()) {
  1058. user.removeNotification(notification.activity);
  1059. }
  1060. }
  1061. }
  1062. }
  1063. },
  1064. });
  1065. SyncedCron.start();
  1066. }),
  1067. 500,
  1068. );
  1069. if (Meteor.isServer) {
  1070. // Let mongoDB ensure username unicity
  1071. Meteor.startup(() => {
  1072. allowedSortValues.forEach(value => {
  1073. Lists._collection._ensureIndex(value);
  1074. });
  1075. Users._collection._ensureIndex({ modifiedAt: -1 });
  1076. Users._collection._ensureIndex(
  1077. {
  1078. username: 1,
  1079. },
  1080. { unique: true },
  1081. );
  1082. Meteor.defer(() => {
  1083. addCronJob();
  1084. });
  1085. });
  1086. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1087. // if admin is removed, board is removed.
  1088. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1089. // to use that board, and not have board deleted.
  1090. // Someone can be later changed to be admin of board, by making change to database.
  1091. // TODO: Add UI for changing someone as board admin.
  1092. //Users.before.remove((userId, doc) => {
  1093. // Boards
  1094. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1095. // .forEach((board) => {
  1096. // // If only one admin for the board
  1097. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1098. // Boards.remove(board._id);
  1099. // }
  1100. // });
  1101. //});
  1102. // Each board document contains the de-normalized number of users that have
  1103. // starred it. If the user star or unstar a board, we need to update this
  1104. // counter.
  1105. // We need to run this code on the server only, otherwise the incrementation
  1106. // will be done twice.
  1107. Users.after.update(function(userId, user, fieldNames) {
  1108. // The `starredBoards` list is hosted on the `profile` field. If this
  1109. // field hasn't been modificated we don't need to run this hook.
  1110. if (!_.contains(fieldNames, 'profile')) return;
  1111. // To calculate a diff of board starred ids, we get both the previous
  1112. // and the newly board ids list
  1113. function getStarredBoardsIds(doc) {
  1114. return doc.profile && doc.profile.starredBoards;
  1115. }
  1116. const oldIds = getStarredBoardsIds(this.previous);
  1117. const newIds = getStarredBoardsIds(user);
  1118. // The _.difference(a, b) method returns the values from a that are not in
  1119. // b. We use it to find deleted and newly inserted ids by using it in one
  1120. // direction and then in the other.
  1121. function incrementBoards(boardsIds, inc) {
  1122. boardsIds.forEach(boardId => {
  1123. Boards.update(boardId, { $inc: { stars: inc } });
  1124. });
  1125. }
  1126. incrementBoards(_.difference(oldIds, newIds), -1);
  1127. incrementBoards(_.difference(newIds, oldIds), +1);
  1128. });
  1129. // Override getUserId so that we can TODO get the current userId
  1130. const fakeUserId = new Meteor.EnvironmentVariable();
  1131. const getUserId = CollectionHooks.getUserId;
  1132. CollectionHooks.getUserId = () => {
  1133. return fakeUserId.get() || getUserId();
  1134. };
  1135. if (!isSandstorm) {
  1136. Users.after.insert((userId, doc) => {
  1137. const fakeUser = {
  1138. extendAutoValueContext: {
  1139. userId: doc._id,
  1140. },
  1141. };
  1142. fakeUserId.withValue(doc._id, () => {
  1143. /*
  1144. // Insert the Welcome Board
  1145. Boards.insert({
  1146. title: TAPi18n.__('welcome-board'),
  1147. permission: 'private',
  1148. }, fakeUser, (err, boardId) => {
  1149. Swimlanes.insert({
  1150. title: TAPi18n.__('welcome-swimlane'),
  1151. boardId,
  1152. sort: 1,
  1153. }, fakeUser);
  1154. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1155. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1156. });
  1157. });
  1158. */
  1159. const Future = require('fibers/future');
  1160. const future1 = new Future();
  1161. const future2 = new Future();
  1162. const future3 = new Future();
  1163. Boards.insert(
  1164. {
  1165. title: TAPi18n.__('templates'),
  1166. permission: 'private',
  1167. type: 'template-container',
  1168. },
  1169. fakeUser,
  1170. (err, boardId) => {
  1171. // Insert the reference to our templates board
  1172. Users.update(fakeUserId.get(), {
  1173. $set: { 'profile.templatesBoardId': boardId },
  1174. });
  1175. // Insert the card templates swimlane
  1176. Swimlanes.insert(
  1177. {
  1178. title: TAPi18n.__('card-templates-swimlane'),
  1179. boardId,
  1180. sort: 1,
  1181. type: 'template-container',
  1182. },
  1183. fakeUser,
  1184. (err, swimlaneId) => {
  1185. // Insert the reference to out card templates swimlane
  1186. Users.update(fakeUserId.get(), {
  1187. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1188. });
  1189. future1.return();
  1190. },
  1191. );
  1192. // Insert the list templates swimlane
  1193. Swimlanes.insert(
  1194. {
  1195. title: TAPi18n.__('list-templates-swimlane'),
  1196. boardId,
  1197. sort: 2,
  1198. type: 'template-container',
  1199. },
  1200. fakeUser,
  1201. (err, swimlaneId) => {
  1202. // Insert the reference to out list templates swimlane
  1203. Users.update(fakeUserId.get(), {
  1204. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1205. });
  1206. future2.return();
  1207. },
  1208. );
  1209. // Insert the board templates swimlane
  1210. Swimlanes.insert(
  1211. {
  1212. title: TAPi18n.__('board-templates-swimlane'),
  1213. boardId,
  1214. sort: 3,
  1215. type: 'template-container',
  1216. },
  1217. fakeUser,
  1218. (err, swimlaneId) => {
  1219. // Insert the reference to out board templates swimlane
  1220. Users.update(fakeUserId.get(), {
  1221. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1222. });
  1223. future3.return();
  1224. },
  1225. );
  1226. },
  1227. );
  1228. // HACK
  1229. future1.wait();
  1230. future2.wait();
  1231. future3.wait();
  1232. });
  1233. });
  1234. }
  1235. Users.after.insert((userId, doc) => {
  1236. // HACK
  1237. doc = Users.findOne({ _id: doc._id });
  1238. if (doc.createdThroughApi) {
  1239. // The admin user should be able to create a user despite disabling registration because
  1240. // it is two different things (registration and creation).
  1241. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1242. // the disableRegistration check.
  1243. // Issue : https://github.com/wekan/wekan/issues/1232
  1244. // PR : https://github.com/wekan/wekan/pull/1251
  1245. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1246. return;
  1247. }
  1248. //invite user to corresponding boards
  1249. const disableRegistration = Settings.findOne().disableRegistration;
  1250. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1251. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1252. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1253. const invitationCode = InvitationCodes.findOne({
  1254. code: doc.profile.icode,
  1255. valid: true,
  1256. });
  1257. if (!invitationCode) {
  1258. throw new Meteor.Error('error-invitation-code-not-exist');
  1259. } else {
  1260. invitationCode.boardsToBeInvited.forEach(boardId => {
  1261. const board = Boards.findOne(boardId);
  1262. board.addMember(doc._id);
  1263. });
  1264. if (!doc.profile) {
  1265. doc.profile = {};
  1266. }
  1267. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1268. Users.update(doc._id, { $set: { profile: doc.profile } });
  1269. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1270. }
  1271. }
  1272. });
  1273. }
  1274. // USERS REST API
  1275. if (Meteor.isServer) {
  1276. // Middleware which checks that API is enabled.
  1277. JsonRoutes.Middleware.use(function(req, res, next) {
  1278. const api = req.url.startsWith('/api');
  1279. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1280. return next();
  1281. } else {
  1282. res.writeHead(301, { Location: '/' });
  1283. return res.end();
  1284. }
  1285. });
  1286. /**
  1287. * @operation get_current_user
  1288. *
  1289. * @summary returns the current user
  1290. * @return_type Users
  1291. */
  1292. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1293. try {
  1294. Authentication.checkLoggedIn(req.userId);
  1295. const data = Meteor.users.findOne({ _id: req.userId });
  1296. delete data.services;
  1297. // get all boards where the user is member of
  1298. let boards = Boards.find(
  1299. {
  1300. type: 'board',
  1301. 'members.userId': req.userId,
  1302. },
  1303. {
  1304. fields: { _id: 1, members: 1 },
  1305. },
  1306. );
  1307. boards = boards.map(b => {
  1308. const u = b.members.find(m => m.userId === req.userId);
  1309. delete u.userId;
  1310. u.boardId = b._id;
  1311. return u;
  1312. });
  1313. data.boards = boards;
  1314. JsonRoutes.sendResult(res, {
  1315. code: 200,
  1316. data,
  1317. });
  1318. } catch (error) {
  1319. JsonRoutes.sendResult(res, {
  1320. code: 200,
  1321. data: error,
  1322. });
  1323. }
  1324. });
  1325. /**
  1326. * @operation get_all_users
  1327. *
  1328. * @summary return all the users
  1329. *
  1330. * @description Only the admin user (the first user) can call the REST API.
  1331. * @return_type [{ _id: string,
  1332. * username: string}]
  1333. */
  1334. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1335. try {
  1336. Authentication.checkUserId(req.userId);
  1337. JsonRoutes.sendResult(res, {
  1338. code: 200,
  1339. data: Meteor.users.find({}).map(function(doc) {
  1340. return { _id: doc._id, username: doc.username };
  1341. }),
  1342. });
  1343. } catch (error) {
  1344. JsonRoutes.sendResult(res, {
  1345. code: 200,
  1346. data: error,
  1347. });
  1348. }
  1349. });
  1350. /**
  1351. * @operation get_user
  1352. *
  1353. * @summary get a given user
  1354. *
  1355. * @description Only the admin user (the first user) can call the REST API.
  1356. *
  1357. * @param {string} userId the user ID
  1358. * @return_type Users
  1359. */
  1360. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1361. try {
  1362. Authentication.checkUserId(req.userId);
  1363. const id = req.params.userId;
  1364. // get all boards where the user is member of
  1365. let boards = Boards.find(
  1366. {
  1367. type: 'board',
  1368. 'members.userId': id,
  1369. },
  1370. {
  1371. fields: { _id: 1, members: 1 },
  1372. },
  1373. );
  1374. boards = boards.map(b => {
  1375. const u = b.members.find(m => m.userId === id);
  1376. delete u.userId;
  1377. u.boardId = b._id;
  1378. return u;
  1379. });
  1380. const user = Meteor.users.findOne({ _id: id });
  1381. user.boards = boards;
  1382. JsonRoutes.sendResult(res, {
  1383. code: 200,
  1384. data: user,
  1385. });
  1386. } catch (error) {
  1387. JsonRoutes.sendResult(res, {
  1388. code: 200,
  1389. data: error,
  1390. });
  1391. }
  1392. });
  1393. /**
  1394. * @operation edit_user
  1395. *
  1396. * @summary edit a given user
  1397. *
  1398. * @description Only the admin user (the first user) can call the REST API.
  1399. *
  1400. * Possible values for *action*:
  1401. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1402. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1403. * - `enableLogin`: Enable a user
  1404. *
  1405. * @param {string} userId the user ID
  1406. * @param {string} action the action
  1407. * @return_type {_id: string,
  1408. * title: string}
  1409. */
  1410. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1411. try {
  1412. Authentication.checkUserId(req.userId);
  1413. const id = req.params.userId;
  1414. const action = req.body.action;
  1415. let data = Meteor.users.findOne({ _id: id });
  1416. if (data !== undefined) {
  1417. if (action === 'takeOwnership') {
  1418. data = Boards.find(
  1419. {
  1420. 'members.userId': id,
  1421. 'members.isAdmin': true,
  1422. },
  1423. { sort: { sort: 1 /* boards default sorting */ } },
  1424. ).map(function(board) {
  1425. if (board.hasMember(req.userId)) {
  1426. board.removeMember(req.userId);
  1427. }
  1428. board.changeOwnership(id, req.userId);
  1429. return {
  1430. _id: board._id,
  1431. title: board.title,
  1432. };
  1433. });
  1434. } else {
  1435. if (action === 'disableLogin' && id !== req.userId) {
  1436. Users.update(
  1437. { _id: id },
  1438. {
  1439. $set: {
  1440. loginDisabled: true,
  1441. 'services.resume.loginTokens': '',
  1442. },
  1443. },
  1444. );
  1445. } else if (action === 'enableLogin') {
  1446. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1447. }
  1448. data = Meteor.users.findOne({ _id: id });
  1449. }
  1450. }
  1451. JsonRoutes.sendResult(res, {
  1452. code: 200,
  1453. data,
  1454. });
  1455. } catch (error) {
  1456. JsonRoutes.sendResult(res, {
  1457. code: 200,
  1458. data: error,
  1459. });
  1460. }
  1461. });
  1462. /**
  1463. * @operation add_board_member
  1464. * @tag Boards
  1465. *
  1466. * @summary Add New Board Member with Role
  1467. *
  1468. * @description Only the admin user (the first user) can call the REST API.
  1469. *
  1470. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1471. * to later change the permissions.
  1472. *
  1473. * @param {string} boardId the board ID
  1474. * @param {string} userId the user ID
  1475. * @param {boolean} isAdmin is the user an admin of the board
  1476. * @param {boolean} isNoComments disable comments
  1477. * @param {boolean} isCommentOnly only enable comments
  1478. * @return_type {_id: string,
  1479. * title: string}
  1480. */
  1481. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1482. req,
  1483. res,
  1484. ) {
  1485. try {
  1486. Authentication.checkUserId(req.userId);
  1487. const userId = req.params.userId;
  1488. const boardId = req.params.boardId;
  1489. const action = req.body.action;
  1490. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1491. let data = Meteor.users.findOne({ _id: userId });
  1492. if (data !== undefined) {
  1493. if (action === 'add') {
  1494. data = Boards.find({
  1495. _id: boardId,
  1496. }).map(function(board) {
  1497. if (!board.hasMember(userId)) {
  1498. board.addMember(userId);
  1499. function isTrue(data) {
  1500. return data.toLowerCase() === 'true';
  1501. }
  1502. board.setMemberPermission(
  1503. userId,
  1504. isTrue(isAdmin),
  1505. isTrue(isNoComments),
  1506. isTrue(isCommentOnly),
  1507. userId,
  1508. );
  1509. }
  1510. return {
  1511. _id: board._id,
  1512. title: board.title,
  1513. };
  1514. });
  1515. }
  1516. }
  1517. JsonRoutes.sendResult(res, {
  1518. code: 200,
  1519. data: query,
  1520. });
  1521. } catch (error) {
  1522. JsonRoutes.sendResult(res, {
  1523. code: 200,
  1524. data: error,
  1525. });
  1526. }
  1527. });
  1528. /**
  1529. * @operation remove_board_member
  1530. * @tag Boards
  1531. *
  1532. * @summary Remove Member from Board
  1533. *
  1534. * @description Only the admin user (the first user) can call the REST API.
  1535. *
  1536. * @param {string} boardId the board ID
  1537. * @param {string} userId the user ID
  1538. * @param {string} action the action (needs to be `remove`)
  1539. * @return_type {_id: string,
  1540. * title: string}
  1541. */
  1542. JsonRoutes.add(
  1543. 'POST',
  1544. '/api/boards/:boardId/members/:userId/remove',
  1545. function(req, res) {
  1546. try {
  1547. Authentication.checkUserId(req.userId);
  1548. const userId = req.params.userId;
  1549. const boardId = req.params.boardId;
  1550. const action = req.body.action;
  1551. let data = Meteor.users.findOne({ _id: userId });
  1552. if (data !== undefined) {
  1553. if (action === 'remove') {
  1554. data = Boards.find({
  1555. _id: boardId,
  1556. }).map(function(board) {
  1557. if (board.hasMember(userId)) {
  1558. board.removeMember(userId);
  1559. }
  1560. return {
  1561. _id: board._id,
  1562. title: board.title,
  1563. };
  1564. });
  1565. }
  1566. }
  1567. JsonRoutes.sendResult(res, {
  1568. code: 200,
  1569. data: query,
  1570. });
  1571. } catch (error) {
  1572. JsonRoutes.sendResult(res, {
  1573. code: 200,
  1574. data: error,
  1575. });
  1576. }
  1577. },
  1578. );
  1579. /**
  1580. * @operation new_user
  1581. *
  1582. * @summary Create a new user
  1583. *
  1584. * @description Only the admin user (the first user) can call the REST API.
  1585. *
  1586. * @param {string} username the new username
  1587. * @param {string} email the email of the new user
  1588. * @param {string} password the password of the new user
  1589. * @return_type {_id: string}
  1590. */
  1591. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1592. try {
  1593. Authentication.checkUserId(req.userId);
  1594. const id = Accounts.createUser({
  1595. username: req.body.username,
  1596. email: req.body.email,
  1597. password: req.body.password,
  1598. from: 'admin',
  1599. });
  1600. JsonRoutes.sendResult(res, {
  1601. code: 200,
  1602. data: {
  1603. _id: id,
  1604. },
  1605. });
  1606. } catch (error) {
  1607. JsonRoutes.sendResult(res, {
  1608. code: 200,
  1609. data: error,
  1610. });
  1611. }
  1612. });
  1613. /**
  1614. * @operation delete_user
  1615. *
  1616. * @summary Delete a user
  1617. *
  1618. * @description Only the admin user (the first user) can call the REST API.
  1619. *
  1620. * @param {string} userId the ID of the user to delete
  1621. * @return_type {_id: string}
  1622. */
  1623. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1624. try {
  1625. Authentication.checkUserId(req.userId);
  1626. const id = req.params.userId;
  1627. // Delete is not enabled yet, because it does leave empty user avatars
  1628. // to boards: boards members, card members and assignees have
  1629. // empty users. See:
  1630. // - wekan/client/components/settings/peopleBody.jade deleteButton
  1631. // - wekan/client/components/settings/peopleBody.js deleteButton
  1632. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  1633. // that does now remove member from board, card members and assignees correctly,
  1634. // but that should be used to remove user from all boards similarly
  1635. // - wekan/models/users.js Delete is not enabled
  1636. // Meteor.users.remove({ _id: id });
  1637. JsonRoutes.sendResult(res, {
  1638. code: 200,
  1639. data: {
  1640. _id: id,
  1641. },
  1642. });
  1643. } catch (error) {
  1644. JsonRoutes.sendResult(res, {
  1645. code: 200,
  1646. data: error,
  1647. });
  1648. }
  1649. });
  1650. /**
  1651. * @operation create_user_token
  1652. *
  1653. * @summary Create a user token
  1654. *
  1655. * @description Only the admin user (the first user) can call the REST API.
  1656. *
  1657. * @param {string} userId the ID of the user to delete
  1658. * @return_type {_id: string}
  1659. */
  1660. JsonRoutes.add('POST', '/api/createtoken/:userId', function(req, res) {
  1661. try {
  1662. Authentication.checkUserId(req.userId);
  1663. const id = req.params.userId;
  1664. const token = Accounts._generateStampedLoginToken();
  1665. Accounts._insertLoginToken(id, token);
  1666. JsonRoutes.sendResult(res, {
  1667. code: 200,
  1668. data: {
  1669. _id: id,
  1670. authToken: token.token,
  1671. },
  1672. });
  1673. } catch (error) {
  1674. JsonRoutes.sendResult(res, {
  1675. code: 200,
  1676. data: error,
  1677. });
  1678. }
  1679. });
  1680. }
  1681. export default Users;