users.js 34 KB

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