-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaccounts-add-service-server.js
189 lines (169 loc) · 6.2 KB
/
accounts-add-service-server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/* globals AccountsAddService, AccountsMultiple
*/
"use strict";
var mergeUserErrorReason = AccountsAddService._mergeUserErrorReason;
AccountsAddService.databaseMigrationEnabled = true;
AccountsAddService._migrationControl =
new Mongo.Collection("AccountsAddService._migrationControl");
// returns false if the migration isn't run, or the number of users updated
// if it is.
AccountsAddService._migrateDatabase = function () {
if (! AccountsAddService.databaseMigrationEnabled) {
return false;
}
var addHasLoggedIn =
AccountsAddService._migrationControl.findOne('addHasLoggedIn');
if (addHasLoggedIn && addHasLoggedIn.startedAt) {
return false;
}
if (! addHasLoggedIn) {
try {
AccountsAddService._migrationControl.insert({ _id: 'addHasLoggedIn' });
} catch (err) {
// Ignore duplicate key error thrown if already id already exists due to
// concurrent insertion attempts
if (! (err.name === 'MongoError' && err.message.indexOf('E11000'))) {
throw err;
}
}
}
var numAffected = AccountsAddService._migrationControl.update({
_id: 'addHasLoggedIn',
startedAt: { $exists: false }
}, {
$set: {
startedAt: new Date(),
}
});
// Only one server will return numAffected !== 0. When numAffect === 0,
// The migration was already started (and possibly finished)
if (numAffected === 0) {
return false;
}
var selector = {
hasLoggedIn: { $exists: false },
'services.resume': { $exists: true }
};
var numUsersUpdated = Meteor.users.update(selector, {
$set: { hasLoggedIn: true }
});
if (numUsersUpdated > 0) {
console.log('brettle:accounts-add-service set hasLoggedIn = true for ' +
numUsersUpdated + ' existing user(s).');
}
AccountsAddService._migrationControl.update({
_id: 'addHasLoggedIn',
}, {
$set: {
finishedAt: new Date(),
}
});
return numUsersUpdated;
};
Meteor.startup(AccountsAddService._migrateDatabase);
// The first time a user logs in, we set his hasLoggedIn property so that
// we don't accidentally merge his account if his "resume" service is removed.
Accounts.onLogin(function (attemptInfo) {
if (attemptInfo.user && ! attemptInfo.user.hasLoggedIn) {
Meteor.users.update(attemptInfo.user._id, {
$set: { hasLoggedIn: true }
});
}
});
function isMergeable(user) {
// A user should be merged if they have never logged in. If they have
// never logged in, they won't have a "resume" service and they won't have
// the `hasLoggedIn` property.
return !(user.services && user.services.resume) && !(user.hasLoggedIn);
}
AccountsAddService._init = function () {
AccountsMultiple.register(addServiceCallbackSet);
};
var addServiceCallbackSet = {
validateSwitch: function(attemptingUser, attempt) {
if (isMergeable(attempt.user)) {
throw new Meteor.Error(Accounts.LoginCancelledError.numericError,
mergeUserErrorReason);
}
return true;
},
onSwitchFailure: function(attemptingUser, failedAttempt) {
if (!failedAttempt.error ||
!failedAttempt.error.error || !failedAttempt.error.reason ||
failedAttempt.error.error !== Accounts.LoginCancelledError.numericError ||
failedAttempt.error.reason !== mergeUserErrorReason) {
return;
}
var serviceName = failedAttempt.type;
var serviceData = failedAttempt.user.services[serviceName];
// Repin any pinned oauth credentials to the logged in user
if (serviceName !== "password" && serviceName !== "resume") {
repinCredentials(serviceData, failedAttempt.user._id, attemptingUser._id);
}
Meteor.users.remove(failedAttempt.user._id);
// Copy the serviceData into Meteor.user.services[serviceName]
var setAttrs = {};
_.each(serviceData, function(value, key) {
setAttrs["services." + serviceName + "." + key] = value;
});
// Non-destructively merge profile properties
var attemptingProfile = attemptingUser.profile || {};
var attemptProfile = failedAttempt.user.profile;
attemptProfile = _.omit(attemptProfile, _.keys(attemptingProfile));
_.each(attemptProfile, function(value, key) {
setAttrs["profile." + key] = value;
});
// Non-destructively merge emails
if (failedAttempt.user.emails) {
var attemptingEmails = attemptingUser.emails || [];
var attemptEmails = failedAttempt.user.emails;
var mergedEmails = attemptingEmails.concat(attemptEmails);
mergedEmails = _.uniq(mergedEmails, false, function (email) {
return email.address;
});
setAttrs.emails = mergedEmails;
}
// Non-destructively merge email verification tokens
if (failedAttempt.user.services &&
failedAttempt.user.services.email &&
failedAttempt.user.services.email.verificationTokens) {
var attemptingTokens = (
attemptingUser.services &&
attemptingUser.services.email &&
attemptingUser.services.email.verificationTokens
) || [];
var attemptTokens = failedAttempt.user.services.email.verificationTokens;
var mergedTokens = attemptingTokens.concat(attemptTokens);
mergedTokens = _.uniq(mergedTokens, false, function (tokenRecord) {
return tokenRecord.token;
});
setAttrs["services.email.verificationTokens"] = mergedTokens;
}
// Non-destructively merge top-level properties
var attemptingTop = attemptingUser || {};
var attemptTop = failedAttempt.user;
attemptTop = _.omit(attemptTop, _.keys(attemptingTop));
delete attemptTop.profile; // handled above
delete attemptTop.emails; // handled above
delete attemptTop.services; // handled above
_.each(attemptTop, function(value, key) {
setAttrs[key] = value;
});
Meteor.users.update(attemptingUser._id, {
$set: setAttrs
});
}
};
var OAuthEncryption = Package["oauth-encryption"] &&
Package["oauth-encryption"].OAuthEncryption;
function repinCredentials(serviceData, oldUserId, newUserId) {
_.each(_.keys(serviceData), function(key) {
var value = serviceData[key];
if (OAuthEncryption && OAuthEncryption.isSealed(value)) {
value =
OAuthEncryption.seal(OAuthEncryption.open(value, oldUserId), newUserId);
}
serviceData[key] = value;
});
}
AccountsAddService._init();