export.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 = Buffer.allocUnsafe(0);
  135. buffer.fill(0);
  136. // callback has the form function (err, res) {}
  137. const tmpFile = path.join(
  138. os.tmpdir(),
  139. `tmpexport${process.pid}${Math.random()}`,
  140. );
  141. const tmpWriteable = fs.createWriteStream(tmpFile);
  142. const readStream = doc.createReadStream();
  143. readStream.on('data', function(chunk) {
  144. buffer = Buffer.concat([buffer, chunk]);
  145. });
  146. readStream.on('error', function(err) {
  147. callback(null, null);
  148. });
  149. readStream.on('end', function() {
  150. // done
  151. fs.unlink(tmpFile, () => {
  152. //ignored
  153. });
  154. callback(null, buffer.toString('base64'));
  155. });
  156. readStream.pipe(tmpWriteable);
  157. };
  158. const getBase64DataSync = Meteor.wrapAsync(getBase64Data);
  159. result.attachments = Attachments.find(byBoard)
  160. .fetch()
  161. .map(attachment => {
  162. let filebase64 = null;
  163. filebase64 = getBase64DataSync(attachment);
  164. return {
  165. _id: attachment._id,
  166. cardId: attachment.cardId,
  167. //url: FlowRouter.url(attachment.url()),
  168. file: filebase64,
  169. name: attachment.original.name,
  170. type: attachment.original.type,
  171. };
  172. });
  173. // we also have to export some user data - as the other elements only
  174. // include id but we have to be careful:
  175. // 1- only exports users that are linked somehow to that board
  176. // 2- do not export any sensitive information
  177. const users = {};
  178. result.members.forEach(member => {
  179. users[member.userId] = true;
  180. });
  181. result.lists.forEach(list => {
  182. users[list.userId] = true;
  183. });
  184. result.cards.forEach(card => {
  185. users[card.userId] = true;
  186. if (card.members) {
  187. card.members.forEach(memberId => {
  188. users[memberId] = true;
  189. });
  190. }
  191. });
  192. result.comments.forEach(comment => {
  193. users[comment.userId] = true;
  194. });
  195. result.activities.forEach(activity => {
  196. users[activity.userId] = true;
  197. });
  198. result.checklists.forEach(checklist => {
  199. users[checklist.userId] = true;
  200. });
  201. const byUserIds = {
  202. _id: {
  203. $in: Object.getOwnPropertyNames(users),
  204. },
  205. };
  206. // we use whitelist to be sure we do not expose inadvertently
  207. // some secret fields that gets added to User later.
  208. const userFields = {
  209. fields: {
  210. _id: 1,
  211. username: 1,
  212. 'profile.fullname': 1,
  213. 'profile.initials': 1,
  214. 'profile.avatarUrl': 1,
  215. },
  216. };
  217. result.users = Users.find(byUserIds, userFields)
  218. .fetch()
  219. .map(user => {
  220. // user avatar is stored as a relative url, we export absolute
  221. if ((user.profile || {}).avatarUrl) {
  222. user.profile.avatarUrl = FlowRouter.url(user.profile.avatarUrl);
  223. }
  224. return user;
  225. });
  226. return result;
  227. }
  228. canExport(user) {
  229. const board = Boards.findOne(this._boardId);
  230. return board && board.isVisibleBy(user);
  231. }
  232. }