forked from acemtp/meteor-accounts-passwordless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccounts-passwordless.js
232 lines (195 loc) · 7.95 KB
/
accounts-passwordless.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
Accounts.passwordless = {};
if (Meteor.isClient) {
/**
* Request a verification code.
* @param selector The email or username of the user
* @param [callback]
*/
Meteor.sendVerificationCode = function (selector, options, callback) {
if (!callback && typeof options === 'function')
callback = options;
// Save the selector in a Session so even if the client reloads, the selector is stored
Session.set('accounts-passwordless.selector', selector);
Meteor.call('accounts-passwordless.sendVerificationCode', selector, options, callback);
};
/**
* Login with the verification code.
* @param options code The verification code. selector The username or email (optional)
* @param [callback]
*/
Meteor.loginWithPasswordless = function (options, callback) {
console.log('lwpl', options);
Accounts.callLoginMethod({
methodArguments: [{
selector: Session.get('accounts-passwordless.selector') || options.selector,
code: options.code
}],
userCallback: callback
});
};
/**
* Set username. The user must be logged
* @param username The name of the user
* @param [callback]
*/
Meteor.setUsername = function (username, callback) {
Meteor.call('accounts-passwordless.setUsername', username, callback);
};
}
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
if(Meteor.isServer) {
Accounts.passwordless.emailTemplates = {
from: "Meteor Accounts <[email protected]>",
siteName: Meteor.absoluteUrl().replace(/^https?:\/\//, '').replace(/\/$/, ''),
sendVerificationCode: {
subject: function (code) {
return "Your verification code is " + code + " for " + Accounts.passwordless.emailTemplates.siteName;
},
text: function (user, code) {
var greeting = (user && user.username) ?
("Hello " + user.username + ",") : "Hello,";
return greeting + "\n"
+ "\n"
+ "Your verification code is " + code + ".\n"
+ "\n"
+ "Thanks.\n";
}
}
};
Meteor.methods({
'accounts-passwordless.sendVerificationCode': function (selector, options) {
check(selector, String);
check(options, Match.Optional(Match.Any));
Accounts.passwordless.sendVerificationCode(selector, options);
},
'accounts-passwordless.setUsername': function (username) {
check(username, String);
if(!this.userId) throw new Meteor.Error('You must be logged to change your username');
if(username.length < 3) throw new Meteor.Error('Your username must have at least 3 characters');
var existingUser = Meteor.users.findOne({ username: username });
if(existingUser) throw new Meteor.Error('This username already exists');
Meteor.users.update(this.userId, { $set: { username: username } });
}
});
// Handler to login with passwordless
Accounts.registerLoginHandler('passwordless', function (options) {
if (options.code === undefined) return undefined; // don't handle
check(options, {
selector: String,
code: String
});
if(!options.selector) throw new Meteor.Error('No selector setuped');
return Accounts.passwordless.verifyCode(options.selector, options.code);
});
var codes = new Meteor.Collection('meteor_accounts_passwordless');
/**
* Send a 4 digit verification code by email
* @param selector The email or username of the user
*/
Accounts.passwordless.sendVerificationCode = function (selector, options) {
var email;
var user;
if (selector.indexOf('@') === -1) {
user = Meteor.users.findOne({ username: selector });
if(!user) throw new Meteor.Error('Username \''+selector+'\' doesn\'t exists, enter your email address to create your account instead of your username.');
if(!user.emails || user.emails.length < 1) throw new Meteor.Error('No email attached to user ' + selector);
email = user.emails[0].address;
} else {
user = Meteor.users.findOne({ 'emails.address': selector });
// If the user doesn't exists, we'll create it when the user will verify his email
email = selector;
}
var code = Math.floor(Random.fraction() * 10000) + '';
// force pin to 4 digits
code = ('0000' + code).slice(-4);
// Generate a new code
codes.upsert({ email: email }, { $set: { code: code }});
Email.send({
to: email,
from: Accounts.passwordless.emailTemplates.from,
subject: Accounts.passwordless.emailTemplates.sendVerificationCode.subject(code),
text: Accounts.passwordless.emailTemplates.sendVerificationCode.text(user, code, selector, options)
});
};
// from accounts-password code
var createUser = function (options) {
// Unknown keys allowed, because a onCreateUserHook can take arbitrary
// options.
check(options, Match.ObjectIncluding({
username: Match.Optional(String),
email: Match.Optional(String),
}));
var username = options.username;
var email = options.email;
if (!username && !email)
throw new Meteor.Error(400, "Need to set a username or email");
var user = {services: {}};
if (options.password) {
var hashed = hashPassword(options.password);
user.services.password = { bcrypt: hashed };
}
if (username)
user.username = username;
if (email)
user.emails = [{address: email, verified: false}];
return Accounts.insertUserDoc(options, user);
};
/**
* Verify if the code is valid
* @param selector The email or username of the user
* @param code The code the user entered
*/
Accounts.passwordless.verifyCode = function (selector, code) {
var user;
var email;
if (selector.indexOf('@') === -1) {
user = Meteor.users.findOne({ username: selector });
if(!user) throw new Meteor.Error('Username '+selector+' doesn\'t exists, create an accounts first or login with the email');
if(!user.emails || user.emails.length < 1) throw new Meteor.Error('No email attached to user '+selector);
email = user.emails[0].address;
} else {
user = Meteor.users.findOne({ 'emails.address': selector });
email = selector;
}
var validCode = codes.findOne({ email: email});
if (!validCode)
throw new Meteor.Error('Unknown email');
var now = new Date().getTime() / 1000;
var timeToWait;
if (validCode.lastTry) {
timeToWait = validCode.lastTry.getTime()/1000 + Math.pow(validCode.nbTry, 2);
if (timeToWait > now)
throw new Meteor.Error('You must wait ' + Math.ceil(timeToWait - now) + ' seconds');
}
if (validCode.code !== code) {
codes.update({email: email}, { $set: {lastTry: new Date()}, $inc: {nbTry: 1 }});
throw new Meteor.Error('Invalid verification code');
}
// Clear the verification code after a succesful login.
codes.remove({ email: email });
var uid;
if(user) {
uid = user._id;
} else {
uid = createUser({ email: email });
user = Meteor.users.findOne(uid);
console.log('created user', uid, user);
}
if(user) {
// Set the email as verified since he validated the code with this email
var ve = _.find(user.emails, function (e) { return e.address === email; });
if(ve && !ve.verified) {
// By including the address in the query, we can use 'emails.$' in the
// modifier to get a reference to the specific object in the emails
// array. See
// http://www.mongodb.org/display/DOCS/Updating/#Updating-The%24positionaloperator)
// http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull
Meteor.users.update({ _id: uid, 'emails.address': email }, { $set: { 'emails.$.verified': true } });
}
}
return { userId: uid };
};
}