-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSMSVerify.js
executable file
·63 lines (52 loc) · 1.89 KB
/
SMSVerify.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
// This mem-cache module is a local in-memory cache - for production use, you would replace this with Memcache, Redis, or a database
const Cache = require('mem-cache');
const cache = new Cache();
function SMSVerify(twilioClient, sendingPhoneNumber) {
this.twilioClient = twilioClient;
this.sendingPhoneNumber = sendingPhoneNumber;
};
module.exports = SMSVerify;
SMSVerify.prototype.generateOneTimeCode = function() {
const codelength = 6;
return Math.floor(Math.random() * (Math.pow(10, (codelength - 1)) * 9)) + Math.pow(10, (codelength - 1));
};
SMSVerify.prototype.getExpiration = function() {
return 900;
};
SMSVerify.prototype.request = function(phone) {
console.log('Requesting SMS to be sent to ' + phone);
const otp = this.generateOneTimeCode();
cache.set(phone, otp, this.getExpiration() * 1000);
const smsMessage = '[#] Use ' + otp + ' as your code for the app!\n';
console.log(smsMessage);
this.twilioClient.messages.create({
to: phone,
from: this.sendingPhoneNumber,
body: smsMessage,
}).then((message) => console.log(message.sid));
};
SMSVerify.prototype.verify = function(phone, smsMessage) {
console.log('Verifying ' + phone + ':' + smsMessage);
const otp = cache.get(phone);
if (otp == null) {
console.log('No cached otp value found for phone: ' + phone);
return false;
}
if (smsMessage.indexOf(otp) > -1) {
console.log('Found otp value in cache');
return true;
} else {
console.log('Mismatch between otp value found and otp value expected');
return false;
}
};
SMSVerify.prototype.reset = function(phone) {
console.log('Resetting code for: ' + phone);
const otp = cache.get(phone);
if (otp == null) {
console.log('No cached otp value found for phone: ' + phone);
return false;
}
cache.remove(phone);
return true;
};