users.js 56 KB

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