users.js 28 KB

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