2
0

users.js 40 KB

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