users.js 35 KB

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