users.js 36 KB

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