users.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139
  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. <<<<<<< HEAD
  928. <<<<<<< HEAD
  929. check(fullname, String);
  930. check(username, String);
  931. check(initials, String);
  932. check(password, String);
  933. check(isAdmin, String);
  934. check(isActive, String);
  935. check(email, String);
  936. check(importUsernames, Array);
  937. check(userOrgsArray, Array);
  938. check(userTeamsArray, Array);
  939. =======
  940. >>>>>>> feature/250f95de
  941. =======
  942. >>>>>>> feature/250f95de
  943. const nUsersWithUsername = Users.find({
  944. username,
  945. }).count();
  946. const nUsersWithEmail = Users.find({
  947. email,
  948. }).count();
  949. if (nUsersWithUsername > 0) {
  950. throw new Meteor.Error('username-already-taken');
  951. } else if (nUsersWithEmail > 0) {
  952. throw new Meteor.Error('email-already-taken');
  953. } else {
  954. Accounts.createUser({
  955. username,
  956. password,
  957. isAdmin,
  958. isActive,
  959. email: email.toLowerCase(),
  960. from: 'admin',
  961. });
  962. const user =
  963. Users.findOne(username) ||
  964. Users.findOne({
  965. username,
  966. });
  967. if (user) {
  968. Users.update(user._id, {
  969. $set: {
  970. 'profile.fullname': fullname,
  971. importUsernames,
  972. 'profile.initials': initials,
  973. orgs: userOrgsArray,
  974. teams: userTeamsArray,
  975. },
  976. });
  977. }
  978. }
  979. }
  980. },
  981. setUsername(username, userId) {
  982. check(username, String);
  983. check(userId, String);
  984. if (Meteor.user() && Meteor.user().isAdmin) {
  985. const nUsersWithUsername = Users.find({
  986. username,
  987. }).count();
  988. if (nUsersWithUsername > 0) {
  989. throw new Meteor.Error('username-already-taken');
  990. } else {
  991. Users.update(userId, {
  992. $set: {
  993. username,
  994. },
  995. });
  996. }
  997. }
  998. },
  999. setEmail(email, userId) {
  1000. check(email, String);
  1001. check(username, String);
  1002. if (Meteor.user() && Meteor.user().isAdmin) {
  1003. if (Array.isArray(email)) {
  1004. email = email.shift();
  1005. }
  1006. const existingUser = Users.findOne(
  1007. {
  1008. 'emails.address': email,
  1009. },
  1010. {
  1011. fields: {
  1012. _id: 1,
  1013. },
  1014. },
  1015. );
  1016. if (existingUser) {
  1017. throw new Meteor.Error('email-already-taken');
  1018. } else {
  1019. Users.update(userId, {
  1020. $set: {
  1021. emails: [
  1022. {
  1023. address: email,
  1024. verified: false,
  1025. },
  1026. ],
  1027. },
  1028. });
  1029. }
  1030. }
  1031. },
  1032. setUsernameAndEmail(username, email, userId) {
  1033. check(username, String);
  1034. check(email, String);
  1035. check(userId, String);
  1036. if (Meteor.user() && Meteor.user().isAdmin) {
  1037. if (Array.isArray(email)) {
  1038. email = email.shift();
  1039. }
  1040. Meteor.call('setUsername', username, userId);
  1041. Meteor.call('setEmail', email, userId);
  1042. }
  1043. },
  1044. setPassword(newPassword, userId) {
  1045. check(userId, String);
  1046. check(newPassword, String);
  1047. if (Meteor.user() && Meteor.user().isAdmin) {
  1048. if (Meteor.user().isAdmin) {
  1049. Accounts.setPassword(userId, newPassword);
  1050. }
  1051. }
  1052. },
  1053. setEmailVerified(email, verified, userId) {
  1054. check(email, String);
  1055. check(verified, Boolean);
  1056. check(userId, String);
  1057. if (Meteor.user() && Meteor.user().isAdmin) {
  1058. Users.update(userId, {
  1059. $set: {
  1060. emails: [
  1061. {
  1062. address: email,
  1063. verified,
  1064. },
  1065. ],
  1066. },
  1067. });
  1068. }
  1069. },
  1070. setInitials(initials, userId) {
  1071. check(initials, String);
  1072. check(userId, String);
  1073. if (Meteor.user() && Meteor.user().isAdmin) {
  1074. Users.update(userId, {
  1075. $set: {
  1076. 'profile.initials': initials,
  1077. },
  1078. });
  1079. }
  1080. },
  1081. // we accept userId, username, email
  1082. inviteUserToBoard(username, boardId) {
  1083. check(username, String);
  1084. check(boardId, String);
  1085. const inviter = Meteor.user();
  1086. const board = Boards.findOne(boardId);
  1087. const allowInvite =
  1088. inviter &&
  1089. board &&
  1090. board.members &&
  1091. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  1092. _.where(board.members, {
  1093. userId: inviter._id,
  1094. })[0].isActive;
  1095. // GitHub issue 2060
  1096. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  1097. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  1098. this.unblock();
  1099. const posAt = username.indexOf('@');
  1100. let user = null;
  1101. if (posAt >= 0) {
  1102. user = Users.findOne({
  1103. emails: {
  1104. $elemMatch: {
  1105. address: username,
  1106. },
  1107. },
  1108. });
  1109. } else {
  1110. user =
  1111. Users.findOne(username) ||
  1112. Users.findOne({
  1113. username,
  1114. });
  1115. }
  1116. if (user) {
  1117. if (user._id === inviter._id)
  1118. throw new Meteor.Error('error-user-notAllowSelf');
  1119. } else {
  1120. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  1121. if (
  1122. Settings.findOne({
  1123. disableRegistration: true,
  1124. })
  1125. ) {
  1126. throw new Meteor.Error('error-user-notCreated');
  1127. }
  1128. // Set in lowercase email before creating account
  1129. const email = username.toLowerCase();
  1130. username = email.substring(0, posAt);
  1131. const newUserId = Accounts.createUser({
  1132. username,
  1133. email,
  1134. });
  1135. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  1136. // assume new user speak same language with inviter
  1137. if (inviter.profile && inviter.profile.language) {
  1138. Users.update(newUserId, {
  1139. $set: {
  1140. 'profile.language': inviter.profile.language,
  1141. },
  1142. });
  1143. }
  1144. Accounts.sendEnrollmentEmail(newUserId);
  1145. user = Users.findOne(newUserId);
  1146. }
  1147. board.addMember(user._id);
  1148. user.addInvite(boardId);
  1149. //Check if there is a subtasks board
  1150. if (board.subtasksDefaultBoardId) {
  1151. const subBoard = Boards.findOne(board.subtasksDefaultBoardId);
  1152. //If there is, also add user to that board
  1153. if (subBoard) {
  1154. subBoard.addMember(user._id);
  1155. user.addInvite(subBoard._id);
  1156. }
  1157. }
  1158. try {
  1159. const params = {
  1160. user: user.username,
  1161. inviter: inviter.username,
  1162. board: board.title,
  1163. url: board.absoluteUrl(),
  1164. };
  1165. const lang = user.getLanguage();
  1166. Email.send({
  1167. to: user.emails[0].address.toLowerCase(),
  1168. from: Accounts.emailTemplates.from,
  1169. subject: TAPi18n.__('email-invite-subject', params, lang),
  1170. text: TAPi18n.__('email-invite-text', params, lang),
  1171. });
  1172. } catch (e) {
  1173. throw new Meteor.Error('email-fail', e.message);
  1174. }
  1175. return {
  1176. username: user.username,
  1177. email: user.emails[0].address,
  1178. };
  1179. },
  1180. impersonate(userId) {
  1181. check(userId, String);
  1182. if (!Meteor.users.findOne(userId))
  1183. throw new Meteor.Error(404, 'User not found');
  1184. if (!Meteor.user().isAdmin)
  1185. throw new Meteor.Error(403, 'Permission denied');
  1186. ImpersonatedUsers.insert({ adminId: Meteor.user()._id, userId: userId, reason: 'clickedImpersonate' });
  1187. this.setUserId(userId);
  1188. },
  1189. isImpersonated(userId) {
  1190. check(userId, String);
  1191. const isImpersonated = ImpersonatedUsers.findOne({
  1192. userId: userId,
  1193. });
  1194. return isImpersonated;
  1195. },
  1196. });
  1197. Accounts.onCreateUser((options, user) => {
  1198. const userCount = Users.find().count();
  1199. if (userCount === 0) {
  1200. user.isAdmin = true;
  1201. return user;
  1202. }
  1203. if (user.services.oidc) {
  1204. let email = user.services.oidc.email;
  1205. if (Array.isArray(email)) {
  1206. email = email.shift();
  1207. }
  1208. email = email.toLowerCase();
  1209. user.username = user.services.oidc.username;
  1210. user.emails = [
  1211. {
  1212. address: email,
  1213. verified: true,
  1214. },
  1215. ];
  1216. const initials = user.services.oidc.fullname
  1217. .split(/\s+/)
  1218. .reduce((memo, word) => {
  1219. return memo + word[0];
  1220. }, '')
  1221. .toUpperCase();
  1222. user.profile = {
  1223. initials,
  1224. fullname: user.services.oidc.fullname,
  1225. boardView: 'board-view-swimlanes',
  1226. };
  1227. user.authenticationMethod = 'oauth2';
  1228. // see if any existing user has this email address or username, otherwise create new
  1229. const existingUser = Meteor.users.findOne({
  1230. $or: [
  1231. {
  1232. 'emails.address': email,
  1233. },
  1234. {
  1235. username: user.username,
  1236. },
  1237. ],
  1238. });
  1239. if (!existingUser) return user;
  1240. // copy across new service info
  1241. const service = _.keys(user.services)[0];
  1242. existingUser.services[service] = user.services[service];
  1243. existingUser.emails = user.emails;
  1244. existingUser.username = user.username;
  1245. existingUser.profile = user.profile;
  1246. existingUser.authenticationMethod = user.authenticationMethod;
  1247. Meteor.users.remove({
  1248. _id: user._id,
  1249. });
  1250. Meteor.users.remove({
  1251. _id: existingUser._id,
  1252. }); // is going to be created again
  1253. return existingUser;
  1254. }
  1255. if (options.from === 'admin') {
  1256. user.createdThroughApi = true;
  1257. return user;
  1258. }
  1259. const disableRegistration = Settings.findOne().disableRegistration;
  1260. // If this is the first Authentication by the ldap and self registration disabled
  1261. if (disableRegistration && options && options.ldap) {
  1262. user.authenticationMethod = 'ldap';
  1263. return user;
  1264. }
  1265. // If self registration enabled
  1266. if (!disableRegistration) {
  1267. return user;
  1268. }
  1269. if (!options || !options.profile) {
  1270. throw new Meteor.Error(
  1271. 'error-invitation-code-blank',
  1272. 'The invitation code is required',
  1273. );
  1274. }
  1275. const invitationCode = InvitationCodes.findOne({
  1276. code: options.profile.invitationcode,
  1277. email: options.email,
  1278. valid: true,
  1279. });
  1280. if (!invitationCode) {
  1281. throw new Meteor.Error(
  1282. 'error-invitation-code-not-exist',
  1283. // eslint-disable-next-line quotes
  1284. "The invitation code doesn't exist",
  1285. );
  1286. } else {
  1287. user.profile = {
  1288. icode: options.profile.invitationcode,
  1289. };
  1290. user.profile.boardView = 'board-view-swimlanes';
  1291. // Deletes the invitation code after the user was created successfully.
  1292. setTimeout(
  1293. Meteor.bindEnvironment(() => {
  1294. InvitationCodes.remove({
  1295. _id: invitationCode._id,
  1296. });
  1297. }),
  1298. 200,
  1299. );
  1300. return user;
  1301. }
  1302. });
  1303. }
  1304. const addCronJob = _.debounce(
  1305. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  1306. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  1307. const envRemoveAge =
  1308. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  1309. // default notifications will be removed 2 days after they are read
  1310. const defaultRemoveAge = 2;
  1311. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  1312. SyncedCron.add({
  1313. name: 'notification_cleanup',
  1314. schedule: (parser) => parser.text('every 1 days'),
  1315. job: () => {
  1316. for (const user of Users.find()) {
  1317. if (!user.profile || !user.profile.notifications) continue;
  1318. for (const notification of user.profile.notifications) {
  1319. if (notification.read) {
  1320. const removeDate = new Date(notification.read);
  1321. removeDate.setDate(removeDate.getDate() + removeAge);
  1322. if (removeDate <= new Date()) {
  1323. user.removeNotification(notification.activity);
  1324. }
  1325. }
  1326. }
  1327. }
  1328. },
  1329. });
  1330. SyncedCron.start();
  1331. }),
  1332. 500,
  1333. );
  1334. if (Meteor.isServer) {
  1335. // Let mongoDB ensure username unicity
  1336. Meteor.startup(() => {
  1337. allowedSortValues.forEach((value) => {
  1338. Lists._collection._ensureIndex(value);
  1339. });
  1340. Users._collection._ensureIndex({
  1341. modifiedAt: -1,
  1342. });
  1343. Users._collection._ensureIndex(
  1344. {
  1345. username: 1,
  1346. },
  1347. {
  1348. unique: true,
  1349. },
  1350. );
  1351. Meteor.defer(() => {
  1352. addCronJob();
  1353. });
  1354. });
  1355. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  1356. // if admin is removed, board is removed.
  1357. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  1358. // to use that board, and not have board deleted.
  1359. // Someone can be later changed to be admin of board, by making change to database.
  1360. // TODO: Add UI for changing someone as board admin.
  1361. //Users.before.remove((userId, doc) => {
  1362. // Boards
  1363. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  1364. // .forEach((board) => {
  1365. // // If only one admin for the board
  1366. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  1367. // Boards.remove(board._id);
  1368. // }
  1369. // });
  1370. //});
  1371. // Each board document contains the de-normalized number of users that have
  1372. // starred it. If the user star or unstar a board, we need to update this
  1373. // counter.
  1374. // We need to run this code on the server only, otherwise the incrementation
  1375. // will be done twice.
  1376. Users.after.update(function (userId, user, fieldNames) {
  1377. // The `starredBoards` list is hosted on the `profile` field. If this
  1378. // field hasn't been modificated we don't need to run this hook.
  1379. if (!_.contains(fieldNames, 'profile')) return;
  1380. // To calculate a diff of board starred ids, we get both the previous
  1381. // and the newly board ids list
  1382. function getStarredBoardsIds(doc) {
  1383. return doc.profile && doc.profile.starredBoards;
  1384. }
  1385. const oldIds = getStarredBoardsIds(this.previous);
  1386. const newIds = getStarredBoardsIds(user);
  1387. // The _.difference(a, b) method returns the values from a that are not in
  1388. // b. We use it to find deleted and newly inserted ids by using it in one
  1389. // direction and then in the other.
  1390. function incrementBoards(boardsIds, inc) {
  1391. boardsIds.forEach((boardId) => {
  1392. Boards.update(boardId, {
  1393. $inc: {
  1394. stars: inc,
  1395. },
  1396. });
  1397. });
  1398. }
  1399. incrementBoards(_.difference(oldIds, newIds), -1);
  1400. incrementBoards(_.difference(newIds, oldIds), +1);
  1401. });
  1402. // Override getUserId so that we can TODO get the current userId
  1403. const fakeUserId = new Meteor.EnvironmentVariable();
  1404. const getUserId = CollectionHooks.getUserId;
  1405. CollectionHooks.getUserId = () => {
  1406. return fakeUserId.get() || getUserId();
  1407. };
  1408. if (!isSandstorm) {
  1409. Users.after.insert((userId, doc) => {
  1410. const fakeUser = {
  1411. extendAutoValueContext: {
  1412. userId: doc._id,
  1413. },
  1414. };
  1415. fakeUserId.withValue(doc._id, () => {
  1416. /*
  1417. // Insert the Welcome Board
  1418. Boards.insert({
  1419. title: TAPi18n.__('welcome-board'),
  1420. permission: 'private',
  1421. }, fakeUser, (err, boardId) => {
  1422. Swimlanes.insert({
  1423. title: TAPi18n.__('welcome-swimlane'),
  1424. boardId,
  1425. sort: 1,
  1426. }, fakeUser);
  1427. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  1428. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  1429. });
  1430. });
  1431. */
  1432. const Future = require('fibers/future');
  1433. const future1 = new Future();
  1434. const future2 = new Future();
  1435. const future3 = new Future();
  1436. Boards.insert(
  1437. {
  1438. title: TAPi18n.__('templates'),
  1439. permission: 'private',
  1440. type: 'template-container',
  1441. },
  1442. fakeUser,
  1443. (err, boardId) => {
  1444. // Insert the reference to our templates board
  1445. Users.update(fakeUserId.get(), {
  1446. $set: {
  1447. 'profile.templatesBoardId': boardId,
  1448. },
  1449. });
  1450. // Insert the card templates swimlane
  1451. Swimlanes.insert(
  1452. {
  1453. title: TAPi18n.__('card-templates-swimlane'),
  1454. boardId,
  1455. sort: 1,
  1456. type: 'template-container',
  1457. },
  1458. fakeUser,
  1459. (err, swimlaneId) => {
  1460. // Insert the reference to out card templates swimlane
  1461. Users.update(fakeUserId.get(), {
  1462. $set: {
  1463. 'profile.cardTemplatesSwimlaneId': swimlaneId,
  1464. },
  1465. });
  1466. future1.return();
  1467. },
  1468. );
  1469. // Insert the list templates swimlane
  1470. Swimlanes.insert(
  1471. {
  1472. title: TAPi18n.__('list-templates-swimlane'),
  1473. boardId,
  1474. sort: 2,
  1475. type: 'template-container',
  1476. },
  1477. fakeUser,
  1478. (err, swimlaneId) => {
  1479. // Insert the reference to out list templates swimlane
  1480. Users.update(fakeUserId.get(), {
  1481. $set: {
  1482. 'profile.listTemplatesSwimlaneId': swimlaneId,
  1483. },
  1484. });
  1485. future2.return();
  1486. },
  1487. );
  1488. // Insert the board templates swimlane
  1489. Swimlanes.insert(
  1490. {
  1491. title: TAPi18n.__('board-templates-swimlane'),
  1492. boardId,
  1493. sort: 3,
  1494. type: 'template-container',
  1495. },
  1496. fakeUser,
  1497. (err, swimlaneId) => {
  1498. // Insert the reference to out board templates swimlane
  1499. Users.update(fakeUserId.get(), {
  1500. $set: {
  1501. 'profile.boardTemplatesSwimlaneId': swimlaneId,
  1502. },
  1503. });
  1504. future3.return();
  1505. },
  1506. );
  1507. },
  1508. );
  1509. // HACK
  1510. future1.wait();
  1511. future2.wait();
  1512. future3.wait();
  1513. });
  1514. });
  1515. }
  1516. Users.after.insert((userId, doc) => {
  1517. // HACK
  1518. doc = Users.findOne({
  1519. _id: doc._id,
  1520. });
  1521. if (doc.createdThroughApi) {
  1522. // The admin user should be able to create a user despite disabling registration because
  1523. // it is two different things (registration and creation).
  1524. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1525. // the disableRegistration check.
  1526. // Issue : https://github.com/wekan/wekan/issues/1232
  1527. // PR : https://github.com/wekan/wekan/pull/1251
  1528. Users.update(doc._id, {
  1529. $set: {
  1530. createdThroughApi: '',
  1531. },
  1532. });
  1533. return;
  1534. }
  1535. //invite user to corresponding boards
  1536. const disableRegistration = Settings.findOne().disableRegistration;
  1537. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1538. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1539. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1540. const invitationCode = InvitationCodes.findOne({
  1541. code: doc.profile.icode,
  1542. valid: true,
  1543. });
  1544. if (!invitationCode) {
  1545. throw new Meteor.Error('error-invitation-code-not-exist');
  1546. } else {
  1547. invitationCode.boardsToBeInvited.forEach((boardId) => {
  1548. const board = Boards.findOne(boardId);
  1549. board.addMember(doc._id);
  1550. });
  1551. if (!doc.profile) {
  1552. doc.profile = {};
  1553. }
  1554. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1555. Users.update(doc._id, {
  1556. $set: {
  1557. profile: doc.profile,
  1558. },
  1559. });
  1560. InvitationCodes.update(invitationCode._id, {
  1561. $set: {
  1562. valid: false,
  1563. },
  1564. });
  1565. }
  1566. }
  1567. });
  1568. }
  1569. // USERS REST API
  1570. if (Meteor.isServer) {
  1571. // Middleware which checks that API is enabled.
  1572. JsonRoutes.Middleware.use(function (req, res, next) {
  1573. const api = req.url.startsWith('/api');
  1574. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1575. return next();
  1576. } else {
  1577. res.writeHead(301, {
  1578. Location: '/',
  1579. });
  1580. return res.end();
  1581. }
  1582. });
  1583. /**
  1584. * @operation get_current_user
  1585. *
  1586. * @summary returns the current user
  1587. * @return_type Users
  1588. */
  1589. JsonRoutes.add('GET', '/api/user', function (req, res) {
  1590. try {
  1591. Authentication.checkLoggedIn(req.userId);
  1592. const data = Meteor.users.findOne({
  1593. _id: req.userId,
  1594. });
  1595. delete data.services;
  1596. // get all boards where the user is member of
  1597. let boards = Boards.find(
  1598. {
  1599. type: 'board',
  1600. 'members.userId': req.userId,
  1601. },
  1602. {
  1603. fields: {
  1604. _id: 1,
  1605. members: 1,
  1606. },
  1607. },
  1608. );
  1609. boards = boards.map((b) => {
  1610. const u = b.members.find((m) => m.userId === req.userId);
  1611. delete u.userId;
  1612. u.boardId = b._id;
  1613. return u;
  1614. });
  1615. data.boards = boards;
  1616. JsonRoutes.sendResult(res, {
  1617. code: 200,
  1618. data,
  1619. });
  1620. } catch (error) {
  1621. JsonRoutes.sendResult(res, {
  1622. code: 200,
  1623. data: error,
  1624. });
  1625. }
  1626. });
  1627. /**
  1628. * @operation get_all_users
  1629. *
  1630. * @summary return all the users
  1631. *
  1632. * @description Only the admin user (the first user) can call the REST API.
  1633. * @return_type [{ _id: string,
  1634. * username: string}]
  1635. */
  1636. JsonRoutes.add('GET', '/api/users', function (req, res) {
  1637. try {
  1638. Authentication.checkUserId(req.userId);
  1639. JsonRoutes.sendResult(res, {
  1640. code: 200,
  1641. data: Meteor.users.find({}).map(function (doc) {
  1642. return {
  1643. _id: doc._id,
  1644. username: doc.username,
  1645. };
  1646. }),
  1647. });
  1648. } catch (error) {
  1649. JsonRoutes.sendResult(res, {
  1650. code: 200,
  1651. data: error,
  1652. });
  1653. }
  1654. });
  1655. /**
  1656. * @operation get_user
  1657. *
  1658. * @summary get a given user
  1659. *
  1660. * @description Only the admin user (the first user) can call the REST API.
  1661. *
  1662. * @param {string} userId the user ID or username
  1663. * @return_type Users
  1664. */
  1665. JsonRoutes.add('GET', '/api/users/:userId', function (req, res) {
  1666. try {
  1667. Authentication.checkUserId(req.userId);
  1668. let id = req.params.userId;
  1669. let user = Meteor.users.findOne({
  1670. _id: id,
  1671. });
  1672. if (!user) {
  1673. user = Meteor.users.findOne({
  1674. username: id,
  1675. });
  1676. id = user._id;
  1677. }
  1678. // get all boards where the user is member of
  1679. let boards = Boards.find(
  1680. {
  1681. type: 'board',
  1682. 'members.userId': id,
  1683. },
  1684. {
  1685. fields: {
  1686. _id: 1,
  1687. members: 1,
  1688. },
  1689. },
  1690. );
  1691. boards = boards.map((b) => {
  1692. const u = b.members.find((m) => m.userId === id);
  1693. delete u.userId;
  1694. u.boardId = b._id;
  1695. return u;
  1696. });
  1697. user.boards = boards;
  1698. JsonRoutes.sendResult(res, {
  1699. code: 200,
  1700. data: user,
  1701. });
  1702. } catch (error) {
  1703. JsonRoutes.sendResult(res, {
  1704. code: 200,
  1705. data: error,
  1706. });
  1707. }
  1708. });
  1709. /**
  1710. * @operation edit_user
  1711. *
  1712. * @summary edit a given user
  1713. *
  1714. * @description Only the admin user (the first user) can call the REST API.
  1715. *
  1716. * Possible values for *action*:
  1717. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1718. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1719. * - `enableLogin`: Enable a user
  1720. *
  1721. * @param {string} userId the user ID
  1722. * @param {string} action the action
  1723. * @return_type {_id: string,
  1724. * title: string}
  1725. */
  1726. JsonRoutes.add('PUT', '/api/users/:userId', function (req, res) {
  1727. try {
  1728. Authentication.checkUserId(req.userId);
  1729. const id = req.params.userId;
  1730. const action = req.body.action;
  1731. let data = Meteor.users.findOne({
  1732. _id: id,
  1733. });
  1734. if (data !== undefined) {
  1735. if (action === 'takeOwnership') {
  1736. data = Boards.find(
  1737. {
  1738. 'members.userId': id,
  1739. 'members.isAdmin': true,
  1740. },
  1741. {
  1742. sort: {
  1743. sort: 1 /* boards default sorting */,
  1744. },
  1745. },
  1746. ).map(function (board) {
  1747. if (board.hasMember(req.userId)) {
  1748. board.removeMember(req.userId);
  1749. }
  1750. board.changeOwnership(id, req.userId);
  1751. return {
  1752. _id: board._id,
  1753. title: board.title,
  1754. };
  1755. });
  1756. } else {
  1757. if (action === 'disableLogin' && id !== req.userId) {
  1758. Users.update(
  1759. {
  1760. _id: id,
  1761. },
  1762. {
  1763. $set: {
  1764. loginDisabled: true,
  1765. 'services.resume.loginTokens': '',
  1766. },
  1767. },
  1768. );
  1769. } else if (action === 'enableLogin') {
  1770. Users.update(
  1771. {
  1772. _id: id,
  1773. },
  1774. {
  1775. $set: {
  1776. loginDisabled: '',
  1777. },
  1778. },
  1779. );
  1780. }
  1781. data = Meteor.users.findOne({
  1782. _id: id,
  1783. });
  1784. }
  1785. }
  1786. JsonRoutes.sendResult(res, {
  1787. code: 200,
  1788. data,
  1789. });
  1790. } catch (error) {
  1791. JsonRoutes.sendResult(res, {
  1792. code: 200,
  1793. data: error,
  1794. });
  1795. }
  1796. });
  1797. /**
  1798. * @operation add_board_member
  1799. * @tag Boards
  1800. *
  1801. * @summary Add New Board Member with Role
  1802. *
  1803. * @description Only the admin user (the first user) can call the REST API.
  1804. *
  1805. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1806. * to later change the permissions.
  1807. *
  1808. * @param {string} boardId the board ID
  1809. * @param {string} userId the user ID
  1810. * @param {boolean} isAdmin is the user an admin of the board
  1811. * @param {boolean} isNoComments disable comments
  1812. * @param {boolean} isCommentOnly only enable comments
  1813. * @return_type {_id: string,
  1814. * title: string}
  1815. */
  1816. JsonRoutes.add(
  1817. 'POST',
  1818. '/api/boards/:boardId/members/:userId/add',
  1819. function (req, res) {
  1820. try {
  1821. Authentication.checkUserId(req.userId);
  1822. const userId = req.params.userId;
  1823. const boardId = req.params.boardId;
  1824. const action = req.body.action;
  1825. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1826. let data = Meteor.users.findOne({
  1827. _id: userId,
  1828. });
  1829. if (data !== undefined) {
  1830. if (action === 'add') {
  1831. data = Boards.find({
  1832. _id: boardId,
  1833. }).map(function (board) {
  1834. if (!board.hasMember(userId)) {
  1835. board.addMember(userId);
  1836. function isTrue(data) {
  1837. return data.toLowerCase() === 'true';
  1838. }
  1839. board.setMemberPermission(
  1840. userId,
  1841. isTrue(isAdmin),
  1842. isTrue(isNoComments),
  1843. isTrue(isCommentOnly),
  1844. userId,
  1845. );
  1846. }
  1847. return {
  1848. _id: board._id,
  1849. title: board.title,
  1850. };
  1851. });
  1852. }
  1853. }
  1854. JsonRoutes.sendResult(res, {
  1855. code: 200,
  1856. data: query,
  1857. });
  1858. } catch (error) {
  1859. JsonRoutes.sendResult(res, {
  1860. code: 200,
  1861. data: error,
  1862. });
  1863. }
  1864. },
  1865. );
  1866. /**
  1867. * @operation remove_board_member
  1868. * @tag Boards
  1869. *
  1870. * @summary Remove Member from Board
  1871. *
  1872. * @description Only the admin user (the first user) can call the REST API.
  1873. *
  1874. * @param {string} boardId the board ID
  1875. * @param {string} userId the user ID
  1876. * @param {string} action the action (needs to be `remove`)
  1877. * @return_type {_id: string,
  1878. * title: string}
  1879. */
  1880. JsonRoutes.add(
  1881. 'POST',
  1882. '/api/boards/:boardId/members/:userId/remove',
  1883. function (req, res) {
  1884. try {
  1885. Authentication.checkUserId(req.userId);
  1886. const userId = req.params.userId;
  1887. const boardId = req.params.boardId;
  1888. const action = req.body.action;
  1889. let data = Meteor.users.findOne({
  1890. _id: userId,
  1891. });
  1892. if (data !== undefined) {
  1893. if (action === 'remove') {
  1894. data = Boards.find({
  1895. _id: boardId,
  1896. }).map(function (board) {
  1897. if (board.hasMember(userId)) {
  1898. board.removeMember(userId);
  1899. }
  1900. return {
  1901. _id: board._id,
  1902. title: board.title,
  1903. };
  1904. });
  1905. }
  1906. }
  1907. JsonRoutes.sendResult(res, {
  1908. code: 200,
  1909. data: query,
  1910. });
  1911. } catch (error) {
  1912. JsonRoutes.sendResult(res, {
  1913. code: 200,
  1914. data: error,
  1915. });
  1916. }
  1917. },
  1918. );
  1919. /**
  1920. * @operation new_user
  1921. *
  1922. * @summary Create a new user
  1923. *
  1924. * @description Only the admin user (the first user) can call the REST API.
  1925. *
  1926. * @param {string} username the new username
  1927. * @param {string} email the email of the new user
  1928. * @param {string} password the password of the new user
  1929. * @return_type {_id: string}
  1930. */
  1931. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  1932. try {
  1933. Authentication.checkUserId(req.userId);
  1934. const id = Accounts.createUser({
  1935. username: req.body.username,
  1936. email: req.body.email,
  1937. password: req.body.password,
  1938. from: 'admin',
  1939. });
  1940. JsonRoutes.sendResult(res, {
  1941. code: 200,
  1942. data: {
  1943. _id: id,
  1944. },
  1945. });
  1946. } catch (error) {
  1947. JsonRoutes.sendResult(res, {
  1948. code: 200,
  1949. data: error,
  1950. });
  1951. }
  1952. });
  1953. /**
  1954. * @operation delete_user
  1955. *
  1956. * @summary Delete a user
  1957. *
  1958. * @description Only the admin user (the first user) can call the REST API.
  1959. *
  1960. * @param {string} userId the ID of the user to delete
  1961. * @return_type {_id: string}
  1962. */
  1963. JsonRoutes.add('DELETE', '/api/users/:userId', function (req, res) {
  1964. try {
  1965. Authentication.checkUserId(req.userId);
  1966. const id = req.params.userId;
  1967. // Delete is not enabled yet, because it does leave empty user avatars
  1968. // to boards: boards members, card members and assignees have
  1969. // empty users. See:
  1970. // - wekan/client/components/settings/peopleBody.jade deleteButton
  1971. // - wekan/client/components/settings/peopleBody.js deleteButton
  1972. // - wekan/client/components/sidebar/sidebar.js Popup.afterConfirm('removeMember'
  1973. // that does now remove member from board, card members and assignees correctly,
  1974. // but that should be used to remove user from all boards similarly
  1975. // - wekan/models/users.js Delete is not enabled
  1976. // Meteor.users.remove({ _id: id });
  1977. JsonRoutes.sendResult(res, {
  1978. code: 200,
  1979. data: {
  1980. _id: id,
  1981. },
  1982. });
  1983. } catch (error) {
  1984. JsonRoutes.sendResult(res, {
  1985. code: 200,
  1986. data: error,
  1987. });
  1988. }
  1989. });
  1990. /**
  1991. * @operation create_user_token
  1992. *
  1993. * @summary Create a user token
  1994. *
  1995. * @description Only the admin user (the first user) can call the REST API.
  1996. *
  1997. * @param {string} userId the ID of the user to create token for.
  1998. * @return_type {_id: string}
  1999. */
  2000. JsonRoutes.add('POST', '/api/createtoken/:userId', function (req, res) {
  2001. try {
  2002. Authentication.checkUserId(req.userId);
  2003. const id = req.params.userId;
  2004. const token = Accounts._generateStampedLoginToken();
  2005. Accounts._insertLoginToken(id, token);
  2006. JsonRoutes.sendResult(res, {
  2007. code: 200,
  2008. data: {
  2009. _id: id,
  2010. authToken: token.token,
  2011. },
  2012. });
  2013. } catch (error) {
  2014. JsonRoutes.sendResult(res, {
  2015. code: 200,
  2016. data: error,
  2017. });
  2018. }
  2019. });
  2020. }
  2021. export default Users;