users.js 52 KB

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