users.js 36 KB

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