client.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors
  2. // Licensed under the MIT License:
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. function loginWithSandstorm(connection, apiHost, apiToken) {
  22. // Log in the connection using Sandstorm authentication.
  23. //
  24. // After calling this, connection.sandstormUser() will reactively return an object containing
  25. // Sansdstorm user info, including permissions as authenticated by the server. Even if the user
  26. // is anonymous, this information is returned. `sandstormUser()` returns `null` up until the
  27. // point where login succeeds.
  28. // How this works:
  29. // 1. We create a cryptographically random token, which we're going to send to the server twice.
  30. // 2. We make a method call to log in with this token. The server initially has no idea who
  31. // is calling and will block waiting for info. (The method is marked "wait" on the client side
  32. // so that further method calls are blocked until login completes.)
  33. // 3. We also send an XHR with the same token. When the server receives the XHR, it harvests the
  34. // Sandstorm headers, looks for the corresponding login method call, marks its connection as
  35. // logged in, and then lets it return.
  36. //
  37. // We don't actually use Accounts.callLoginMethod() because we don't need or want the
  38. // "resume token" logic. On a disconnect, we need to re-authenticate, because the user's
  39. // permissions may have changed (indeed, this may be the reason for the disconnect).
  40. // If the connection doesn't already have a sandstormUser() method, add it now.
  41. if (!connection._sandstormUser) {
  42. connection._sandstormUser = new ReactiveVar(null);
  43. connection.sandstormUser = connection._sandstormUser.get.bind(connection._sandstormUser);
  44. }
  45. // Generate a random token which we'll send both over an XHR and over DDP at the same time.
  46. var token = Random.secret();
  47. var waiting = true; // We'll keep retrying XHRs until the method returns.
  48. var reconnected = false;
  49. var onResultReceived = function (error, result) {
  50. waiting = false;
  51. if (error) {
  52. // ignore for now; loggedInAndDataReadyCallback() will get the error too
  53. } else {
  54. connection.onReconnect = function () {
  55. reconnected = true;
  56. loginWithSandstorm(connection, apiHost, apiToken);
  57. };
  58. }
  59. };
  60. var loggedInAndDataReadyCallback = function (error, result) {
  61. if (reconnected) {
  62. // Oh, we're already on a future connection attempt. Don't mess with anything.
  63. return;
  64. }
  65. if (error) {
  66. console.error("loginWithSandstorm failed:", error);
  67. } else {
  68. connection._sandstormUser.set(result.sandstorm);
  69. connection.setUserId(result.userId);
  70. }
  71. };
  72. Meteor.apply("loginWithSandstorm", [token],
  73. {wait: true, onResultReceived: onResultReceived},
  74. loggedInAndDataReadyCallback);
  75. var sendXhr = function () {
  76. if (!waiting) return; // Method call finished.
  77. headers = {"Content-Type": "application/x-sandstorm-login-token"};
  78. var testInfo = localStorage.sandstormTestUserInfo;
  79. if (testInfo) {
  80. testInfo = JSON.parse(testInfo);
  81. if (testInfo.id) {
  82. headers["X-Sandstorm-User-Id"] = testInfo.id;
  83. }
  84. if (testInfo.name) {
  85. headers["X-Sandstorm-Username"] = encodeURI(testInfo.name);
  86. }
  87. if (testInfo.picture) {
  88. headers["X-Sandstorm-User-Picture"] = testInfo.picture;
  89. }
  90. if (testInfo.permissions) {
  91. headers["X-Sandstorm-Permissions"] = testInfo.permissions.join(",");
  92. }
  93. if (testInfo.preferredHandle) {
  94. headers["X-Sandstorm-Preferred-Handle"] = testInfo.preferredHandle;
  95. }
  96. if (testInfo.pronouns) {
  97. headers["X-Sandstorm-User-Pronouns"] = testInfo.pronouns;
  98. }
  99. }
  100. var postUrl = "/.sandstorm-login";
  101. // Sandstorm mobile apps need to point at a different host and use an Authorization token.
  102. if (apiHost) {
  103. postUrl = apiHost + postUrl;
  104. headers.Authorization = "Bearer " + apiToken;
  105. }
  106. // Send the token in an HTTP POST request which on the server side will allow us to receive the
  107. // Sandstorm headers.
  108. HTTP.post(postUrl,
  109. {content: token, headers: headers},
  110. function (error, result) {
  111. if (error) {
  112. console.error("couldn't get /.sandstorm-login:", error);
  113. if (waiting) {
  114. // Try again in a second.
  115. Meteor.setTimeout(sendXhr, 1000);
  116. }
  117. }
  118. });
  119. };
  120. // Wait until the connection is up before we start trying to send XHRs.
  121. var stopImmediately = false; // Unfortunately, Tracker.autorun() runs the first time inline.
  122. var handle = Tracker.autorun(function () {
  123. if (!waiting) {
  124. if (handle) {
  125. handle.stop();
  126. } else {
  127. stopImmediately = true;
  128. }
  129. return;
  130. } else if (connection.status().connected) {
  131. if (handle) {
  132. handle.stop();
  133. } else {
  134. stopImmediately = true;
  135. }
  136. // Wait 10ms before our first attempt to send the rendezvous XHR because if it arrives
  137. // before the method call it will be rejected.
  138. Meteor.setTimeout(sendXhr, 10);
  139. }
  140. });
  141. if (stopImmediately) handle.stop();
  142. }
  143. if (__meteor_runtime_config__.SANDSTORM) {
  144. // Auto-login the main Meteor connection.
  145. loginWithSandstorm(Meteor.connection, __meteor_runtime_config__.SANDSTORM_API_HOST,
  146. __meteor_runtime_config__.SANDSTORM_API_TOKEN);
  147. if (Package["accounts-base"]) {
  148. // Make Meteor.loggingIn() work by calling a private method of accounts-base. If this breaks then
  149. // maybe we should just overwrite Meteor.loggingIn() instead.
  150. Tracker.autorun(function () {
  151. Package["accounts-base"].Accounts._setLoggingIn(!Meteor.connection.sandstormUser());
  152. });
  153. }
  154. Meteor.sandstormUser = function () {
  155. return Meteor.connection.sandstormUser();
  156. };
  157. SandstormAccounts = {
  158. setTestUserInfo: function (info) {
  159. localStorage.sandstormTestUserInfo = JSON.stringify(info);
  160. loginWithSandstorm(Meteor.connection, __meteor_runtime_config__.SANDSTORM_API_HOST,
  161. __meteor_runtime_config__.SANDSTORM_API_TOKEN);
  162. }
  163. };
  164. }