Permalink
Browse files

Change interface for determining if the user doc is loaded to a new r…

…eactive

function Meteor.userLoaded(), which is true if you are logged in and the user
doc is loaded, and a currentUserLoaded Handlebars helper to match.

If logged in and the user doc is not yet loaded, Meteor.user() now returns an
object which only contains _id.

The current user subscription is now named meteor.currentUser rather than being
an unnamed sub. (loginServiceConfiguration is renamed
meteor.loginServiceConfiguration to match.) This subscription is sub'd from when
you log in and unsub'd from when you log out (or if you log in with different
credentials).

I was very careful to make sure that in the case of "sub #1, unsub #1, sub #2,
sub #1 is ready" we do not declare the user to be ready. I could have instead
modified livedata_connection to not call ready callbacks for unsub'd
subscriptions (add a "delete self.sub_ready_callbacks[obj._id]" to the self.subs
removed function) but this seemed less invasive.

The password and email tests use this to take a more rigorous approach to
waiting for the data to load, and they change the localStorage keys so that
multiple tabs running tests don't interact via localStorage.
  • Loading branch information...
1 parent 3720106 commit 0f3c44b8c2d8b647d8d4b95510ad4c58dc8b699d @glasser glasser committed Oct 7, 2012
@@ -4,23 +4,64 @@
return Meteor.default_connection.userId();
};
+ var userLoadedListeners = new Meteor.deps._ContextSet;
+ var currentUserSubscriptionData;
+
+ Meteor.userLoaded = function () {
+ userLoadedListeners.addCurrentContext();
+ return currentUserSubscriptionData && currentUserSubscriptionData.loaded;
+ };
+
Meteor.user = function () {
var userId = Meteor.userId();
- if (userId) {
- var result = Meteor.users.findOne(userId);
- if (result) {
- return result;
- } else {
- // If the login method completes but new subcriptions haven't
- // yet been sent down to the client, this is the best we can
- // do
- return {_id: userId, loading: true};
- }
- } else {
+ if (!userId)
return null;
+ if (currentUserSubscriptionData && currentUserSubscriptionData.loaded)
+ return Meteor.users.findOne(userId);
+ // Not yet loaded: return a minimal object.
+ return {_id: userId};
+ };
+
+ Accounts._makeClientLoggedOut = function() {
+ Accounts._unstoreLoginToken();
+ Meteor.default_connection.setUserId(null);
+ Meteor.default_connection.onReconnect = null;
+ userLoadedListeners.invalidateAll();
+ if (currentUserSubscriptionData) {
+ currentUserSubscriptionData.handle.stop();
+ currentUserSubscriptionData = null;
}
};
+ Accounts._makeClientLoggedIn = function(userId, token) {
+ Accounts._storeLoginToken(userId, token);
+ Meteor.default_connection.setUserId(userId);
+ Meteor.default_connection.onReconnect = function() {
+ Meteor.apply('login', [{resume: token}], {wait: true}, function(error, result) {
+ if (error) {
+ Accounts._makeClientLoggedOut();
+ throw error;
+ } else {
+ // nothing to do
+ }
+ });
+ };
+ userLoadedListeners.invalidateAll();
+ if (currentUserSubscriptionData) {
+ currentUserSubscriptionData.handle.stop();
+ }
+ var data = currentUserSubscriptionData = {loaded: false};
+ data.handle = Meteor.subscribe(
+ "meteor.currentUser", function () {
+ // Important! We use "data" here, not "currentUserSubscriptionData", so
+ // that if we log out and in again before this subscription is ready, we
+ // don't make currentUserSubscriptionData look ready just because this
+ // older iteration of subscribing is ready.
+ data.loaded = true;
+ userLoadedListeners.invalidateAll();
+ });
+ };
+
Meteor.logout = function (callback) {
Meteor.apply('logout', [], {wait: true}, function(error, result) {
if (error) {
@@ -32,19 +73,22 @@
});
};
- // If we're using Handlebars, register the {{currentUser}} global
- // helper
- if (window.Handlebars) {
+ // If we're using Handlebars, register the {{currentUser}} and
+ // {{currentUserLoaded}} global helpers.
+ if (typeof Handlebars !== 'undefined') {
Handlebars.registerHelper('currentUser', function () {
return Meteor.user();
});
+ Handlebars.registerHelper('currentUserLoaded', function () {
+ return Meteor.userLoaded();
+ });
}
// XXX this can be simplified if we merge in
// https://github.com/meteor/meteor/pull/273
var loginServicesConfigured = false;
var loginServicesConfiguredListeners = new Meteor.deps._ContextSet;
- Meteor.subscribe("loginServiceConfiguration", function () {
+ Meteor.subscribe("meteor.loginServiceConfiguration", function () {
loginServicesConfigured = true;
loginServicesConfiguredListeners.invalidateAll();
});
@@ -233,13 +233,22 @@
/// PUBLISHING DATA
///
- // Always publish the current user's record to the client.
- Meteor.publish(null, function() {
+ // Publish the current user's record to the client.
+ // XXX This should just be a universal subscription, but we want to know when
+ // we've gotten the data after a 'login' method, which currently requires
+ // us to unsub, sub, and wait for onComplete. This is wasteful because
+ // we're actually guaranteed to have the data by the time that 'login'
+ // returns. But we don't expose a callback to Meteor.apply which lets us
+ // know when the data has been processed (ie, quiescence, or at least
+ // partial quiescence).
+ Meteor.publish("meteor.currentUser", function() {
if (this.userId())
return Meteor.users.find({_id: this.userId()},
{fields: {profile: 1, username: 1, emails: 1}});
- else
+ else {
+ this.complete();
return null;
+ }
}, {is_auto: true});
// If autopublish is on, also publish everyone else's user record.
@@ -252,7 +261,7 @@
});
// Publish all login service configuration fields other than secret.
- Meteor.publish("loginServiceConfiguration", function () {
+ Meteor.publish("meteor.loginServiceConfiguration", function () {
return Accounts.configuration.find({}, {fields: {secret: 0}});
}, {is_auto: true}); // not techincally autopublish, but stops the warning.
@@ -3,6 +3,14 @@
var loginTokenKey = "Meteor.loginToken";
var userIdKey = "Meteor.userId";
+ // Call this from the top level of the test file for any test that does
+ // logging in and out, to protect multiple tabs running the same tests
+ // simultaneously from interfering with each others' localStorage.
+ Accounts._isolateLoginTokenForTest = function () {
+ loginTokenKey = loginTokenKey + Meteor.uuid();
+ userIdKey = userIdKey + Meteor.uuid();
+ };
+
Accounts._storeLoginToken = function(userId, token) {
localStorage.setItem(userIdKey, userId);
localStorage.setItem(loginTokenKey, token);
@@ -28,27 +36,6 @@
Accounts._storedUserId = function() {
return localStorage.getItem(userIdKey);
};
-
- Accounts._makeClientLoggedOut = function() {
- Accounts._unstoreLoginToken();
- Meteor.default_connection.setUserId(null);
- Meteor.default_connection.onReconnect = null;
- };
-
- Accounts._makeClientLoggedIn = function(userId, token) {
- Accounts._storeLoginToken(userId, token);
- Meteor.default_connection.setUserId(userId);
- Meteor.default_connection.onReconnect = function() {
- Meteor.apply('login', [{resume: token}], {wait: true}, function(error, result) {
- if (error) {
- Accounts._makeClientLoggedOut();
- throw error;
- } else {
- // nothing to do
- }
- });
- };
- };
})();
// Login with a Meteor access token
@@ -11,6 +11,8 @@
var validateEmailToken;
var enrollAccountToken;
+ Accounts._isolateLoginTokenForTest();
+
testAsyncMulti("accounts emails - reset password flow", [
function (test, expect) {
email1 = Meteor.uuid() + "-intercept@example.com";
@@ -65,6 +67,7 @@
var getValidateEmailToken = function (email, test, expect) {
Meteor.call("getInterceptedEmails", email, expect(function (error, result) {
+ test.isFalse(error);
test.notEqual(result, undefined);
test.equal(result.length, 1);
var content = result[0];
@@ -77,15 +80,28 @@
}));
};
+ var waitUntilLoggedIn = function (test, expect) {
+ var unblockNextFunction = expect();
+ var quiesceCallback = function () {
+ Meteor._autorun(function (handle) {
+ if (!Meteor.userLoaded()) return;
+ handle.stop();
+ unblockNextFunction();
+ });
+ };
+ return expect(function (error) {
+ test.equal(error, undefined);
+ Meteor.default_connection.onQuiesce(quiesceCallback);
+ });
+ };
+
testAsyncMulti("accounts emails - validate email flow", [
function (test, expect) {
email2 = Meteor.uuid() + "-intercept@example.com";
email3 = Meteor.uuid() + "-intercept@example.com";
Accounts.createUser(
{email: email2, password: 'foobar'},
- expect(function (error) {
- test.equal(error, undefined);
- }));
+ waitUntilLoggedIn(test, expect));
},
function (test, expect) {
test.equal(Meteor.user().emails.length, 1);
@@ -96,17 +112,23 @@
getValidateEmailToken(email2, test, expect);
},
function (test, expect) {
- Accounts.validateEmail(validateEmailToken, expect(function(error) {
- test.isFalse(error);
- }));
- // ARGH! ON QUIESCE!!
- Meteor.default_connection.onQuiesce(expect(function () {
- test.equal(Meteor.user().emails.length, 1);
- test.equal(Meteor.user().emails[0].address, email2);
- test.isTrue(Meteor.user().emails[0].validated);
+ // Log out, to test that validateEmail logs us back in. (And if we don't
+ // do that, waitUntilLoggedIn won't be able to prevent race conditions.)
+ Meteor.logout(expect(function (error) {
+ test.equal(error, undefined);
+ test.equal(Meteor.user(), null);
}));
},
function (test, expect) {
+ Accounts.validateEmail(validateEmailToken,
+ waitUntilLoggedIn(test, expect));
+ },
+ function (test, expect) {
+ test.equal(Meteor.user().emails.length, 1);
+ test.equal(Meteor.user().emails[0].address, email2);
+ test.isTrue(Meteor.user().emails[0].validated);
+ },
+ function (test, expect) {
Meteor.call(
"addEmailForTestAndValidate", email3,
expect(function (error, result) {
@@ -124,15 +146,20 @@
getValidateEmailToken(email3, test, expect);
},
function (test, expect) {
- Accounts.validateEmail(validateEmailToken, expect(function(error) {
- test.isFalse(error);
+ // Log out, to test that validateEmail logs us back in. (And if we don't
+ // do that, waitUntilLoggedIn won't be able to prevent race conditions.)
+ Meteor.logout(expect(function (error) {
+ test.equal(error, undefined);
+ test.equal(Meteor.user(), null);
}));
},
function (test, expect) {
- Meteor.default_connection.onQuiesce(expect(function () {
- test.equal(Meteor.user().emails[1].address, email3);
- test.isTrue(Meteor.user().emails[1].validated);
- }));
+ Accounts.validateEmail(validateEmailToken,
+ waitUntilLoggedIn(test, expect));
+ },
+ function (test, expect) {
+ test.equal(Meteor.user().emails[1].address, email3);
+ test.isTrue(Meteor.user().emails[1].validated);
},
function (test, expect) {
Meteor.logout(expect(function (error) {
@@ -172,16 +199,13 @@
getEnrollAccountToken(email4, test, expect);
},
function (test, expect) {
- Accounts.resetPassword(enrollAccountToken, 'password', expect(function(error) {
- test.isFalse(error);
- }));
+ Accounts.resetPassword(enrollAccountToken, 'password',
+ waitUntilLoggedIn(test, expect));
},
function (test, expect) {
- Meteor.default_connection.onQuiesce(expect(function () {
- test.equal(Meteor.user().emails.length, 1);
- test.equal(Meteor.user().emails[0].address, email4);
- test.isTrue(Meteor.user().emails[0].validated);
- }));
+ test.equal(Meteor.user().emails.length, 1);
+ test.equal(Meteor.user().emails[0].address, email4);
+ test.isTrue(Meteor.user().emails[0].validated);
},
function (test, expect) {
Meteor.logout(expect(function (error) {
@@ -190,9 +214,13 @@
}));
},
function (test, expect) {
- Meteor.loginWithPassword({email: email4}, 'password', expect(function(error) {
- test.isFalse(error);
- }));
+ Meteor.loginWithPassword({email: email4}, 'password',
+ waitUntilLoggedIn(test ,expect));
+ },
+ function (test, expect) {
+ test.equal(Meteor.user().emails.length, 1);
+ test.equal(Meteor.user().emails[0].address, email4);
+ test.isTrue(Meteor.user().emails[0].validated);
},
function (test, expect) {
Meteor.logout(expect(function (error) {
Oops, something went wrong.

0 comments on commit 0f3c44b

Please sign in to comment.