users.js 34 KB

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