users.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728
  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. }),
  339. );
  340. Users.allow({
  341. update(userId, doc) {
  342. const user = Users.findOne({ _id: userId });
  343. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  344. return true;
  345. if (!user) {
  346. return false;
  347. }
  348. return doc._id === userId;
  349. },
  350. remove(userId, doc) {
  351. const adminsNumber = Users.find({ isAdmin: true }).count();
  352. const { isAdmin } = Users.findOne(
  353. { _id: userId },
  354. { fields: { isAdmin: 1 } },
  355. );
  356. // Prevents remove of the only one administrator
  357. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  358. return false;
  359. }
  360. // If it's the user or an admin
  361. return userId === doc._id || isAdmin;
  362. },
  363. fetch: [],
  364. });
  365. // Search a user in the complete server database by its name or username. This
  366. // is used for instance to add a new user to a board.
  367. const searchInFields = ['username', 'profile.fullname'];
  368. Users.initEasySearch(searchInFields, {
  369. use: 'mongo-db',
  370. returnFields: [...searchInFields, 'profile.avatarUrl'],
  371. });
  372. if (Meteor.isClient) {
  373. Users.helpers({
  374. isBoardMember() {
  375. const board = Boards.findOne(Session.get('currentBoard'));
  376. return board && board.hasMember(this._id);
  377. },
  378. isNotNoComments() {
  379. const board = Boards.findOne(Session.get('currentBoard'));
  380. return (
  381. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  382. );
  383. },
  384. isNoComments() {
  385. const board = Boards.findOne(Session.get('currentBoard'));
  386. return board && board.hasNoComments(this._id);
  387. },
  388. isNotCommentOnly() {
  389. const board = Boards.findOne(Session.get('currentBoard'));
  390. return (
  391. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  392. );
  393. },
  394. isCommentOnly() {
  395. const board = Boards.findOne(Session.get('currentBoard'));
  396. return board && board.hasCommentOnly(this._id);
  397. },
  398. isNotWorker() {
  399. const board = Boards.findOne(Session.get('currentBoard'));
  400. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  401. },
  402. isWorker() {
  403. const board = Boards.findOne(Session.get('currentBoard'));
  404. return board && board.hasWorker(this._id);
  405. },
  406. isBoardAdmin(boardId = Session.get('currentBoard')) {
  407. const board = Boards.findOne(boardId);
  408. return board && board.hasAdmin(this._id);
  409. },
  410. });
  411. }
  412. Users.helpers({
  413. boards() {
  414. return Boards.find(
  415. { 'members.userId': this._id },
  416. { sort: { sort: 1 /* boards default sorting */ } },
  417. );
  418. },
  419. starredBoards() {
  420. const { starredBoards = [] } = this.profile || {};
  421. return Boards.find(
  422. { archived: false, _id: { $in: starredBoards } },
  423. {
  424. sort: { sort: 1 /* boards default sorting */ },
  425. },
  426. );
  427. },
  428. hasStarred(boardId) {
  429. const { starredBoards = [] } = this.profile || {};
  430. return _.contains(starredBoards, boardId);
  431. },
  432. invitedBoards() {
  433. const { invitedBoards = [] } = this.profile || {};
  434. return Boards.find(
  435. { archived: false, _id: { $in: invitedBoards } },
  436. {
  437. sort: { sort: 1 /* boards default sorting */ },
  438. },
  439. );
  440. },
  441. isInvitedTo(boardId) {
  442. const { invitedBoards = [] } = this.profile || {};
  443. return _.contains(invitedBoards, boardId);
  444. },
  445. _getListSortBy() {
  446. const profile = this.profile || {};
  447. const sortBy = profile.listSortBy || defaultSortBy;
  448. const keyPattern = /^(-{0,1})(.*$)/;
  449. const ret = [];
  450. if (keyPattern.exec(sortBy)) {
  451. ret[0] = RegExp.$2;
  452. ret[1] = RegExp.$1 ? -1 : 1;
  453. }
  454. return ret;
  455. },
  456. hasSortBy() {
  457. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  458. return !this.hasShowDesktopDragHandles();
  459. },
  460. getListSortBy() {
  461. return this._getListSortBy()[0];
  462. },
  463. getListSortTypes() {
  464. return allowedSortValues;
  465. },
  466. getListSortByDirection() {
  467. return this._getListSortBy()[1];
  468. },
  469. hasTag(tag) {
  470. const { tags = [] } = this.profile || {};
  471. return _.contains(tags, tag);
  472. },
  473. hasNotification(activityId) {
  474. const { notifications = [] } = this.profile || {};
  475. return _.contains(notifications, activityId);
  476. },
  477. notifications() {
  478. const { notifications = [] } = this.profile || {};
  479. for (const index in notifications) {
  480. if (!notifications.hasOwnProperty(index)) continue;
  481. const notification = notifications[index];
  482. // this preserves their db sort order for editing
  483. notification.dbIndex = index;
  484. notification.activity = Activities.findOne(notification.activity);
  485. }
  486. // this sorts them newest to oldest to match Trello's behavior
  487. notifications.reverse();
  488. return notifications;
  489. },
  490. hasShowDesktopDragHandles() {
  491. const profile = this.profile || {};
  492. return profile.showDesktopDragHandles || false;
  493. },
  494. hasHideCheckedItems() {
  495. const profile = this.profile || {};
  496. return profile.hideCheckedItems || false;
  497. },
  498. hasHiddenSystemMessages() {
  499. const profile = this.profile || {};
  500. return profile.hiddenSystemMessages || false;
  501. },
  502. hasHiddenMinicardLabelText() {
  503. const profile = this.profile || {};
  504. return profile.hiddenMinicardLabelText || false;
  505. },
  506. getEmailBuffer() {
  507. const { emailBuffer = [] } = this.profile || {};
  508. return emailBuffer;
  509. },
  510. getInitials() {
  511. const profile = this.profile || {};
  512. if (profile.initials) return profile.initials;
  513. else if (profile.fullname) {
  514. return profile.fullname
  515. .split(/\s+/)
  516. .reduce((memo, word) => {
  517. return memo + word[0];
  518. }, '')
  519. .toUpperCase();
  520. } else {
  521. return this.username[0].toUpperCase();
  522. }
  523. },
  524. getLimitToShowCardsCount() {
  525. const profile = this.profile || {};
  526. return profile.showCardsCountAt;
  527. },
  528. getName() {
  529. const profile = this.profile || {};
  530. return profile.fullname || this.username;
  531. },
  532. getLanguage() {
  533. const profile = this.profile || {};
  534. return profile.language || 'en';
  535. },
  536. getStartDayOfWeek() {
  537. const profile = this.profile || {};
  538. if (typeof profile.startDayOfWeek === 'undefined') {
  539. // default is 'Monday' (1)
  540. return 1;
  541. }
  542. return profile.startDayOfWeek;
  543. },
  544. getTemplatesBoardId() {
  545. return (this.profile || {}).templatesBoardId;
  546. },
  547. getTemplatesBoardSlug() {
  548. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  549. },
  550. remove() {
  551. User.remove({ _id: this._id });
  552. },
  553. });
  554. Users.mutations({
  555. toggleBoardStar(boardId) {
  556. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  557. return {
  558. [queryKind]: {
  559. 'profile.starredBoards': boardId,
  560. },
  561. };
  562. },
  563. addInvite(boardId) {
  564. return {
  565. $addToSet: {
  566. 'profile.invitedBoards': boardId,
  567. },
  568. };
  569. },
  570. removeInvite(boardId) {
  571. return {
  572. $pull: {
  573. 'profile.invitedBoards': boardId,
  574. },
  575. };
  576. },
  577. addTag(tag) {
  578. return {
  579. $addToSet: {
  580. 'profile.tags': tag,
  581. },
  582. };
  583. },
  584. removeTag(tag) {
  585. return {
  586. $pull: {
  587. 'profile.tags': tag,
  588. },
  589. };
  590. },
  591. toggleTag(tag) {
  592. if (this.hasTag(tag)) this.removeTag(tag);
  593. else this.addTag(tag);
  594. },
  595. setListSortBy(value) {
  596. return {
  597. $set: {
  598. 'profile.listSortBy': value,
  599. },
  600. };
  601. },
  602. setName(value) {
  603. return {
  604. $set: {
  605. 'profile.fullname': value,
  606. },
  607. };
  608. },
  609. toggleDesktopHandles(value = false) {
  610. return {
  611. $set: {
  612. 'profile.showDesktopDragHandles': !value,
  613. },
  614. };
  615. },
  616. toggleHideCheckedItems() {
  617. const value = this.hasHideCheckedItems();
  618. return {
  619. $set: {
  620. 'profile.hideCheckedItems': !value,
  621. },
  622. };
  623. },
  624. toggleSystem(value = false) {
  625. return {
  626. $set: {
  627. 'profile.hiddenSystemMessages': !value,
  628. },
  629. };
  630. },
  631. toggleLabelText(value = false) {
  632. return {
  633. $set: {
  634. 'profile.hiddenMinicardLabelText': !value,
  635. },
  636. };
  637. },
  638. addNotification(activityId) {
  639. return {
  640. $addToSet: {
  641. 'profile.notifications': { activity: activityId },
  642. },
  643. };
  644. },
  645. removeNotification(activityId) {
  646. return {
  647. $pull: {
  648. 'profile.notifications': { activity: activityId },
  649. },
  650. };
  651. },
  652. addEmailBuffer(text) {
  653. return {
  654. $addToSet: {
  655. 'profile.emailBuffer': text,
  656. },
  657. };
  658. },
  659. clearEmailBuffer() {
  660. return {
  661. $set: {
  662. 'profile.emailBuffer': [],
  663. },
  664. };
  665. },
  666. setAvatarUrl(avatarUrl) {
  667. return { $set: { 'profile.avatarUrl': avatarUrl } };
  668. },
  669. setShowCardsCountAt(limit) {
  670. return { $set: { 'profile.showCardsCountAt': limit } };
  671. },
  672. setStartDayOfWeek(startDay) {
  673. return { $set: { 'profile.startDayOfWeek': startDay } };
  674. },
  675. setBoardView(view) {
  676. return {
  677. $set: {
  678. 'profile.boardView': view,
  679. },
  680. };
  681. },
  682. });
  683. Meteor.methods({
  684. setListSortBy(value) {
  685. check(value, String);
  686. Meteor.user().setListSortBy(value);
  687. },
  688. toggleDesktopDragHandles() {
  689. const user = Meteor.user();
  690. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  691. },
  692. toggleHideCheckedItems() {
  693. const user = Meteor.user();
  694. user.toggleHideCheckedItems();
  695. },
  696. toggleSystemMessages() {
  697. const user = Meteor.user();
  698. user.toggleSystem(user.hasHiddenSystemMessages());
  699. },
  700. toggleMinicardLabelText() {
  701. const user = Meteor.user();
  702. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  703. },
  704. changeLimitToShowCardsCount(limit) {
  705. check(limit, Number);
  706. Meteor.user().setShowCardsCountAt(limit);
  707. },
  708. changeStartDayOfWeek(startDay) {
  709. check(startDay, Number);
  710. Meteor.user().setStartDayOfWeek(startDay);
  711. },
  712. });
  713. if (Meteor.isServer) {
  714. Meteor.methods({
  715. setCreateUser(fullname, username, password, isAdmin, isActive, email) {
  716. if (Meteor.user() && Meteor.user().isAdmin) {
  717. check(fullname, String);
  718. check(username, String);
  719. check(password, String);
  720. check(isAdmin, String);
  721. check(isActive, String);
  722. check(email, String);
  723. const nUsersWithUsername = Users.find({ username }).count();
  724. const nUsersWithEmail = Users.find({ email }).count();
  725. if (nUsersWithUsername > 0) {
  726. throw new Meteor.Error('username-already-taken');
  727. } else if (nUsersWithEmail > 0) {
  728. throw new Meteor.Error('email-already-taken');
  729. } else {
  730. Accounts.createUser({
  731. username,
  732. password,
  733. isAdmin,
  734. isActive,
  735. email: email.toLowerCase(),
  736. from: 'admin',
  737. });
  738. user = Users.findOne(username) || Users.findOne({ username });
  739. if (user) {
  740. Users.update(user._id, {
  741. $set: { 'profile.fullname': fullname },
  742. });
  743. }
  744. }
  745. }
  746. },
  747. setUsername(username, userId) {
  748. if (Meteor.user() && Meteor.user().isAdmin) {
  749. check(username, String);
  750. check(userId, String);
  751. const nUsersWithUsername = Users.find({ username }).count();
  752. if (nUsersWithUsername > 0) {
  753. throw new Meteor.Error('username-already-taken');
  754. } else {
  755. Users.update(userId, { $set: { username } });
  756. }
  757. }
  758. },
  759. setEmail(email, userId) {
  760. if (Meteor.user() && Meteor.user().isAdmin) {
  761. if (Array.isArray(email)) {
  762. email = email.shift();
  763. }
  764. check(email, String);
  765. const existingUser = Users.findOne(
  766. { 'emails.address': email },
  767. { fields: { _id: 1 } },
  768. );
  769. if (existingUser) {
  770. throw new Meteor.Error('email-already-taken');
  771. } else {
  772. Users.update(userId, {
  773. $set: {
  774. emails: [
  775. {
  776. address: email,
  777. verified: false,
  778. },
  779. ],
  780. },
  781. });
  782. }
  783. }
  784. },
  785. setUsernameAndEmail(username, email, userId) {
  786. if (Meteor.user() && Meteor.user().isAdmin) {
  787. check(username, String);
  788. if (Array.isArray(email)) {
  789. email = email.shift();
  790. }
  791. check(email, String);
  792. check(userId, String);
  793. Meteor.call('setUsername', username, userId);
  794. Meteor.call('setEmail', email, userId);
  795. }
  796. },
  797. setPassword(newPassword, userId) {
  798. if (Meteor.user() && Meteor.user().isAdmin) {
  799. check(userId, String);
  800. check(newPassword, String);
  801. if (Meteor.user().isAdmin) {
  802. Accounts.setPassword(userId, newPassword);
  803. }
  804. }
  805. },
  806. setEmailVerified(email, verified, userId) {
  807. if (Meteor.user() && Meteor.user().isAdmin) {
  808. check(email, String);
  809. check(verified, Boolean);
  810. check(userId, String);
  811. Users.update(userId, {
  812. $set: {
  813. emails: [
  814. {
  815. address: email,
  816. verified,
  817. },
  818. ],
  819. },
  820. });
  821. }
  822. },
  823. setInitials(initials, userId) {
  824. if (Meteor.user() && Meteor.user().isAdmin) {
  825. check(initials, String);
  826. check(userId, String);
  827. Users.update(userId, {
  828. $set: {
  829. 'profile.initials': initials,
  830. },
  831. });
  832. }
  833. },
  834. // we accept userId, username, email
  835. inviteUserToBoard(username, boardId) {
  836. check(username, String);
  837. check(boardId, String);
  838. const inviter = Meteor.user();
  839. const board = Boards.findOne(boardId);
  840. const allowInvite =
  841. inviter &&
  842. board &&
  843. board.members &&
  844. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  845. _.where(board.members, { userId: inviter._id })[0].isActive;
  846. // GitHub issue 2060
  847. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  848. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  849. this.unblock();
  850. const posAt = username.indexOf('@');
  851. let user = null;
  852. if (posAt >= 0) {
  853. user = Users.findOne({ emails: { $elemMatch: { address: username } } });
  854. } else {
  855. user = Users.findOne(username) || Users.findOne({ username });
  856. }
  857. if (user) {
  858. if (user._id === inviter._id)
  859. throw new Meteor.Error('error-user-notAllowSelf');
  860. } else {
  861. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  862. if (Settings.findOne({ disableRegistration: true })) {
  863. throw new Meteor.Error('error-user-notCreated');
  864. }
  865. // Set in lowercase email before creating account
  866. const email = username.toLowerCase();
  867. username = email.substring(0, posAt);
  868. const newUserId = Accounts.createUser({ username, email });
  869. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  870. // assume new user speak same language with inviter
  871. if (inviter.profile && inviter.profile.language) {
  872. Users.update(newUserId, {
  873. $set: {
  874. 'profile.language': inviter.profile.language,
  875. },
  876. });
  877. }
  878. Accounts.sendEnrollmentEmail(newUserId);
  879. user = Users.findOne(newUserId);
  880. }
  881. board.addMember(user._id);
  882. user.addInvite(boardId);
  883. //Check if there is a subtasks board
  884. if (board.subtasksDefaultBoardId) {
  885. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  886. //If there is, also add user to that board
  887. if (subBoard) {
  888. subBoard.addMember(user._id);
  889. user.addInvite(subBoard._id);
  890. }
  891. }
  892. try {
  893. const params = {
  894. user: user.username,
  895. inviter: inviter.username,
  896. board: board.title,
  897. url: board.absoluteUrl(),
  898. };
  899. const lang = user.getLanguage();
  900. Email.send({
  901. to: user.emails[0].address.toLowerCase(),
  902. from: Accounts.emailTemplates.from,
  903. subject: TAPi18n.__('email-invite-subject', params, lang),
  904. text: TAPi18n.__('email-invite-text', params, lang),
  905. });
  906. } catch (e) {
  907. throw new Meteor.Error('email-fail', e.message);
  908. }
  909. return { username: user.username, email: user.emails[0].address };
  910. },
  911. impersonate(userId) {
  912. check(userId, String);
  913. if (!Meteor.users.findOne(userId))
  914. throw new Meteor.Error(404, 'User not found');
  915. if (!Meteor.user().isAdmin)
  916. throw new Meteor.Error(403, 'Permission denied');
  917. this.setUserId(userId);
  918. },
  919. });
  920. Accounts.onCreateUser((options, user) => {
  921. const userCount = Users.find().count();
  922. if (userCount === 0) {
  923. user.isAdmin = true;
  924. return user;
  925. }
  926. if (user.services.oidc) {
  927. let email = user.services.oidc.email;
  928. if (Array.isArray(email)) {
  929. email = email.shift();
  930. }
  931. email = email.toLowerCase();
  932. user.username = user.services.oidc.username;
  933. user.emails = [{ address: email, verified: true }];
  934. const initials = user.services.oidc.fullname
  935. .match(/\b[a-zA-Z]/g)
  936. .join('')
  937. .toUpperCase();
  938. user.profile = {
  939. initials,
  940. fullname: user.services.oidc.fullname,
  941. boardView: 'board-view-swimlanes',
  942. };
  943. user.authenticationMethod = 'oauth2';
  944. // see if any existing user has this email address or username, otherwise create new
  945. const existingUser = Meteor.users.findOne({
  946. $or: [{ 'emails.address': email }, { username: user.username }],
  947. });
  948. if (!existingUser) return user;
  949. // copy across new service info
  950. const service = _.keys(user.services)[0];
  951. existingUser.services[service] = user.services[service];
  952. existingUser.emails = user.emails;
  953. existingUser.username = user.username;
  954. existingUser.profile = user.profile;
  955. existingUser.authenticationMethod = user.authenticationMethod;
  956. Meteor.users.remove({ _id: user._id });
  957. Meteor.users.remove({ _id: existingUser._id }); // is going to be created again
  958. return existingUser;
  959. }
  960. if (options.from === 'admin') {
  961. user.createdThroughApi = true;
  962. return user;
  963. }
  964. const disableRegistration = Settings.findOne().disableRegistration;
  965. // If this is the first Authentication by the ldap and self registration disabled
  966. if (disableRegistration && options && options.ldap) {
  967. user.authenticationMethod = 'ldap';
  968. return user;
  969. }
  970. // If self registration enabled
  971. if (!disableRegistration) {
  972. return user;
  973. }
  974. if (!options || !options.profile) {
  975. throw new Meteor.Error(
  976. 'error-invitation-code-blank',
  977. 'The invitation code is required',
  978. );
  979. }
  980. const invitationCode = InvitationCodes.findOne({
  981. code: options.profile.invitationcode,
  982. email: options.email,
  983. valid: true,
  984. });
  985. if (!invitationCode) {
  986. throw new Meteor.Error(
  987. 'error-invitation-code-not-exist',
  988. // eslint-disable-next-line quotes
  989. "The invitation code doesn't exist",
  990. );
  991. } else {
  992. user.profile = { icode: options.profile.invitationcode };
  993. user.profile.boardView = 'board-view-swimlanes';
  994. // Deletes the invitation code after the user was created successfully.
  995. setTimeout(
  996. Meteor.bindEnvironment(() => {
  997. InvitationCodes.remove({ _id: invitationCode._id });
  998. }),
  999. 200,
  1000. );
  1001. return user;
  1002. }
  1003. });
  1004. }
  1005. const addCronJob = _.debounce(
  1006. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  1007. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  1008. const envRemoveAge =
  1009. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  1010. // default notifications will be removed 2 days after they are read
  1011. const defaultRemoveAge = 2;
  1012. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  1013. SyncedCron.add({
  1014. name: 'notification_cleanup',
  1015. schedule: parser => parser.text('every 1 days'),
  1016. job: () => {
  1017. for (const user of Users.find()) {
  1018. if (!user.profile || !user.profile.notifications) continue;
  1019. for (const notification of user.profile.notifications) {
  1020. if (notification.read) {
  1021. const removeDate = new Date(notification.read);
  1022. removeDate.setDate(removeDate.getDate() + removeAge);
  1023. if (removeDate <= new Date()) {
  1024. user.removeNotification(notification.activity);
  1025. }
  1026. }
  1027. }
  1028. }
  1029. },
  1030. });
  1031. SyncedCron.start();
  1032. }),
  1033. 500,
  1034. );
  1035. if (Meteor.isServer) {
  1036. // Let mongoDB ensure username unicity
  1037. Meteor.startup(() => {
  1038. allowedSortValues.forEach(value => {
  1039. Lists._collection._ensureIndex(value);
  1040. });
  1041. Users._collection._ensureIndex({ modifiedAt: -1 });
  1042. Users._collection._ensureIndex(
  1043. {
  1044. username: 1,
  1045. },
  1046. { unique: true },
  1047. );
  1048. Meteor.defer(() => {
  1049. addCronJob();
  1050. });
  1051. });
  1052. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1053. // if admin is removed, board is removed.
  1054. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1055. // to use that board, and not have board deleted.
  1056. // Someone can be later changed to be admin of board, by making change to database.
  1057. // TODO: Add UI for changing someone as board admin.
  1058. //Users.before.remove((userId, doc) => {
  1059. // Boards
  1060. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1061. // .forEach((board) => {
  1062. // // If only one admin for the board
  1063. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1064. // Boards.remove(board._id);
  1065. // }
  1066. // });
  1067. //});
  1068. // Each board document contains the de-normalized number of users that have
  1069. // starred it. If the user star or unstar a board, we need to update this
  1070. // counter.
  1071. // We need to run this code on the server only, otherwise the incrementation
  1072. // will be done twice.
  1073. Users.after.update(function(userId, user, fieldNames) {
  1074. // The `starredBoards` list is hosted on the `profile` field. If this
  1075. // field hasn't been modificated we don't need to run this hook.
  1076. if (!_.contains(fieldNames, 'profile')) return;
  1077. // To calculate a diff of board starred ids, we get both the previous
  1078. // and the newly board ids list
  1079. function getStarredBoardsIds(doc) {
  1080. return doc.profile && doc.profile.starredBoards;
  1081. }
  1082. const oldIds = getStarredBoardsIds(this.previous);
  1083. const newIds = getStarredBoardsIds(user);
  1084. // The _.difference(a, b) method returns the values from a that are not in
  1085. // b. We use it to find deleted and newly inserted ids by using it in one
  1086. // direction and then in the other.
  1087. function incrementBoards(boardsIds, inc) {
  1088. boardsIds.forEach(boardId => {
  1089. Boards.update(boardId, { $inc: { stars: inc } });
  1090. });
  1091. }
  1092. incrementBoards(_.difference(oldIds, newIds), -1);
  1093. incrementBoards(_.difference(newIds, oldIds), +1);
  1094. });
  1095. // Override getUserId so that we can TODO get the current userId
  1096. const fakeUserId = new Meteor.EnvironmentVariable();
  1097. const getUserId = CollectionHooks.getUserId;
  1098. CollectionHooks.getUserId = () => {
  1099. return fakeUserId.get() || getUserId();
  1100. };
  1101. if (!isSandstorm) {
  1102. Users.after.insert((userId, doc) => {
  1103. const fakeUser = {
  1104. extendAutoValueContext: {
  1105. userId: doc._id,
  1106. },
  1107. };
  1108. fakeUserId.withValue(doc._id, () => {
  1109. /*
  1110. // Insert the Welcome Board
  1111. Boards.insert({
  1112. title: TAPi18n.__('welcome-board'),
  1113. permission: 'private',
  1114. }, fakeUser, (err, boardId) => {
  1115. Swimlanes.insert({
  1116. title: TAPi18n.__('welcome-swimlane'),
  1117. boardId,
  1118. sort: 1,
  1119. }, fakeUser);
  1120. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1121. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1122. });
  1123. });
  1124. */
  1125. const Future = require('fibers/future');
  1126. const future1 = new Future();
  1127. const future2 = new Future();
  1128. const future3 = new Future();
  1129. Boards.insert(
  1130. {
  1131. title: TAPi18n.__('templates'),
  1132. permission: 'private',
  1133. type: 'template-container',
  1134. },
  1135. fakeUser,
  1136. (err, boardId) => {
  1137. // Insert the reference to our templates board
  1138. Users.update(fakeUserId.get(), {
  1139. $set: { 'profile.templatesBoardId': boardId },
  1140. });
  1141. // Insert the card templates swimlane
  1142. Swimlanes.insert(
  1143. {
  1144. title: TAPi18n.__('card-templates-swimlane'),
  1145. boardId,
  1146. sort: 1,
  1147. type: 'template-container',
  1148. },
  1149. fakeUser,
  1150. (err, swimlaneId) => {
  1151. // Insert the reference to out card templates swimlane
  1152. Users.update(fakeUserId.get(), {
  1153. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1154. });
  1155. future1.return();
  1156. },
  1157. );
  1158. // Insert the list templates swimlane
  1159. Swimlanes.insert(
  1160. {
  1161. title: TAPi18n.__('list-templates-swimlane'),
  1162. boardId,
  1163. sort: 2,
  1164. type: 'template-container',
  1165. },
  1166. fakeUser,
  1167. (err, swimlaneId) => {
  1168. // Insert the reference to out list templates swimlane
  1169. Users.update(fakeUserId.get(), {
  1170. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1171. });
  1172. future2.return();
  1173. },
  1174. );
  1175. // Insert the board templates swimlane
  1176. Swimlanes.insert(
  1177. {
  1178. title: TAPi18n.__('board-templates-swimlane'),
  1179. boardId,
  1180. sort: 3,
  1181. type: 'template-container',
  1182. },
  1183. fakeUser,
  1184. (err, swimlaneId) => {
  1185. // Insert the reference to out board templates swimlane
  1186. Users.update(fakeUserId.get(), {
  1187. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1188. });
  1189. future3.return();
  1190. },
  1191. );
  1192. },
  1193. );
  1194. // HACK
  1195. future1.wait();
  1196. future2.wait();
  1197. future3.wait();
  1198. });
  1199. });
  1200. }
  1201. Users.after.insert((userId, doc) => {
  1202. // HACK
  1203. doc = Users.findOne({ _id: doc._id });
  1204. if (doc.createdThroughApi) {
  1205. // The admin user should be able to create a user despite disabling registration because
  1206. // it is two different things (registration and creation).
  1207. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1208. // the disableRegistration check.
  1209. // Issue : https://github.com/wekan/wekan/issues/1232
  1210. // PR : https://github.com/wekan/wekan/pull/1251
  1211. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1212. return;
  1213. }
  1214. //invite user to corresponding boards
  1215. const disableRegistration = Settings.findOne().disableRegistration;
  1216. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1217. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1218. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1219. const invitationCode = InvitationCodes.findOne({
  1220. code: doc.profile.icode,
  1221. valid: true,
  1222. });
  1223. if (!invitationCode) {
  1224. throw new Meteor.Error('error-invitation-code-not-exist');
  1225. } else {
  1226. invitationCode.boardsToBeInvited.forEach(boardId => {
  1227. const board = Boards.findOne(boardId);
  1228. board.addMember(doc._id);
  1229. });
  1230. if (!doc.profile) {
  1231. doc.profile = {};
  1232. }
  1233. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1234. Users.update(doc._id, { $set: { profile: doc.profile } });
  1235. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1236. }
  1237. }
  1238. });
  1239. }
  1240. // USERS REST API
  1241. if (Meteor.isServer) {
  1242. // Middleware which checks that API is enabled.
  1243. JsonRoutes.Middleware.use(function(req, res, next) {
  1244. const api = req.url.startsWith('/api');
  1245. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1246. return next();
  1247. } else {
  1248. res.writeHead(301, { Location: '/' });
  1249. return res.end();
  1250. }
  1251. });
  1252. /**
  1253. * @operation get_current_user
  1254. *
  1255. * @summary returns the current user
  1256. * @return_type Users
  1257. */
  1258. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1259. try {
  1260. Authentication.checkLoggedIn(req.userId);
  1261. const data = Meteor.users.findOne({ _id: req.userId });
  1262. delete data.services;
  1263. // get all boards where the user is member of
  1264. let boards = Boards.find(
  1265. {
  1266. type: 'board',
  1267. 'members.userId': req.userId,
  1268. },
  1269. {
  1270. fields: { _id: 1, members: 1 },
  1271. },
  1272. );
  1273. boards = boards.map(b => {
  1274. const u = b.members.find(m => m.userId === req.userId);
  1275. delete u.userId;
  1276. u.boardId = b._id;
  1277. return u;
  1278. });
  1279. data.boards = boards;
  1280. JsonRoutes.sendResult(res, {
  1281. code: 200,
  1282. data,
  1283. });
  1284. } catch (error) {
  1285. JsonRoutes.sendResult(res, {
  1286. code: 200,
  1287. data: error,
  1288. });
  1289. }
  1290. });
  1291. /**
  1292. * @operation get_all_users
  1293. *
  1294. * @summary return all the users
  1295. *
  1296. * @description Only the admin user (the first user) can call the REST API.
  1297. * @return_type [{ _id: string,
  1298. * username: string}]
  1299. */
  1300. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1301. try {
  1302. Authentication.checkUserId(req.userId);
  1303. JsonRoutes.sendResult(res, {
  1304. code: 200,
  1305. data: Meteor.users.find({}).map(function(doc) {
  1306. return { _id: doc._id, username: doc.username };
  1307. }),
  1308. });
  1309. } catch (error) {
  1310. JsonRoutes.sendResult(res, {
  1311. code: 200,
  1312. data: error,
  1313. });
  1314. }
  1315. });
  1316. /**
  1317. * @operation get_user
  1318. *
  1319. * @summary get a given user
  1320. *
  1321. * @description Only the admin user (the first user) can call the REST API.
  1322. *
  1323. * @param {string} userId the user ID
  1324. * @return_type Users
  1325. */
  1326. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1327. try {
  1328. Authentication.checkUserId(req.userId);
  1329. const id = req.params.userId;
  1330. // get all boards where the user is member of
  1331. let boards = Boards.find(
  1332. {
  1333. type: 'board',
  1334. 'members.userId': id,
  1335. },
  1336. {
  1337. fields: { _id: 1, members: 1 },
  1338. },
  1339. );
  1340. boards = boards.map(b => {
  1341. const u = b.members.find(m => m.userId === id);
  1342. delete u.userId;
  1343. u.boardId = b._id;
  1344. return u;
  1345. });
  1346. const user = Meteor.users.findOne({ _id: id });
  1347. user.boards = boards;
  1348. JsonRoutes.sendResult(res, {
  1349. code: 200,
  1350. data: user,
  1351. });
  1352. } catch (error) {
  1353. JsonRoutes.sendResult(res, {
  1354. code: 200,
  1355. data: error,
  1356. });
  1357. }
  1358. });
  1359. /**
  1360. * @operation edit_user
  1361. *
  1362. * @summary edit a given user
  1363. *
  1364. * @description Only the admin user (the first user) can call the REST API.
  1365. *
  1366. * Possible values for *action*:
  1367. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1368. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1369. * - `enableLogin`: Enable a user
  1370. *
  1371. * @param {string} userId the user ID
  1372. * @param {string} action the action
  1373. * @return_type {_id: string,
  1374. * title: string}
  1375. */
  1376. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1377. try {
  1378. Authentication.checkUserId(req.userId);
  1379. const id = req.params.userId;
  1380. const action = req.body.action;
  1381. let data = Meteor.users.findOne({ _id: id });
  1382. if (data !== undefined) {
  1383. if (action === 'takeOwnership') {
  1384. data = Boards.find(
  1385. {
  1386. 'members.userId': id,
  1387. 'members.isAdmin': true,
  1388. },
  1389. { sort: { sort: 1 /* boards default sorting */ } },
  1390. ).map(function(board) {
  1391. if (board.hasMember(req.userId)) {
  1392. board.removeMember(req.userId);
  1393. }
  1394. board.changeOwnership(id, req.userId);
  1395. return {
  1396. _id: board._id,
  1397. title: board.title,
  1398. };
  1399. });
  1400. } else {
  1401. if (action === 'disableLogin' && id !== req.userId) {
  1402. Users.update(
  1403. { _id: id },
  1404. {
  1405. $set: {
  1406. loginDisabled: true,
  1407. 'services.resume.loginTokens': '',
  1408. },
  1409. },
  1410. );
  1411. } else if (action === 'enableLogin') {
  1412. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1413. }
  1414. data = Meteor.users.findOne({ _id: id });
  1415. }
  1416. }
  1417. JsonRoutes.sendResult(res, {
  1418. code: 200,
  1419. data,
  1420. });
  1421. } catch (error) {
  1422. JsonRoutes.sendResult(res, {
  1423. code: 200,
  1424. data: error,
  1425. });
  1426. }
  1427. });
  1428. /**
  1429. * @operation add_board_member
  1430. * @tag Boards
  1431. *
  1432. * @summary Add New Board Member with Role
  1433. *
  1434. * @description Only the admin user (the first user) can call the REST API.
  1435. *
  1436. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1437. * to later change the permissions.
  1438. *
  1439. * @param {string} boardId the board ID
  1440. * @param {string} userId the user ID
  1441. * @param {boolean} isAdmin is the user an admin of the board
  1442. * @param {boolean} isNoComments disable comments
  1443. * @param {boolean} isCommentOnly only enable comments
  1444. * @return_type {_id: string,
  1445. * title: string}
  1446. */
  1447. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1448. req,
  1449. res,
  1450. ) {
  1451. try {
  1452. Authentication.checkUserId(req.userId);
  1453. const userId = req.params.userId;
  1454. const boardId = req.params.boardId;
  1455. const action = req.body.action;
  1456. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1457. let data = Meteor.users.findOne({ _id: userId });
  1458. if (data !== undefined) {
  1459. if (action === 'add') {
  1460. data = Boards.find({
  1461. _id: boardId,
  1462. }).map(function(board) {
  1463. if (!board.hasMember(userId)) {
  1464. board.addMember(userId);
  1465. function isTrue(data) {
  1466. return data.toLowerCase() === 'true';
  1467. }
  1468. board.setMemberPermission(
  1469. userId,
  1470. isTrue(isAdmin),
  1471. isTrue(isNoComments),
  1472. isTrue(isCommentOnly),
  1473. userId,
  1474. );
  1475. }
  1476. return {
  1477. _id: board._id,
  1478. title: board.title,
  1479. };
  1480. });
  1481. }
  1482. }
  1483. JsonRoutes.sendResult(res, {
  1484. code: 200,
  1485. data: query,
  1486. });
  1487. } catch (error) {
  1488. JsonRoutes.sendResult(res, {
  1489. code: 200,
  1490. data: error,
  1491. });
  1492. }
  1493. });
  1494. /**
  1495. * @operation remove_board_member
  1496. * @tag Boards
  1497. *
  1498. * @summary Remove Member from Board
  1499. *
  1500. * @description Only the admin user (the first user) can call the REST API.
  1501. *
  1502. * @param {string} boardId the board ID
  1503. * @param {string} userId the user ID
  1504. * @param {string} action the action (needs to be `remove`)
  1505. * @return_type {_id: string,
  1506. * title: string}
  1507. */
  1508. JsonRoutes.add(
  1509. 'POST',
  1510. '/api/boards/:boardId/members/:userId/remove',
  1511. function(req, res) {
  1512. try {
  1513. Authentication.checkUserId(req.userId);
  1514. const userId = req.params.userId;
  1515. const boardId = req.params.boardId;
  1516. const action = req.body.action;
  1517. let data = Meteor.users.findOne({ _id: userId });
  1518. if (data !== undefined) {
  1519. if (action === 'remove') {
  1520. data = Boards.find({
  1521. _id: boardId,
  1522. }).map(function(board) {
  1523. if (board.hasMember(userId)) {
  1524. board.removeMember(userId);
  1525. }
  1526. return {
  1527. _id: board._id,
  1528. title: board.title,
  1529. };
  1530. });
  1531. }
  1532. }
  1533. JsonRoutes.sendResult(res, {
  1534. code: 200,
  1535. data: query,
  1536. });
  1537. } catch (error) {
  1538. JsonRoutes.sendResult(res, {
  1539. code: 200,
  1540. data: error,
  1541. });
  1542. }
  1543. },
  1544. );
  1545. /**
  1546. * @operation new_user
  1547. *
  1548. * @summary Create a new user
  1549. *
  1550. * @description Only the admin user (the first user) can call the REST API.
  1551. *
  1552. * @param {string} username the new username
  1553. * @param {string} email the email of the new user
  1554. * @param {string} password the password of the new user
  1555. * @return_type {_id: string}
  1556. */
  1557. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1558. try {
  1559. Authentication.checkUserId(req.userId);
  1560. const id = Accounts.createUser({
  1561. username: req.body.username,
  1562. email: req.body.email,
  1563. password: req.body.password,
  1564. from: 'admin',
  1565. });
  1566. JsonRoutes.sendResult(res, {
  1567. code: 200,
  1568. data: {
  1569. _id: id,
  1570. },
  1571. });
  1572. } catch (error) {
  1573. JsonRoutes.sendResult(res, {
  1574. code: 200,
  1575. data: error,
  1576. });
  1577. }
  1578. });
  1579. /**
  1580. * @operation delete_user
  1581. *
  1582. * @summary Delete a user
  1583. *
  1584. * @description Only the admin user (the first user) can call the REST API.
  1585. *
  1586. * @param {string} userId the ID of the user to delete
  1587. * @return_type {_id: string}
  1588. */
  1589. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1590. try {
  1591. Authentication.checkUserId(req.userId);
  1592. const id = req.params.userId;
  1593. // Delete is not enabled yet, because it does leave empty user avatars
  1594. // to boards: boards members, card members and assignees have
  1595. // empty users. See:
  1596. // - wekan/client/components/settings/peopleBody.jade deleteButton
  1597. // - wekan/client/components/settings/peopleBody.js deleteButton
  1598. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  1599. // that does now remove member from board, card members and assignees correctly,
  1600. // but that should be used to remove user from all boards similarly
  1601. // - wekan/models/users.js Delete is not enabled
  1602. // Meteor.users.remove({ _id: id });
  1603. JsonRoutes.sendResult(res, {
  1604. code: 200,
  1605. data: {
  1606. _id: id,
  1607. },
  1608. });
  1609. } catch (error) {
  1610. JsonRoutes.sendResult(res, {
  1611. code: 200,
  1612. data: error,
  1613. });
  1614. }
  1615. });
  1616. }
  1617. export default Users;