users.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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 if (this.isUpsert) {
  57. return { $setOnInsert: new Date() };
  58. } else {
  59. this.unset();
  60. }
  61. },
  62. },
  63. modifiedAt: {
  64. type: Date,
  65. denyUpdate: false,
  66. // eslint-disable-next-line consistent-return
  67. autoValue() {
  68. if (this.isInsert || this.isUpsert || this.isUpdate) {
  69. return new Date();
  70. } else {
  71. this.unset();
  72. }
  73. },
  74. },
  75. profile: {
  76. /**
  77. * profile settings
  78. */
  79. type: Object,
  80. optional: true,
  81. // eslint-disable-next-line consistent-return
  82. autoValue() {
  83. if (this.isInsert && !this.isSet) {
  84. return {
  85. boardView: 'board-view-lists',
  86. };
  87. }
  88. },
  89. },
  90. 'profile.avatarUrl': {
  91. /**
  92. * URL of the avatar of the user
  93. */
  94. type: String,
  95. optional: true,
  96. },
  97. 'profile.emailBuffer': {
  98. /**
  99. * list of email buffers of the user
  100. */
  101. type: [String],
  102. optional: true,
  103. },
  104. 'profile.fullname': {
  105. /**
  106. * full name of the user
  107. */
  108. type: String,
  109. optional: true,
  110. },
  111. 'profile.showDesktopDragHandles': {
  112. /**
  113. * does the user want to hide system messages?
  114. */
  115. type: Boolean,
  116. optional: true,
  117. },
  118. 'profile.hiddenSystemMessages': {
  119. /**
  120. * does the user want to hide system messages?
  121. */
  122. type: Boolean,
  123. optional: true,
  124. },
  125. 'profile.hiddenMinicardLabelText': {
  126. /**
  127. * does the user want to hide minicard label texts?
  128. */
  129. type: Boolean,
  130. optional: true,
  131. },
  132. 'profile.initials': {
  133. /**
  134. * initials of the user
  135. */
  136. type: String,
  137. optional: true,
  138. },
  139. 'profile.invitedBoards': {
  140. /**
  141. * board IDs the user has been invited to
  142. */
  143. type: [String],
  144. optional: true,
  145. },
  146. 'profile.language': {
  147. /**
  148. * language of the user
  149. */
  150. type: String,
  151. optional: true,
  152. },
  153. 'profile.notifications': {
  154. /**
  155. * enabled notifications for the user
  156. */
  157. type: [String],
  158. optional: true,
  159. },
  160. 'profile.showCardsCountAt': {
  161. /**
  162. * showCardCountAt field of the user
  163. */
  164. type: Number,
  165. optional: true,
  166. },
  167. 'profile.starredBoards': {
  168. /**
  169. * list of starred board IDs
  170. */
  171. type: [String],
  172. optional: true,
  173. },
  174. 'profile.icode': {
  175. /**
  176. * icode
  177. */
  178. type: String,
  179. optional: true,
  180. },
  181. 'profile.boardView': {
  182. /**
  183. * boardView field of the user
  184. */
  185. type: String,
  186. optional: true,
  187. allowedValues: [
  188. 'board-view-lists',
  189. 'board-view-swimlanes',
  190. 'board-view-cal',
  191. ],
  192. },
  193. 'profile.templatesBoardId': {
  194. /**
  195. * Reference to the templates board
  196. */
  197. type: String,
  198. defaultValue: '',
  199. },
  200. 'profile.cardTemplatesSwimlaneId': {
  201. /**
  202. * Reference to the card templates swimlane Id
  203. */
  204. type: String,
  205. defaultValue: '',
  206. },
  207. 'profile.listTemplatesSwimlaneId': {
  208. /**
  209. * Reference to the list templates swimlane Id
  210. */
  211. type: String,
  212. defaultValue: '',
  213. },
  214. 'profile.boardTemplatesSwimlaneId': {
  215. /**
  216. * Reference to the board templates swimlane Id
  217. */
  218. type: String,
  219. defaultValue: '',
  220. },
  221. services: {
  222. /**
  223. * services field of the user
  224. */
  225. type: Object,
  226. optional: true,
  227. blackbox: true,
  228. },
  229. heartbeat: {
  230. /**
  231. * last time the user has been seen
  232. */
  233. type: Date,
  234. optional: true,
  235. },
  236. isAdmin: {
  237. /**
  238. * is the user an admin of the board?
  239. */
  240. type: Boolean,
  241. optional: true,
  242. },
  243. createdThroughApi: {
  244. /**
  245. * was the user created through the API?
  246. */
  247. type: Boolean,
  248. optional: true,
  249. },
  250. loginDisabled: {
  251. /**
  252. * loginDisabled field of the user
  253. */
  254. type: Boolean,
  255. optional: true,
  256. },
  257. authenticationMethod: {
  258. /**
  259. * authentication method of the user
  260. */
  261. type: String,
  262. optional: false,
  263. defaultValue: 'password',
  264. },
  265. }),
  266. );
  267. Users.allow({
  268. update(userId, doc) {
  269. const user = Users.findOne({ _id: userId });
  270. if ((user && user.isAdmin) || (Meteor.user() && Meteor.user().isAdmin))
  271. return true;
  272. if (!user) {
  273. return false;
  274. }
  275. return doc._id === userId;
  276. },
  277. remove(userId, doc) {
  278. const adminsNumber = Users.find({ isAdmin: true }).count();
  279. const { isAdmin } = Users.findOne(
  280. { _id: userId },
  281. { fields: { isAdmin: 1 } },
  282. );
  283. // Prevents remove of the only one administrator
  284. if (adminsNumber === 1 && isAdmin && userId === doc._id) {
  285. return false;
  286. }
  287. // If it's the user or an admin
  288. return userId === doc._id || isAdmin;
  289. },
  290. fetch: [],
  291. });
  292. // Search a user in the complete server database by its name or username. This
  293. // is used for instance to add a new user to a board.
  294. const searchInFields = ['username', 'profile.fullname'];
  295. Users.initEasySearch(searchInFields, {
  296. use: 'mongo-db',
  297. returnFields: [...searchInFields, 'profile.avatarUrl'],
  298. });
  299. if (Meteor.isClient) {
  300. Users.helpers({
  301. isBoardMember() {
  302. const board = Boards.findOne(Session.get('currentBoard'));
  303. return board && board.hasMember(this._id);
  304. },
  305. isNotNoComments() {
  306. const board = Boards.findOne(Session.get('currentBoard'));
  307. return (
  308. board && board.hasMember(this._id) && !board.hasNoComments(this._id)
  309. );
  310. },
  311. isNoComments() {
  312. const board = Boards.findOne(Session.get('currentBoard'));
  313. return board && board.hasNoComments(this._id);
  314. },
  315. isNotCommentOnly() {
  316. const board = Boards.findOne(Session.get('currentBoard'));
  317. return (
  318. board && board.hasMember(this._id) && !board.hasCommentOnly(this._id)
  319. );
  320. },
  321. isCommentOnly() {
  322. const board = Boards.findOne(Session.get('currentBoard'));
  323. return board && board.hasCommentOnly(this._id);
  324. },
  325. isBoardAdmin() {
  326. const board = Boards.findOne(Session.get('currentBoard'));
  327. return board && board.hasAdmin(this._id);
  328. },
  329. });
  330. }
  331. Users.helpers({
  332. boards() {
  333. return Boards.find({ 'members.userId': this._id });
  334. },
  335. starredBoards() {
  336. const { starredBoards = [] } = this.profile || {};
  337. return Boards.find({ archived: false, _id: { $in: starredBoards } });
  338. },
  339. hasStarred(boardId) {
  340. const { starredBoards = [] } = this.profile || {};
  341. return _.contains(starredBoards, boardId);
  342. },
  343. invitedBoards() {
  344. const { invitedBoards = [] } = this.profile || {};
  345. return Boards.find({ archived: false, _id: { $in: invitedBoards } });
  346. },
  347. isInvitedTo(boardId) {
  348. const { invitedBoards = [] } = this.profile || {};
  349. return _.contains(invitedBoards, boardId);
  350. },
  351. hasTag(tag) {
  352. const { tags = [] } = this.profile || {};
  353. return _.contains(tags, tag);
  354. },
  355. hasNotification(activityId) {
  356. const { notifications = [] } = this.profile || {};
  357. return _.contains(notifications, activityId);
  358. },
  359. hasShowDesktopDragHandles() {
  360. const profile = this.profile || {};
  361. return profile.showDesktopDragHandles || false;
  362. },
  363. hasHiddenSystemMessages() {
  364. const profile = this.profile || {};
  365. return profile.hiddenSystemMessages || false;
  366. },
  367. hasHiddenMinicardLabelText() {
  368. const profile = this.profile || {};
  369. return profile.hiddenMinicardLabelText || false;
  370. },
  371. getEmailBuffer() {
  372. const { emailBuffer = [] } = this.profile || {};
  373. return emailBuffer;
  374. },
  375. getInitials() {
  376. const profile = this.profile || {};
  377. if (profile.initials) return profile.initials;
  378. else if (profile.fullname) {
  379. return profile.fullname
  380. .split(/\s+/)
  381. .reduce((memo, word) => {
  382. return memo + word[0];
  383. }, '')
  384. .toUpperCase();
  385. } else {
  386. return this.username[0].toUpperCase();
  387. }
  388. },
  389. getLimitToShowCardsCount() {
  390. const profile = this.profile || {};
  391. return profile.showCardsCountAt;
  392. },
  393. getName() {
  394. const profile = this.profile || {};
  395. return profile.fullname || this.username;
  396. },
  397. getLanguage() {
  398. const profile = this.profile || {};
  399. return profile.language || 'en';
  400. },
  401. getTemplatesBoardId() {
  402. return (this.profile || {}).templatesBoardId;
  403. },
  404. getTemplatesBoardSlug() {
  405. return (Boards.findOne((this.profile || {}).templatesBoardId) || {}).slug;
  406. },
  407. remove() {
  408. User.remove({ _id: this._id });
  409. },
  410. });
  411. Users.mutations({
  412. toggleBoardStar(boardId) {
  413. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  414. return {
  415. [queryKind]: {
  416. 'profile.starredBoards': boardId,
  417. },
  418. };
  419. },
  420. addInvite(boardId) {
  421. return {
  422. $addToSet: {
  423. 'profile.invitedBoards': boardId,
  424. },
  425. };
  426. },
  427. removeInvite(boardId) {
  428. return {
  429. $pull: {
  430. 'profile.invitedBoards': boardId,
  431. },
  432. };
  433. },
  434. addTag(tag) {
  435. return {
  436. $addToSet: {
  437. 'profile.tags': tag,
  438. },
  439. };
  440. },
  441. removeTag(tag) {
  442. return {
  443. $pull: {
  444. 'profile.tags': tag,
  445. },
  446. };
  447. },
  448. toggleTag(tag) {
  449. if (this.hasTag(tag)) this.removeTag(tag);
  450. else this.addTag(tag);
  451. },
  452. toggleDesktopHandles(value = false) {
  453. return {
  454. $set: {
  455. 'profile.showDesktopDragHandles': !value,
  456. },
  457. };
  458. },
  459. toggleSystem(value = false) {
  460. return {
  461. $set: {
  462. 'profile.hiddenSystemMessages': !value,
  463. },
  464. };
  465. },
  466. toggleLabelText(value = false) {
  467. return {
  468. $set: {
  469. 'profile.hiddenMinicardLabelText': !value,
  470. },
  471. };
  472. },
  473. addNotification(activityId) {
  474. return {
  475. $addToSet: {
  476. 'profile.notifications': activityId,
  477. },
  478. };
  479. },
  480. removeNotification(activityId) {
  481. return {
  482. $pull: {
  483. 'profile.notifications': activityId,
  484. },
  485. };
  486. },
  487. addEmailBuffer(text) {
  488. return {
  489. $addToSet: {
  490. 'profile.emailBuffer': text,
  491. },
  492. };
  493. },
  494. clearEmailBuffer() {
  495. return {
  496. $set: {
  497. 'profile.emailBuffer': [],
  498. },
  499. };
  500. },
  501. setAvatarUrl(avatarUrl) {
  502. return { $set: { 'profile.avatarUrl': avatarUrl } };
  503. },
  504. setShowCardsCountAt(limit) {
  505. return { $set: { 'profile.showCardsCountAt': limit } };
  506. },
  507. setBoardView(view) {
  508. return {
  509. $set: {
  510. 'profile.boardView': view,
  511. },
  512. };
  513. },
  514. });
  515. Meteor.methods({
  516. setUsername(username, userId) {
  517. check(username, String);
  518. const nUsersWithUsername = Users.find({ username }).count();
  519. if (nUsersWithUsername > 0) {
  520. throw new Meteor.Error('username-already-taken');
  521. } else {
  522. Users.update(userId, { $set: { username } });
  523. }
  524. },
  525. toggleDesktopDragHandles() {
  526. const user = Meteor.user();
  527. user.toggleDesktopHandles(user.hasShowDesktopDragHandles());
  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;