sandstorm.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. // In sandstorm we only have one board per sandstorm instance. Since we want to
  6. // keep most of our code unchanged, we simply hard-code a board `_id` and
  7. // redirect the user to this particular board.
  8. const sandstormBoard = {
  9. _id: 'sandstorm',
  10. // XXX Should be shared with the grain instance name.
  11. title: 'Wekan',
  12. slug: 'libreboard',
  13. members: [],
  14. // Board access security is handled by sandstorm, so in our point of view we
  15. // can alway assume that the board is public (unauthorized users won't be able
  16. // to access it anyway).
  17. permission: 'public',
  18. };
  19. if (isSandstorm && Meteor.isServer) {
  20. function updateUserPermissions(userId, permissions) {
  21. const isActive = permissions.indexOf('participate') > -1;
  22. const isAdmin = permissions.indexOf('configure') > -1;
  23. const permissionDoc = { userId, isActive, isAdmin };
  24. const boardMembers = Boards.findOne(sandstormBoard._id).members;
  25. const memberIndex = _.pluck(boardMembers, 'userId').indexOf(userId);
  26. let modifier;
  27. if (memberIndex > -1)
  28. modifier = { $set: { [`members.${memberIndex}`]: permissionDoc }};
  29. else if (!isActive)
  30. modifier = {};
  31. else
  32. modifier = { $push: { members: permissionDoc }};
  33. Boards.update(sandstormBoard._id, modifier);
  34. }
  35. Picker.route('/', (params, req, res) => {
  36. // Redirect the user to the hard-coded board. On the first launch the user
  37. // will be redirected to the board before its creation. But that's not a
  38. // problem thanks to the reactive board publication. We used to do this
  39. // redirection on the client side but that was sometimes visible on loading,
  40. // and the home page was accessible by pressing the back button of the
  41. // browser, a server-side redirection solves both of these issues.
  42. //
  43. // XXX Maybe the sandstorm http-bridge could provide some kind of "home URL"
  44. // in the manifest?
  45. const base = req.headers['x-sandstorm-base-path'];
  46. const { _id, slug } = sandstormBoard;
  47. const boardPath = FlowRouter.path('board', { id: _id, slug });
  48. res.writeHead(301, {
  49. Location: base + boardPath,
  50. });
  51. res.end();
  52. // `accounts-sandstorm` populate the Users collection when new users
  53. // accesses the document, but in case a already known user comes back, we
  54. // need to update his associated document to match the request HTTP headers
  55. // informations.
  56. // XXX We need to update this document even if the initial route is not `/`.
  57. // Unfortuanlty I wasn't able to make the Webapp.rawConnectHandlers solution
  58. // work.
  59. const user = Users.findOne({
  60. 'services.sandstorm.id': req.headers['x-sandstorm-user-id'],
  61. });
  62. if (user) {
  63. // XXX At this point the user.services.sandstorm credentials haven't been
  64. // updated, which mean that the user will have to restart the application
  65. // a second time to see its updated name and avatar.
  66. Users.update(user._id, {
  67. $set: {
  68. 'profile.fullname': user.services.sandstorm.name,
  69. 'profile.avatarUrl': user.services.sandstorm.picture,
  70. },
  71. });
  72. updateUserPermissions(user._id, user.services.sandstorm.permissions);
  73. }
  74. });
  75. // On the first launch of the instance a user is automatically created thanks
  76. // to the `accounts-sandstorm` package. After its creation we insert the
  77. // unique board document. Note that when the `Users.after.insert` hook is
  78. // called, the user is inserted into the database but not connected. So
  79. // despite the appearances `userId` is null in this block.
  80. Users.after.insert((userId, doc) => {
  81. if (!Boards.findOne(sandstormBoard._id)) {
  82. Boards.insert(sandstormBoard, { validate: false });
  83. Activities.update(
  84. { activityTypeId: sandstormBoard._id },
  85. { $set: { userId: doc._id }}
  86. );
  87. }
  88. // We rely on username uniqueness for the user mention feature, but
  89. // Sandstorm doesn't enforce this property -- see #352. Our strategy to
  90. // generate unique usernames from the Sandstorm `preferredHandle` is to
  91. // append a number that we increment until we generate a username that no
  92. // one already uses (eg, 'max', 'max1', 'max2').
  93. function generateUniqueUsername(username, appendNumber) {
  94. return username + String(appendNumber === 0 ? '' : appendNumber);
  95. }
  96. const username = doc.services.sandstorm.preferredHandle;
  97. let appendNumber = 0;
  98. while (Users.findOne({
  99. _id: { $ne: doc._id },
  100. username: generateUniqueUsername(username, appendNumber),
  101. })) {
  102. appendNumber += 1;
  103. }
  104. Users.update(doc._id, {
  105. $set: {
  106. username: generateUniqueUsername(username, appendNumber),
  107. 'profile.fullname': doc.services.sandstorm.name,
  108. 'profile.avatarUrl': doc.services.sandstorm.picture,
  109. },
  110. });
  111. updateUserPermissions(doc._id, doc.services.sandstorm.permissions);
  112. });
  113. // Wekan v0.8 didn’t implement the Sandstorm sharing model and instead kept
  114. // the visibility setting (“public” or “private”) in the UI as does the main
  115. // Meteor application. We need to enforce “public” visibility as the sharing
  116. // is now handled by Sandstorm.
  117. // See https://github.com/wekan/wekan/issues/346
  118. Migrations.add('enforce-public-visibility-for-sandstorm', () => {
  119. Boards.update('sandstorm', { $set: { permission: 'public' }});
  120. });
  121. }
  122. if (isSandstorm && Meteor.isClient) {
  123. // Since the Sandstorm grain is displayed in an iframe of the Sandstorm shell,
  124. // we need to explicitly expose meta data like the page title or the URL path
  125. // so that they could appear in the browser window.
  126. // See https://docs.sandstorm.io/en/latest/developing/path/
  127. function updateSandstormMetaData(msg) {
  128. return window.parent.postMessage(msg, '*');
  129. }
  130. FlowRouter.triggers.enter([({ path }) => {
  131. updateSandstormMetaData({ setPath: path });
  132. }]);
  133. Tracker.autorun(() => {
  134. updateSandstormMetaData({ setTitle: DocHead.getTitle() });
  135. });
  136. // Runtime redirection from the home page to the unique board -- since the
  137. // home page contains a list of a single board it's not worth to display.
  138. //
  139. // XXX Hack. The home route is already defined at this point so we need to
  140. // add the redirection trigger to the internal route object.
  141. FlowRouter._routesMap.home._triggersEnter.push((context, redirect) => {
  142. redirect(FlowRouter.path('board', {
  143. id: sandstormBoard._id,
  144. slug: sandstormBoard.slug,
  145. }));
  146. });
  147. // XXX Hack. `Meteor.absoluteUrl` doesn't work in Sandstorm, since every
  148. // session has a different URL whereas Meteor computes absoluteUrl based on
  149. // the ROOT_URL environment variable. So we overwrite this function on a
  150. // sandstorm client to return relative paths instead of absolutes.
  151. const _absoluteUrl = Meteor.absoluteUrl;
  152. const _defaultOptions = Meteor.absoluteUrl.defaultOptions;
  153. Meteor.absoluteUrl = (path, options) => {
  154. const url = _absoluteUrl(path, options);
  155. return url.replace(/^https?:\/\/127\.0\.0\.1:[0-9]{2,5}/, '');
  156. };
  157. Meteor.absoluteUrl.defaultOptions = _defaultOptions;
  158. }
  159. // We use this blaze helper in the UI to hide some templates that does not make
  160. // sense in the context of sandstorm, like board staring, board archiving, user
  161. // name edition, etc.
  162. Blaze.registerHelper('isSandstorm', isSandstorm);