export.js 6.9 KB

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