export.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. /* global JsonRoutes */
  2. if (Meteor.isServer) {
  3. // todo XXX once we have a real API in place, move that route there
  4. // todo XXX also share the route definition between the client and the server
  5. // so that we could use something like
  6. // `ApiRoutes.path('boards/export', boardId)``
  7. // on the client instead of copy/pasting the route path manually between the
  8. // client and the server.
  9. /**
  10. * @operation export
  11. * @tag Boards
  12. *
  13. * @summary This route is used to export the board.
  14. *
  15. * @description If user is already logged-in, pass loginToken as param
  16. * "authToken": '/api/boards/:boardId/export?authToken=:token'
  17. *
  18. * See https://blog.kayla.com.au/server-side-route-authentication-in-meteor/
  19. * for detailed explanations
  20. *
  21. * @param {string} boardId the ID of the board we are exporting
  22. * @param {string} authToken the loginToken
  23. */
  24. JsonRoutes.add('get', '/api/boards/:boardId/export', function(req, res) {
  25. const boardId = req.params.boardId;
  26. let user = null;
  27. const loginToken = req.query.authToken;
  28. if (loginToken) {
  29. const hashToken = Accounts._hashLoginToken(loginToken);
  30. user = Meteor.users.findOne({
  31. 'services.resume.loginTokens.hashedToken': hashToken,
  32. });
  33. } else if (!Meteor.settings.public.sandstorm) {
  34. Authentication.checkUserId(req.userId);
  35. user = Users.findOne({ _id: req.userId, isAdmin: true });
  36. }
  37. const exporter = new Exporter(boardId);
  38. if (exporter.canExport(user)) {
  39. JsonRoutes.sendResult(res, {
  40. code: 200,
  41. data: exporter.build(),
  42. });
  43. } else {
  44. // we could send an explicit error message, but on the other hand the only
  45. // way to get there is by hacking the UI so let's keep it raw.
  46. JsonRoutes.sendResult(res, 403);
  47. }
  48. });
  49. }
  50. // exporter maybe is broken since Gridfs introduced, add fs and path
  51. export class Exporter {
  52. constructor(boardId) {
  53. this._boardId = boardId;
  54. }
  55. build() {
  56. const fs = Npm.require('fs');
  57. const os = Npm.require('os');
  58. const path = Npm.require('path');
  59. const byBoard = { boardId: this._boardId };
  60. const byBoardNoLinked = {
  61. boardId: this._boardId,
  62. linkedId: { $in: ['', null] },
  63. };
  64. // we do not want to retrieve boardId in related elements
  65. const noBoardId = {
  66. fields: {
  67. boardId: 0,
  68. },
  69. };
  70. const result = {
  71. _format: 'wekan-board-1.0.0',
  72. };
  73. _.extend(
  74. result,
  75. Boards.findOne(this._boardId, {
  76. fields: {
  77. stars: 0,
  78. },
  79. }),
  80. );
  81. result.lists = Lists.find(byBoard, noBoardId).fetch();
  82. result.cards = Cards.find(byBoardNoLinked, noBoardId).fetch();
  83. result.swimlanes = Swimlanes.find(byBoard, noBoardId).fetch();
  84. result.customFields = CustomFields.find(
  85. { boardIds: { $in: [this.boardId] } },
  86. { fields: { boardId: 0 } },
  87. ).fetch();
  88. result.comments = CardComments.find(byBoard, noBoardId).fetch();
  89. result.activities = Activities.find(byBoard, noBoardId).fetch();
  90. result.rules = Rules.find(byBoard, noBoardId).fetch();
  91. result.checklists = [];
  92. result.checklistItems = [];
  93. result.subtaskItems = [];
  94. result.triggers = [];
  95. result.actions = [];
  96. result.cards.forEach(card => {
  97. result.checklists.push(
  98. ...Checklists.find({
  99. cardId: card._id,
  100. }).fetch(),
  101. );
  102. result.checklistItems.push(
  103. ...ChecklistItems.find({
  104. cardId: card._id,
  105. }).fetch(),
  106. );
  107. result.subtaskItems.push(
  108. ...Cards.find({
  109. parentid: card._id,
  110. }).fetch(),
  111. );
  112. });
  113. result.rules.forEach(rule => {
  114. result.triggers.push(
  115. ...Triggers.find(
  116. {
  117. _id: rule.triggerId,
  118. },
  119. noBoardId,
  120. ).fetch(),
  121. );
  122. result.actions.push(
  123. ...Actions.find(
  124. {
  125. _id: rule.actionId,
  126. },
  127. noBoardId,
  128. ).fetch(),
  129. );
  130. });
  131. // [Old] for attachments we only export IDs and absolute url to original doc
  132. // [New] Encode attachment to base64
  133. const getBase64Data = function(doc, callback) {
  134. let buffer = new Buffer(0);
  135. // callback has the form function (err, res) {}
  136. const tmpWriteable = fs.createWriteStream(
  137. path.join(os.tmpdir(), `tmpexport${process.pid}`),
  138. );
  139. const readStream = doc.createReadStream();
  140. readStream.on('data', function(chunk) {
  141. buffer = Buffer.concat([buffer, chunk]);
  142. });
  143. readStream.on('error', function(err) {
  144. callback(err, null);
  145. });
  146. readStream.on('end', function() {
  147. // done
  148. callback(null, buffer.toString('base64'));
  149. });
  150. readStream.pipe(tmpWriteable);
  151. };
  152. const getBase64DataSync = Meteor.wrapAsync(getBase64Data);
  153. result.attachments = Attachments.find(byBoard)
  154. .fetch()
  155. .map(attachment => {
  156. return {
  157. _id: attachment._id,
  158. cardId: attachment.cardId,
  159. // url: FlowRouter.url(attachment.url()),
  160. file: getBase64DataSync(attachment),
  161. name: attachment.original.name,
  162. type: attachment.original.type,
  163. };
  164. });
  165. // we also have to export some user data - as the other elements only
  166. // include id but we have to be careful:
  167. // 1- only exports users that are linked somehow to that board
  168. // 2- do not export any sensitive information
  169. const users = {};
  170. result.members.forEach(member => {
  171. users[member.userId] = true;
  172. });
  173. result.lists.forEach(list => {
  174. users[list.userId] = true;
  175. });
  176. result.cards.forEach(card => {
  177. users[card.userId] = true;
  178. if (card.members) {
  179. card.members.forEach(memberId => {
  180. users[memberId] = true;
  181. });
  182. }
  183. });
  184. result.comments.forEach(comment => {
  185. users[comment.userId] = true;
  186. });
  187. result.activities.forEach(activity => {
  188. users[activity.userId] = true;
  189. });
  190. result.checklists.forEach(checklist => {
  191. users[checklist.userId] = true;
  192. });
  193. const byUserIds = {
  194. _id: {
  195. $in: Object.getOwnPropertyNames(users),
  196. },
  197. };
  198. // we use whitelist to be sure we do not expose inadvertently
  199. // some secret fields that gets added to User later.
  200. const userFields = {
  201. fields: {
  202. _id: 1,
  203. username: 1,
  204. 'profile.fullname': 1,
  205. 'profile.initials': 1,
  206. 'profile.avatarUrl': 1,
  207. },
  208. };
  209. result.users = Users.find(byUserIds, userFields)
  210. .fetch()
  211. .map(user => {
  212. // user avatar is stored as a relative url, we export absolute
  213. if ((user.profile || {}).avatarUrl) {
  214. user.profile.avatarUrl = FlowRouter.url(user.profile.avatarUrl);
  215. }
  216. return user;
  217. });
  218. return result;
  219. }
  220. canExport(user) {
  221. const board = Boards.findOne(this._boardId);
  222. return board && board.isVisibleBy(user);
  223. }
  224. }