users.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  1. import { SyncedCron } from 'meteor/percolate:synced-cron';
  2. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  3. // in the package definition.
  4. const isSandstorm =
  5. Meteor.settings && Meteor.settings.public && Meteor.settings.public.sandstorm;
  6. Users = Meteor.users;
  7. const allowedSortValues = [
  8. '-modifiedAt',
  9. 'modifiedAt',
  10. '-title',
  11. 'title',
  12. '-sort',
  13. 'sort',
  14. ];
  15. const defaultSortBy = allowedSortValues[0];
  16. /**
  17. * A User in wekan
  18. */
  19. Users.attachSchema(
  20. new SimpleSchema({
  21. username: {
  22. /**
  23. * the username of the user
  24. */
  25. type: String,
  26. optional: true,
  27. // eslint-disable-next-line consistent-return
  28. autoValue() {
  29. if (this.isInsert && !this.isSet) {
  30. const name = this.field('profile.fullname');
  31. if (name.isSet) {
  32. return name.value.toLowerCase().replace(/\s/g, '');
  33. }
  34. }
  35. },
  36. },
  37. emails: {
  38. /**
  39. * the list of emails attached to a user
  40. */
  41. type: [Object],
  42. optional: true,
  43. },
  44. 'emails.$.address': {
  45. /**
  46. * The email address
  47. */
  48. type: String,
  49. regEx: SimpleSchema.RegEx.Email,
  50. },
  51. 'emails.$.verified': {
  52. /**
  53. * Has the email been verified
  54. */
  55. type: Boolean,
  56. },
  57. createdAt: {
  58. /**
  59. * creation date of the user
  60. */
  61. type: Date,
  62. // eslint-disable-next-line consistent-return
  63. autoValue() {
  64. if (this.isInsert) {
  65. return new Date();
  66. } else if (this.isUpsert) {
  67. return { $setOnInsert: new Date() };
  68. } else {
  69. this.unset();
  70. }
  71. },
  72. },
  73. modifiedAt: {
  74. type: Date,
  75. denyUpdate: false,
  76. // eslint-disable-next-line consistent-return
  77. autoValue() {
  78. if (this.isInsert || this.isUpsert || this.isUpdate) {
  79. return new Date();
  80. } else {
  81. this.unset();
  82. }
  83. },
  84. },
  85. profile: {
  86. /**
  87. * profile settings
  88. */
  89. type: Object,
  90. optional: true,
  91. // eslint-disable-next-line consistent-return
  92. autoValue() {
  93. if (this.isInsert && !this.isSet) {
  94. return {
  95. boardView: 'board-view-lists',
  96. };
  97. }
  98. },
  99. },
  100. 'profile.avatarUrl': {
  101. /**
  102. * URL of the avatar of the user
  103. */
  104. type: String,
  105. optional: true,
  106. },
  107. 'profile.emailBuffer': {
  108. /**
  109. * list of email buffers of the user
  110. */
  111. type: [String],
  112. optional: true,
  113. },
  114. 'profile.fullname': {
  115. /**
  116. * full name of the user
  117. */
  118. type: String,
  119. optional: true,
  120. },
  121. 'profile.showDesktopDragHandles': {
  122. /**
  123. * does the user want to hide system messages?
  124. */
  125. type: Boolean,
  126. optional: true,
  127. },
  128. 'profile.hiddenSystemMessages': {
  129. /**
  130. * does the user want to hide system messages?
  131. */
  132. type: Boolean,
  133. optional: true,
  134. },
  135. 'profile.hiddenMinicardLabelText': {
  136. /**
  137. * does the user want to hide minicard label texts?
  138. */
  139. type: Boolean,
  140. optional: true,
  141. },
  142. 'profile.initials': {
  143. /**
  144. * initials of the user
  145. */
  146. type: String,
  147. optional: true,
  148. },
  149. 'profile.invitedBoards': {
  150. /**
  151. * board IDs the user has been invited to
  152. */
  153. type: [String],
  154. optional: true,
  155. },
  156. 'profile.language': {
  157. /**
  158. * language of the user
  159. */
  160. type: String,
  161. optional: true,
  162. },
  163. 'profile.notifications': {
  164. /**
  165. * enabled notifications for the user
  166. */
  167. type: [Object],
  168. optional: true,
  169. },
  170. 'profile.notifications.$.activity': {
  171. /**
  172. * The id of the activity this notification references
  173. */
  174. type: String,
  175. },
  176. 'profile.notifications.$.read': {
  177. /**
  178. * the date on which this notification was read
  179. */
  180. type: Date,
  181. optional: true,
  182. },
  183. 'profile.showCardsCountAt': {
  184. /**
  185. * showCardCountAt field of the user
  186. */
  187. type: Number,
  188. optional: true,
  189. },
  190. 'profile.starredBoards': {
  191. /**
  192. * list of starred board IDs
  193. */
  194. type: [String],
  195. optional: true,
  196. },
  197. 'profile.icode': {
  198. /**
  199. * icode
  200. */
  201. type: String,
  202. optional: true,
  203. },
  204. 'profile.boardView': {
  205. /**
  206. * boardView field of the user
  207. */
  208. type: String,
  209. optional: true,
  210. allowedValues: [
  211. 'board-view-lists',
  212. 'board-view-swimlanes',
  213. 'board-view-cal',
  214. ],
  215. },
  216. 'profile.listSortBy': {
  217. /**
  218. * default sort list for user
  219. */
  220. type: String,
  221. optional: true,
  222. defaultValue: defaultSortBy,
  223. allowedValues: allowedSortValues,
  224. },
  225. 'profile.templatesBoardId': {
  226. /**
  227. * Reference to the templates board
  228. */
  229. type: String,
  230. defaultValue: '',
  231. },
  232. 'profile.cardTemplatesSwimlaneId': {
  233. /**
  234. * Reference to the card templates swimlane Id
  235. */
  236. type: String,
  237. defaultValue: '',
  238. },
  239. 'profile.listTemplatesSwimlaneId': {
  240. /**
  241. * Reference to the list templates swimlane Id
  242. */
  243. type: String,
  244. defaultValue: '',
  245. },
  246. 'profile.boardTemplatesSwimlaneId': {
  247. /**
  248. * Reference to the board templates swimlane Id
  249. */
  250. type: String,
  251. defaultValue: '',
  252. },
  253. services: {
  254. /**
  255. * services field of the user
  256. */
  257. type: Object,
  258. optional: true,
  259. blackbox: true,
  260. },
  261. heartbeat: {
  262. /**
  263. * last time the user has been seen
  264. */
  265. type: Date,
  266. optional: true,
  267. },
  268. isAdmin: {
  269. /**
  270. * is the user an admin of the board?
  271. */
  272. type: Boolean,
  273. optional: true,
  274. },
  275. createdThroughApi: {
  276. /**
  277. * was the user created through the API?
  278. */
  279. type: Boolean,
  280. optional: true,
  281. },
  282. loginDisabled: {
  283. /**
  284. * loginDisabled field of the user
  285. */
  286. type: Boolean,
  287. optional: true,
  288. },
  289. authenticationMethod: {
  290. /**
  291. * authentication method of the user
  292. */
  293. type: String,
  294. optional: false,
  295. defaultValue: 'password',
  296. },
  297. }),
  298. );
  299. Users.allow({
  300. update(userId, doc) {
  301. const user = Users.findOne({ _id: userId });
  302. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  303. return true;
  304. if (!user) {
  305. return false;
  306. }
  307. return doc._id === userId;
  308. },
  309. remove(userId, doc) {
  310. const adminsNumber = Users.find({ isAdmin: true }).count();
  311. const { isAdmin } = Users.findOne(
  312. { _id: userId },
  313. { fields: { isAdmin: 1 } },
  314. );
  315. // Prevents remove of the only one administrator
  316. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  317. return false;
  318. }
  319. // If it's the user or an admin
  320. return userId === doc._id || isAdmin;
  321. },
  322. fetch: [],
  323. });
  324. // Search a user in the complete server database by its name or username. This
  325. // is used for instance to add a new user to a board.
  326. const searchInFields = ['username', 'profile.fullname'];
  327. Users.initEasySearch(searchInFields, {
  328. use: 'mongo-db',
  329. returnFields: [...searchInFields, 'profile.avatarUrl'],
  330. });
  331. if (Meteor.isClient) {
  332. Users.helpers({
  333. isBoardMember() {
  334. const board = Boards.findOne(Session.get('currentBoard'));
  335. return board && board.hasMember(this._id);
  336. },
  337. isNotNoComments() {
  338. const board = Boards.findOne(Session.get('currentBoard'));
  339. return (
  340. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  341. );
  342. },
  343. isNoComments() {
  344. const board = Boards.findOne(Session.get('currentBoard'));
  345. return board && board.hasNoComments(this._id);
  346. },
  347. isNotCommentOnly() {
  348. const board = Boards.findOne(Session.get('currentBoard'));
  349. return (
  350. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  351. );
  352. },
  353. isCommentOnly() {
  354. const board = Boards.findOne(Session.get('currentBoard'));
  355. return board && board.hasCommentOnly(this._id);
  356. },
  357. isNotWorker() {
  358. const board = Boards.findOne(Session.get('currentBoard'));
  359. return board && board.hasMember(this._id) && !board.hasWorker(this._id);
  360. },
  361. isWorker() {
  362. const board = Boards.findOne(Session.get('currentBoard'));
  363. return board && board.hasWorker(this._id);
  364. },
  365. isBoardAdmin() {
  366. const board = Boards.findOne(Session.get('currentBoard'));
  367. return board && board.hasAdmin(this._id);
  368. },
  369. });
  370. }
  371. Users.helpers({
  372. boards() {
  373. return Boards.find({ 'members.userId': this._id });
  374. },
  375. starredBoards() {
  376. const { starredBoards = [] } = this.profile || {};
  377. return Boards.find({ archived: false, _id: { $in: starredBoards } });
  378. },
  379. hasStarred(boardId) {
  380. const { starredBoards = [] } = this.profile || {};
  381. return _.contains(starredBoards, boardId);
  382. },
  383. invitedBoards() {
  384. const { invitedBoards = [] } = this.profile || {};
  385. return Boards.find({ archived: false, _id: { $in: invitedBoards } });
  386. },
  387. isInvitedTo(boardId) {
  388. const { invitedBoards = [] } = this.profile || {};
  389. return _.contains(invitedBoards, boardId);
  390. },
  391. _getListSortBy() {
  392. const profile = this.profile || {};
  393. const sortBy = profile.listSortBy || defaultSortBy;
  394. const keyPattern = /^(-{0,1})(.*$)/;
  395. const ret = [];
  396. if (keyPattern.exec(sortBy)) {
  397. ret[0] = RegExp.$2;
  398. ret[1] = RegExp.$1 ? -1 : 1;
  399. }
  400. return ret;
  401. },
  402. hasSortBy() {
  403. // if use doesn't have dragHandle, then we can let user to choose sort list by different order
  404. return !this.hasShowDesktopDragHandles();
  405. },
  406. getListSortBy() {
  407. return this._getListSortBy()[0];
  408. },
  409. getListSortTypes() {
  410. return allowedSortValues;
  411. },
  412. getListSortByDirection() {
  413. return this._getListSortBy()[1];
  414. },
  415. hasTag(tag) {
  416. const { tags = [] } = this.profile || {};
  417. return _.contains(tags, tag);
  418. },
  419. hasNotification(activityId) {
  420. const { notifications = [] } = this.profile || {};
  421. return _.contains(notifications, activityId);
  422. },
  423. notifications() {
  424. const { notifications = [] } = this.profile || {};
  425. for (const index in notifications) {
  426. if (!notifications.hasOwnProperty(index)) continue;
  427. const notification = notifications[index];
  428. // this preserves their db sort order for editing
  429. notification.dbIndex = index;
  430. notification.activity = Activities.findOne(notification.activity);
  431. }
  432. // this sorts them newest to oldest to match Trello's behavior
  433. notifications.reverse();
  434. return notifications;
  435. },
  436. hasShowDesktopDragHandles() {
  437. const profile = this.profile || {};
  438. return profile.showDesktopDragHandles || false;
  439. },
  440. hasHiddenSystemMessages() {
  441. const profile = this.profile || {};
  442. return profile.hiddenSystemMessages || false;
  443. },
  444. hasHiddenMinicardLabelText() {
  445. const profile = this.profile || {};
  446. return profile.hiddenMinicardLabelText || false;
  447. },
  448. getEmailBuffer() {
  449. const { emailBuffer = [] } = this.profile || {};
  450. return emailBuffer;
  451. },
  452. getInitials() {
  453. const profile = this.profile || {};
  454. if (profile.initials) return profile.initials;
  455. else if (profile.fullname) {
  456. return profile.fullname
  457. .split(/\s+/)
  458. .reduce((memo, word) => {
  459. return memo + word[0];
  460. }, '')
  461. .toUpperCase();
  462. } else {
  463. return this.username[0].toUpperCase();
  464. }
  465. },
  466. getLimitToShowCardsCount() {
  467. const profile = this.profile || {};
  468. return profile.showCardsCountAt;
  469. },
  470. getName() {
  471. const profile = this.profile || {};
  472. return profile.fullname || this.username;
  473. },
  474. getLanguage() {
  475. const profile = this.profile || {};
  476. return profile.language || 'en';
  477. },
  478. getTemplatesBoardId() {
  479. return (this.profile || {}).templatesBoardId;
  480. },
  481. getTemplatesBoardSlug() {
  482. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  483. },
  484. remove() {
  485. User.remove({ _id: this._id });
  486. },
  487. });
  488. Users.mutations({
  489. toggleBoardStar(boardId) {
  490. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  491. return {
  492. [queryKind]: {
  493. 'profile.starredBoards': boardId,
  494. },
  495. };
  496. },
  497. addInvite(boardId) {
  498. return {
  499. $addToSet: {
  500. 'profile.invitedBoards': boardId,
  501. },
  502. };
  503. },
  504. removeInvite(boardId) {
  505. return {
  506. $pull: {
  507. 'profile.invitedBoards': boardId,
  508. },
  509. };
  510. },
  511. addTag(tag) {
  512. return {
  513. $addToSet: {
  514. 'profile.tags': tag,
  515. },
  516. };
  517. },
  518. removeTag(tag) {
  519. return {
  520. $pull: {
  521. 'profile.tags': tag,
  522. },
  523. };
  524. },
  525. toggleTag(tag) {
  526. if (this.hasTag(tag)) this.removeTag(tag);
  527. else this.addTag(tag);
  528. },
  529. setListSortBy(value) {
  530. return {
  531. $set: {
  532. 'profile.listSortBy': value,
  533. },
  534. };
  535. },
  536. toggleDesktopHandles(value = false) {
  537. return {
  538. $set: {
  539. 'profile.showDesktopDragHandles': !value,
  540. },
  541. };
  542. },
  543. toggleSystem(value = false) {
  544. return {
  545. $set: {
  546. 'profile.hiddenSystemMessages': !value,
  547. },
  548. };
  549. },
  550. toggleLabelText(value = false) {
  551. return {
  552. $set: {
  553. 'profile.hiddenMinicardLabelText': !value,
  554. },
  555. };
  556. },
  557. addNotification(activityId) {
  558. return {
  559. $addToSet: {
  560. 'profile.notifications': { activity: activityId },
  561. },
  562. };
  563. },
  564. removeNotification(activityId) {
  565. return {
  566. $pull: {
  567. 'profile.notifications': { activity: activityId },
  568. },
  569. };
  570. },
  571. addEmailBuffer(text) {
  572. return {
  573. $addToSet: {
  574. 'profile.emailBuffer': text,
  575. },
  576. };
  577. },
  578. clearEmailBuffer() {
  579. return {
  580. $set: {
  581. 'profile.emailBuffer': [],
  582. },
  583. };
  584. },
  585. setAvatarUrl(avatarUrl) {
  586. return { $set: { 'profile.avatarUrl': avatarUrl } };
  587. },
  588. setShowCardsCountAt(limit) {
  589. return { $set: { 'profile.showCardsCountAt': limit } };
  590. },
  591. setBoardView(view) {
  592. return {
  593. $set: {
  594. 'profile.boardView': view,
  595. },
  596. };
  597. },
  598. });
  599. Meteor.methods({
  600. setListSortBy(value) {
  601. check(value, String);
  602. Meteor.user().setListSortBy(value);
  603. },
  604. toggleDesktopDragHandles() {
  605. const user = Meteor.user();
  606. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  607. },
  608. toggleSystemMessages() {
  609. const user = Meteor.user();
  610. user.toggleSystem(user.hasHiddenSystemMessages());
  611. },
  612. toggleMinicardLabelText() {
  613. const user = Meteor.user();
  614. user.toggleLabelText(user.hasHiddenMinicardLabelText());
  615. },
  616. changeLimitToShowCardsCount(limit) {
  617. check(limit, Number);
  618. Meteor.user().setShowCardsCountAt(limit);
  619. },
  620. });
  621. if (Meteor.isServer) {
  622. Meteor.methods({
  623. setCreateUser(fullname, username, password, isAdmin, isActive, email) {
  624. if (Meteor.user() && Meteor.user().isAdmin) {
  625. check(fullname, String);
  626. check(username, String);
  627. check(password, String);
  628. check(isAdmin, String);
  629. check(isActive, String);
  630. check(email, String);
  631. const nUsersWithUsername = Users.find({ username }).count();
  632. const nUsersWithEmail = Users.find({ email }).count();
  633. if (nUsersWithUsername > 0) {
  634. throw new Meteor.Error('username-already-taken');
  635. } else if (nUsersWithEmail > 0) {
  636. throw new Meteor.Error('email-already-taken');
  637. } else {
  638. Accounts.createUser({
  639. fullname,
  640. username,
  641. password,
  642. isAdmin,
  643. isActive,
  644. email: email.toLowerCase(),
  645. from: 'admin',
  646. });
  647. }
  648. }
  649. },
  650. setUsername(username, userId) {
  651. if (Meteor.user() && Meteor.user().isAdmin) {
  652. check(username, String);
  653. check(userId, String);
  654. const nUsersWithUsername = Users.find({ username }).count();
  655. if (nUsersWithUsername > 0) {
  656. throw new Meteor.Error('username-already-taken');
  657. } else {
  658. Users.update(userId, { $set: { username } });
  659. }
  660. }
  661. },
  662. setEmail(email, userId) {
  663. if (Meteor.user() && Meteor.user().isAdmin) {
  664. if (Array.isArray(email)) {
  665. email = email.shift();
  666. }
  667. check(email, String);
  668. const existingUser = Users.findOne(
  669. { 'emails.address': email },
  670. { fields: { _id: 1 } },
  671. );
  672. if (existingUser) {
  673. throw new Meteor.Error('email-already-taken');
  674. } else {
  675. Users.update(userId, {
  676. $set: {
  677. emails: [
  678. {
  679. address: email,
  680. verified: false,
  681. },
  682. ],
  683. },
  684. });
  685. }
  686. }
  687. },
  688. setUsernameAndEmail(username, email, userId) {
  689. if (Meteor.user() && Meteor.user().isAdmin) {
  690. check(username, String);
  691. if (Array.isArray(email)) {
  692. email = email.shift();
  693. }
  694. check(email, String);
  695. check(userId, String);
  696. Meteor.call('setUsername', username, userId);
  697. Meteor.call('setEmail', email, userId);
  698. }
  699. },
  700. setPassword(newPassword, userId) {
  701. if (Meteor.user() && Meteor.user().isAdmin) {
  702. check(userId, String);
  703. check(newPassword, String);
  704. if (Meteor.user().isAdmin) {
  705. Accounts.setPassword(userId, newPassword);
  706. }
  707. }
  708. },
  709. // we accept userId, username, email
  710. inviteUserToBoard(username, boardId) {
  711. check(username, String);
  712. check(boardId, String);
  713. const inviter = Meteor.user();
  714. const board = Boards.findOne(boardId);
  715. const allowInvite =
  716. inviter &&
  717. board &&
  718. board.members &&
  719. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  720. _.where(board.members, { userId: inviter._id })[0].isActive;
  721. // GitHub issue 2060
  722. //_.where(board.members, { userId: inviter._id })[0].isAdmin;
  723. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  724. this.unblock();
  725. const posAt = username.indexOf('@');
  726. let user = null;
  727. if (posAt >= 0) {
  728. user = Users.findOne({ emails: { $elemMatch: { address: username } } });
  729. } else {
  730. user = Users.findOne(username) || Users.findOne({ username });
  731. }
  732. if (user) {
  733. if (user._id === inviter._id)
  734. throw new Meteor.Error('error-user-notAllowSelf');
  735. } else {
  736. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  737. if (Settings.findOne({ disableRegistration: true })) {
  738. throw new Meteor.Error('error-user-notCreated');
  739. }
  740. // Set in lowercase email before creating account
  741. const email = username.toLowerCase();
  742. username = email.substring(0, posAt);
  743. const newUserId = Accounts.createUser({ username, email });
  744. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  745. // assume new user speak same language with inviter
  746. if (inviter.profile && inviter.profile.language) {
  747. Users.update(newUserId, {
  748. $set: {
  749. 'profile.language': inviter.profile.language,
  750. },
  751. });
  752. }
  753. Accounts.sendEnrollmentEmail(newUserId);
  754. user = Users.findOne(newUserId);
  755. }
  756. board.addMember(user._id);
  757. user.addInvite(boardId);
  758. try {
  759. const params = {
  760. user: user.username,
  761. inviter: inviter.username,
  762. board: board.title,
  763. url: board.absoluteUrl(),
  764. };
  765. const lang = user.getLanguage();
  766. Email.send({
  767. to: user.emails[0].address.toLowerCase(),
  768. from: Accounts.emailTemplates.from,
  769. subject: TAPi18n.__('email-invite-subject', params, lang),
  770. text: TAPi18n.__('email-invite-text', params, lang),
  771. });
  772. } catch (e) {
  773. throw new Meteor.Error('email-fail', e.message);
  774. }
  775. return { username: user.username, email: user.emails[0].address };
  776. },
  777. });
  778. Accounts.onCreateUser((options, user) => {
  779. const userCount = Users.find().count();
  780. if (userCount === 0) {
  781. user.isAdmin = true;
  782. return user;
  783. }
  784. if (user.services.oidc) {
  785. let email = user.services.oidc.email;
  786. if (Array.isArray(email)) {
  787. email = email.shift();
  788. }
  789. email = email.toLowerCase();
  790. user.username = user.services.oidc.username;
  791. user.emails = [{ address: email, verified: true }];
  792. const initials = user.services.oidc.fullname
  793. .match(/\b[a-zA-Z]/g)
  794. .join('')
  795. .toUpperCase();
  796. user.profile = {
  797. initials,
  798. fullname: user.services.oidc.fullname,
  799. boardView: 'board-view-lists',
  800. };
  801. user.authenticationMethod = 'oauth2';
  802. // see if any existing user has this email address or username, otherwise create new
  803. const existingUser = Meteor.users.findOne({
  804. $or: [{ 'emails.address': email }, { username: user.username }],
  805. });
  806. if (!existingUser) return user;
  807. // copy across new service info
  808. const service = _.keys(user.services)[0];
  809. existingUser.services[service] = user.services[service];
  810. existingUser.emails = user.emails;
  811. existingUser.username = user.username;
  812. existingUser.profile = user.profile;
  813. existingUser.authenticationMethod = user.authenticationMethod;
  814. Meteor.users.remove({ _id: existingUser._id }); // remove existing record
  815. return existingUser;
  816. }
  817. if (options.from === 'admin') {
  818. user.createdThroughApi = true;
  819. return user;
  820. }
  821. const disableRegistration = Settings.findOne().disableRegistration;
  822. // If this is the first Authentication by the ldap and self registration disabled
  823. if (disableRegistration && options && options.ldap) {
  824. user.authenticationMethod = 'ldap';
  825. return user;
  826. }
  827. // If self registration enabled
  828. if (!disableRegistration) {
  829. return user;
  830. }
  831. if (!options || !options.profile) {
  832. throw new Meteor.Error(
  833. 'error-invitation-code-blank',
  834. 'The invitation code is required',
  835. );
  836. }
  837. const invitationCode = InvitationCodes.findOne({
  838. code: options.profile.invitationcode,
  839. email: options.email,
  840. valid: true,
  841. });
  842. if (!invitationCode) {
  843. throw new Meteor.Error(
  844. 'error-invitation-code-not-exist',
  845. // eslint-disable-next-line quotes
  846. "The invitation code doesn't exist",
  847. );
  848. } else {
  849. user.profile = { icode: options.profile.invitationcode };
  850. user.profile.boardView = 'board-view-lists';
  851. // Deletes the invitation code after the user was created successfully.
  852. setTimeout(
  853. Meteor.bindEnvironment(() => {
  854. InvitationCodes.remove({ _id: invitationCode._id });
  855. }),
  856. 200,
  857. );
  858. return user;
  859. }
  860. });
  861. }
  862. const addCronJob = _.debounce(
  863. Meteor.bindEnvironment(function notificationCleanupDebounced() {
  864. // passed in the removeAge has to be a number standing for the number of days after a notification is read before we remove it
  865. const envRemoveAge =
  866. process.env.NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE;
  867. // default notifications will be removed 2 days after they are read
  868. const defaultRemoveAge = 2;
  869. const removeAge = parseInt(envRemoveAge, 10) || defaultRemoveAge;
  870. SyncedCron.add({
  871. name: 'notification_cleanup',
  872. schedule: parser => parser.text('every 1 days'),
  873. job: () => {
  874. for (const user of Users.find()) {
  875. for (const notification of user.profile.notifications) {
  876. if (notification.read) {
  877. const removeDate = new Date(notification.read);
  878. removeDate.setDate(removeDate.getDate() + removeAge);
  879. if (removeDate <= new Date()) {
  880. user.removeNotification(notification.activity);
  881. }
  882. }
  883. }
  884. }
  885. },
  886. });
  887. SyncedCron.start();
  888. }),
  889. 500,
  890. );
  891. if (Meteor.isServer) {
  892. // Let mongoDB ensure username unicity
  893. Meteor.startup(() => {
  894. allowedSortValues.forEach(value => {
  895. Lists._collection._ensureIndex(value);
  896. });
  897. Users._collection._ensureIndex({ modifiedAt: -1 });
  898. Users._collection._ensureIndex(
  899. {
  900. username: 1,
  901. },
  902. { unique: true },
  903. );
  904. Meteor.defer(() => {
  905. addCronJob();
  906. });
  907. });
  908. // OLD WAY THIS CODE DID WORK: When user is last admin of board,
  909. // if admin is removed, board is removed.
  910. // NOW THIS IS COMMENTED OUT, because other board users still need to be able
  911. // to use that board, and not have board deleted.
  912. // Someone can be later changed to be admin of board, by making change to database.
  913. // TODO: Add UI for changing someone as board admin.
  914. //Users.before.remove((userId, doc) => {
  915. // Boards
  916. // .find({members: {$elemMatch: {userId: doc._id, isAdmin: true}}})
  917. // .forEach((board) => {
  918. // // If only one admin for the board
  919. // if (board.members.filter((e) => e.isAdmin).length === 1) {
  920. // Boards.remove(board._id);
  921. // }
  922. // });
  923. //});
  924. // Each board document contains the de-normalized number of users that have
  925. // starred it. If the user star or unstar a board, we need to update this
  926. // counter.
  927. // We need to run this code on the server only, otherwise the incrementation
  928. // will be done twice.
  929. Users.after.update(function(userId, user, fieldNames) {
  930. // The `starredBoards` list is hosted on the `profile` field. If this
  931. // field hasn't been modificated we don't need to run this hook.
  932. if (!_.contains(fieldNames, 'profile')) return;
  933. // To calculate a diff of board starred ids, we get both the previous
  934. // and the newly board ids list
  935. function getStarredBoardsIds(doc) {
  936. return doc.profile && doc.profile.starredBoards;
  937. }
  938. const oldIds = getStarredBoardsIds(this.previous);
  939. const newIds = getStarredBoardsIds(user);
  940. // The _.difference(a, b) method returns the values from a that are not in
  941. // b. We use it to find deleted and newly inserted ids by using it in one
  942. // direction and then in the other.
  943. function incrementBoards(boardsIds, inc) {
  944. boardsIds.forEach(boardId => {
  945. Boards.update(boardId, { $inc: { stars: inc } });
  946. });
  947. }
  948. incrementBoards(_.difference(oldIds, newIds), -1);
  949. incrementBoards(_.difference(newIds, oldIds), +1);
  950. });
  951. const fakeUserId = new Meteor.EnvironmentVariable();
  952. const getUserId = CollectionHooks.getUserId;
  953. CollectionHooks.getUserId = () => {
  954. return fakeUserId.get() || getUserId();
  955. };
  956. if (!isSandstorm) {
  957. Users.after.insert((userId, doc) => {
  958. const fakeUser = {
  959. extendAutoValueContext: {
  960. userId: doc._id,
  961. },
  962. };
  963. fakeUserId.withValue(doc._id, () => {
  964. /*
  965. // Insert the Welcome Board
  966. Boards.insert({
  967. title: TAPi18n.__('welcome-board'),
  968. permission: 'private',
  969. }, fakeUser, (err, boardId) => {
  970. Swimlanes.insert({
  971. title: TAPi18n.__('welcome-swimlane'),
  972. boardId,
  973. sort: 1,
  974. }, fakeUser);
  975. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  976. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  977. });
  978. });
  979. */
  980. Boards.insert(
  981. {
  982. title: TAPi18n.__('templates'),
  983. permission: 'private',
  984. type: 'template-container',
  985. },
  986. fakeUser,
  987. (err, boardId) => {
  988. // Insert the reference to our templates board
  989. Users.update(fakeUserId.get(), {
  990. $set: { 'profile.templatesBoardId': boardId },
  991. });
  992. // Insert the card templates swimlane
  993. Swimlanes.insert(
  994. {
  995. title: TAPi18n.__('card-templates-swimlane'),
  996. boardId,
  997. sort: 1,
  998. type: 'template-container',
  999. },
  1000. fakeUser,
  1001. (err, swimlaneId) => {
  1002. // Insert the reference to out card templates swimlane
  1003. Users.update(fakeUserId.get(), {
  1004. $set: { 'profile.cardTemplatesSwimlaneId': swimlaneId },
  1005. });
  1006. },
  1007. );
  1008. // Insert the list templates swimlane
  1009. Swimlanes.insert(
  1010. {
  1011. title: TAPi18n.__('list-templates-swimlane'),
  1012. boardId,
  1013. sort: 2,
  1014. type: 'template-container',
  1015. },
  1016. fakeUser,
  1017. (err, swimlaneId) => {
  1018. // Insert the reference to out list templates swimlane
  1019. Users.update(fakeUserId.get(), {
  1020. $set: { 'profile.listTemplatesSwimlaneId': swimlaneId },
  1021. });
  1022. },
  1023. );
  1024. // Insert the board templates swimlane
  1025. Swimlanes.insert(
  1026. {
  1027. title: TAPi18n.__('board-templates-swimlane'),
  1028. boardId,
  1029. sort: 3,
  1030. type: 'template-container',
  1031. },
  1032. fakeUser,
  1033. (err, swimlaneId) => {
  1034. // Insert the reference to out board templates swimlane
  1035. Users.update(fakeUserId.get(), {
  1036. $set: { 'profile.boardTemplatesSwimlaneId': swimlaneId },
  1037. });
  1038. },
  1039. );
  1040. },
  1041. );
  1042. });
  1043. });
  1044. }
  1045. Users.after.insert((userId, doc) => {
  1046. if (doc.createdThroughApi) {
  1047. // The admin user should be able to create a user despite disabling registration because
  1048. // it is two different things (registration and creation).
  1049. // So, when a new user is created via the api (only admin user can do that) one must avoid
  1050. // the disableRegistration check.
  1051. // Issue : https://github.com/wekan/wekan/issues/1232
  1052. // PR : https://github.com/wekan/wekan/pull/1251
  1053. Users.update(doc._id, { $set: { createdThroughApi: '' } });
  1054. return;
  1055. }
  1056. //invite user to corresponding boards
  1057. const disableRegistration = Settings.findOne().disableRegistration;
  1058. // If ldap, bypass the inviation code if the self registration isn't allowed.
  1059. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  1060. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  1061. const invitationCode = InvitationCodes.findOne({
  1062. code: doc.profile.icode,
  1063. valid: true,
  1064. });
  1065. if (!invitationCode) {
  1066. throw new Meteor.Error('error-invitation-code-not-exist');
  1067. } else {
  1068. invitationCode.boardsToBeInvited.forEach(boardId => {
  1069. const board = Boards.findOne(boardId);
  1070. board.addMember(doc._id);
  1071. });
  1072. if (!doc.profile) {
  1073. doc.profile = {};
  1074. }
  1075. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  1076. Users.update(doc._id, { $set: { profile: doc.profile } });
  1077. InvitationCodes.update(invitationCode._id, { $set: { valid: false } });
  1078. }
  1079. }
  1080. });
  1081. }
  1082. // USERS REST API
  1083. if (Meteor.isServer) {
  1084. // Middleware which checks that API is enabled.
  1085. JsonRoutes.Middleware.use(function(req, res, next) {
  1086. const api = req.url.startsWith('/api');
  1087. if ((api === true && process.env.WITH_API === 'true') || api === false) {
  1088. return next();
  1089. } else {
  1090. res.writeHead(301, { Location: '/' });
  1091. return res.end();
  1092. }
  1093. });
  1094. /**
  1095. * @operation get_current_user
  1096. *
  1097. * @summary returns the current user
  1098. * @return_type Users
  1099. */
  1100. JsonRoutes.add('GET', '/api/user', function(req, res) {
  1101. try {
  1102. Authentication.checkLoggedIn(req.userId);
  1103. const data = Meteor.users.findOne({ _id: req.userId });
  1104. delete data.services;
  1105. JsonRoutes.sendResult(res, {
  1106. code: 200,
  1107. data,
  1108. });
  1109. } catch (error) {
  1110. JsonRoutes.sendResult(res, {
  1111. code: 200,
  1112. data: error,
  1113. });
  1114. }
  1115. });
  1116. /**
  1117. * @operation get_all_users
  1118. *
  1119. * @summary return all the users
  1120. *
  1121. * @description Only the admin user (the first user) can call the REST API.
  1122. * @return_type [{ _id: string,
  1123. * username: string}]
  1124. */
  1125. JsonRoutes.add('GET', '/api/users', function(req, res) {
  1126. try {
  1127. Authentication.checkUserId(req.userId);
  1128. JsonRoutes.sendResult(res, {
  1129. code: 200,
  1130. data: Meteor.users.find({}).map(function(doc) {
  1131. return { _id: doc._id, username: doc.username };
  1132. }),
  1133. });
  1134. } catch (error) {
  1135. JsonRoutes.sendResult(res, {
  1136. code: 200,
  1137. data: error,
  1138. });
  1139. }
  1140. });
  1141. /**
  1142. * @operation get_user
  1143. *
  1144. * @summary get a given user
  1145. *
  1146. * @description Only the admin user (the first user) can call the REST API.
  1147. *
  1148. * @param {string} userId the user ID
  1149. * @return_type Users
  1150. */
  1151. JsonRoutes.add('GET', '/api/users/:userId', function(req, res) {
  1152. try {
  1153. Authentication.checkUserId(req.userId);
  1154. const id = req.params.userId;
  1155. JsonRoutes.sendResult(res, {
  1156. code: 200,
  1157. data: Meteor.users.findOne({ _id: id }),
  1158. });
  1159. } catch (error) {
  1160. JsonRoutes.sendResult(res, {
  1161. code: 200,
  1162. data: error,
  1163. });
  1164. }
  1165. });
  1166. /**
  1167. * @operation edit_user
  1168. *
  1169. * @summary edit a given user
  1170. *
  1171. * @description Only the admin user (the first user) can call the REST API.
  1172. *
  1173. * Possible values for *action*:
  1174. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  1175. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  1176. * - `enableLogin`: Enable a user
  1177. *
  1178. * @param {string} userId the user ID
  1179. * @param {string} action the action
  1180. * @return_type {_id: string,
  1181. * title: string}
  1182. */
  1183. JsonRoutes.add('PUT', '/api/users/:userId', function(req, res) {
  1184. try {
  1185. Authentication.checkUserId(req.userId);
  1186. const id = req.params.userId;
  1187. const action = req.body.action;
  1188. let data = Meteor.users.findOne({ _id: id });
  1189. if (data !== undefined) {
  1190. if (action === 'takeOwnership') {
  1191. data = Boards.find({
  1192. 'members.userId': id,
  1193. 'members.isAdmin': true,
  1194. }).map(function(board) {
  1195. if (board.hasMember(req.userId)) {
  1196. board.removeMember(req.userId);
  1197. }
  1198. board.changeOwnership(id, req.userId);
  1199. return {
  1200. _id: board._id,
  1201. title: board.title,
  1202. };
  1203. });
  1204. } else {
  1205. if (action === 'disableLogin' && id !== req.userId) {
  1206. Users.update(
  1207. { _id: id },
  1208. {
  1209. $set: {
  1210. loginDisabled: true,
  1211. 'services.resume.loginTokens': '',
  1212. },
  1213. },
  1214. );
  1215. } else if (action === 'enableLogin') {
  1216. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  1217. }
  1218. data = Meteor.users.findOne({ _id: id });
  1219. }
  1220. }
  1221. JsonRoutes.sendResult(res, {
  1222. code: 200,
  1223. data,
  1224. });
  1225. } catch (error) {
  1226. JsonRoutes.sendResult(res, {
  1227. code: 200,
  1228. data: error,
  1229. });
  1230. }
  1231. });
  1232. /**
  1233. * @operation add_board_member
  1234. * @tag Boards
  1235. *
  1236. * @summary Add New Board Member with Role
  1237. *
  1238. * @description Only the admin user (the first user) can call the REST API.
  1239. *
  1240. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  1241. * to later change the permissions.
  1242. *
  1243. * @param {string} boardId the board ID
  1244. * @param {string} userId the user ID
  1245. * @param {boolean} isAdmin is the user an admin of the board
  1246. * @param {boolean} isNoComments disable comments
  1247. * @param {boolean} isCommentOnly only enable comments
  1248. * @return_type {_id: string,
  1249. * title: string}
  1250. */
  1251. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function(
  1252. req,
  1253. res,
  1254. ) {
  1255. try {
  1256. Authentication.checkUserId(req.userId);
  1257. const userId = req.params.userId;
  1258. const boardId = req.params.boardId;
  1259. const action = req.body.action;
  1260. const { isAdmin, isNoComments, isCommentOnly } = req.body;
  1261. let data = Meteor.users.findOne({ _id: userId });
  1262. if (data !== undefined) {
  1263. if (action === 'add') {
  1264. data = Boards.find({
  1265. _id: boardId,
  1266. }).map(function(board) {
  1267. if (!board.hasMember(userId)) {
  1268. board.addMember(userId);
  1269. function isTrue(data) {
  1270. return data.toLowerCase() === 'true';
  1271. }
  1272. board.setMemberPermission(
  1273. userId,
  1274. isTrue(isAdmin),
  1275. isTrue(isNoComments),
  1276. isTrue(isCommentOnly),
  1277. userId,
  1278. );
  1279. }
  1280. return {
  1281. _id: board._id,
  1282. title: board.title,
  1283. };
  1284. });
  1285. }
  1286. }
  1287. JsonRoutes.sendResult(res, {
  1288. code: 200,
  1289. data: query,
  1290. });
  1291. } catch (error) {
  1292. JsonRoutes.sendResult(res, {
  1293. code: 200,
  1294. data: error,
  1295. });
  1296. }
  1297. });
  1298. /**
  1299. * @operation remove_board_member
  1300. * @tag Boards
  1301. *
  1302. * @summary Remove Member from Board
  1303. *
  1304. * @description Only the admin user (the first user) can call the REST API.
  1305. *
  1306. * @param {string} boardId the board ID
  1307. * @param {string} userId the user ID
  1308. * @param {string} action the action (needs to be `remove`)
  1309. * @return_type {_id: string,
  1310. * title: string}
  1311. */
  1312. JsonRoutes.add(
  1313. 'POST',
  1314. '/api/boards/:boardId/members/:userId/remove',
  1315. function(req, res) {
  1316. try {
  1317. Authentication.checkUserId(req.userId);
  1318. const userId = req.params.userId;
  1319. const boardId = req.params.boardId;
  1320. const action = req.body.action;
  1321. let data = Meteor.users.findOne({ _id: userId });
  1322. if (data !== undefined) {
  1323. if (action === 'remove') {
  1324. data = Boards.find({
  1325. _id: boardId,
  1326. }).map(function(board) {
  1327. if (board.hasMember(userId)) {
  1328. board.removeMember(userId);
  1329. }
  1330. return {
  1331. _id: board._id,
  1332. title: board.title,
  1333. };
  1334. });
  1335. }
  1336. }
  1337. JsonRoutes.sendResult(res, {
  1338. code: 200,
  1339. data: query,
  1340. });
  1341. } catch (error) {
  1342. JsonRoutes.sendResult(res, {
  1343. code: 200,
  1344. data: error,
  1345. });
  1346. }
  1347. },
  1348. );
  1349. /**
  1350. * @operation new_user
  1351. *
  1352. * @summary Create a new user
  1353. *
  1354. * @description Only the admin user (the first user) can call the REST API.
  1355. *
  1356. * @param {string} username the new username
  1357. * @param {string} email the email of the new user
  1358. * @param {string} password the password of the new user
  1359. * @return_type {_id: string}
  1360. */
  1361. JsonRoutes.add('POST', '/api/users/', function(req, res) {
  1362. try {
  1363. Authentication.checkUserId(req.userId);
  1364. const id = Accounts.createUser({
  1365. username: req.body.username,
  1366. email: req.body.email,
  1367. password: req.body.password,
  1368. from: 'admin',
  1369. });
  1370. JsonRoutes.sendResult(res, {
  1371. code: 200,
  1372. data: {
  1373. _id: id,
  1374. },
  1375. });
  1376. } catch (error) {
  1377. JsonRoutes.sendResult(res, {
  1378. code: 200,
  1379. data: error,
  1380. });
  1381. }
  1382. });
  1383. /**
  1384. * @operation delete_user
  1385. *
  1386. * @summary Delete a user
  1387. *
  1388. * @description Only the admin user (the first user) can call the REST API.
  1389. *
  1390. * @param {string} userId the ID of the user to delete
  1391. * @return_type {_id: string}
  1392. */
  1393. JsonRoutes.add('DELETE', '/api/users/:userId', function(req, res) {
  1394. try {
  1395. Authentication.checkUserId(req.userId);
  1396. const id = req.params.userId;
  1397. Meteor.users.remove({ _id: id });
  1398. JsonRoutes.sendResult(res, {
  1399. code: 200,
  1400. data: {
  1401. _id: id,
  1402. },
  1403. });
  1404. } catch (error) {
  1405. JsonRoutes.sendResult(res, {
  1406. code: 200,
  1407. data: error,
  1408. });
  1409. }
  1410. });
  1411. }
  1412. export default Users;