users.js 53 KB

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