users.js 35 KB

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