-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
passwordless_server.js
248 lines (221 loc) · 6.25 KB
/
passwordless_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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import { Accounts } from 'meteor/accounts-base';
import {
DEFAULT_TOKEN_SEQUENCE_LENGTH,
getUserById,
NonEmptyString,
tokenValidator,
checkToken,
} from './server_utils';
import { Random } from 'meteor/random';
const findUserWithOptions = ({ selector }) => {
if (!selector) {
Accounts._handleError('A selector is necessary');
}
const { email, id, ...rest } = selector;
return Meteor.users.findOne(
{
...rest,
...(id && { _id: id }),
...(email && { 'emails.address': email })
},
{
fields: {
services: 1,
emails: 1,
},
}
);
};
// Handler to login with an ott.
Accounts.registerLoginHandler('passwordless', options => {
if (!options.token) return undefined; // don't handle
check(options, {
token: tokenValidator(),
code: Match.Optional(NonEmptyString),
selector: Accounts._userQueryValidator,
});
const sequence = options.token.toUpperCase();
const { selector } = options;
const user = findUserWithOptions(options);
if (!user) {
Accounts._handleError('User not found');
}
if (!user.services || !user.services.passwordless) {
Accounts._handleError('User has no token set');
}
const result = checkToken({
user,
selector,
sequence,
});
const { verifiedEmail, error } = result;
if (!error && verifiedEmail) {
// This method is added by the package accounts-2fa
if (Accounts._check2faEnabled?.(user)) {
if (!options.code) {
Accounts._handleError('2FA code must be informed', true, 'no-2fa-code');
return;
}
if (
!Accounts._isTokenValid(
user.services.twoFactorAuthentication.secret,
options.code
)
) {
Accounts._handleError('Invalid 2FA code', true, 'invalid-2fa-code');
return;
}
}
// It's necessary to make sure we don't remove the token if the user has 2fa enabled
// otherwise, it would be necessary to generate a new one if this method is called without
// a 2fa code
Meteor.users.update(
{ _id: user._id, 'emails.address': verifiedEmail },
{
$set: {
'emails.$.verified': true,
},
$unset: { 'services.passwordless': 1 },
}
);
}
return result;
});
// Utility for plucking addresses from emails
const pluckAddresses = (emails = []) => emails.map(email => email.address);
const createUser = userData => {
const { username, email } = userData;
if (!username && !email) {
throw new Meteor.Error(400, 'Need to set a username or email');
}
const user = { services: {} };
return Accounts._createUserCheckingDuplicates({
user,
username,
email,
options: userData,
});
};
function generateSequence() {
return Random.hexString(
Accounts._options.tokenSequenceLength || DEFAULT_TOKEN_SEQUENCE_LENGTH
).toUpperCase();
}
Meteor.methods({
requestLoginTokenForUser: ({ selector, userData, options = {} }) => {
let user = Accounts._findUserByQuery(selector, {
fields: { emails: 1 },
});
if (
!user &&
(options.userCreationDisabled ||
Accounts._options.forbidClientAccountCreation)
) {
Accounts._handleError('User not found');
}
// useful to customize messages
const isNewUser = !user;
if (!user) {
const userId = createUser(userData);
user = Accounts._findUserByQuery(
{ id: userId },
{
fields: { emails: 1 },
}
);
}
if (!user) {
Accounts._handleError('User could not be created');
}
const result = {
selector,
userData,
isNewUser,
};
const emails = pluckAddresses(user.emails);
const userSequence = generateSequence();
const tokens = emails
.map(email => {
// if the email was informed we will notify only this email
if (
selector.email &&
selector.email.toLowerCase() !== email.toLowerCase()
) {
return null;
}
const sequence = generateSequence();
return { email, sequence };
})
.filter(Boolean);
if (!tokens.length) {
Accounts._handleError(`Login tokens could not be generated`);
}
Meteor.users.update(user._id, {
$set: {
'services.passwordless': {
createdAt: new Date(),
token: SHA256(user._id + userSequence),
tokens: tokens.map(({ email, sequence }) => ({
email,
token: SHA256(email + sequence),
})),
...(isNewUser ? { isNewUser } : {}),
},
},
});
const shouldSendLoginTokenEmail = Accounts._onCreateLoginTokenHook
? Accounts._onCreateLoginTokenHook({
token: userSequence,
userId: user._id,
})
: true;
if (shouldSendLoginTokenEmail) {
tokens.forEach(({ email, sequence }) => {
Accounts.sendLoginTokenEmail({
userId: user._id,
sequence,
email,
...(options.extra ? { extra: options.extra } : {}),
});
});
}
return result;
},
});
/**
* @summary Send an email with a link the user can use to login with token.
* @locus Server
* @param {Object} options
* @param {String} options.userId The id of the user to send email to.
* @param {String} options.sequence The token to be provided
* @param {String} options.email Which address of the user's to send the email to.
* @param {Object} options.extra Optional. Extra properties
* @returns {Object} Object with {email, user, token, url, options} values.
*/
Accounts.sendLoginTokenEmail = ({ userId, sequence, email, extra = {} }) => {
const user = getUserById(userId);
const url = Accounts.urls.loginToken(email, sequence);
const options = Accounts.generateOptionsForEmail(
email,
user,
url,
'sendLoginToken',
{ ...extra, sequence }
);
Email.send({ ...options, extra });
if (Meteor.isDevelopment) {
console.log(`\nLogin Token url: ${url}`);
}
return { email, user, token: sequence, url, options };
};
const setupUsersCollection = () => {
Meteor.users.createIndexAsync('services.passwordless.tokens.token', {
unique: true,
sparse: true,
});
Meteor.users.createIndexAsync('services.passwordless.token', {
unique: true,
sparse: true,
});
};
Meteor.startup(() => setupUsersCollection());