-
Notifications
You must be signed in to change notification settings - Fork 8
/
SMSVerify.js
executable file
·64 lines (57 loc) · 2.02 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
64
function SMSVerify(twilioClient, appHash, verificationServiceSID, countryCode) {
this.twilioClient = twilioClient;
this.appHash = appHash;
this.verificationServiceSID = verificationServiceSID;
this.countryCode = countryCode;
};
module.exports = SMSVerify;
SMSVerify.prototype.getE164Number = function(phone, callback) {
this.twilioClient.lookups.phoneNumbers(phone)
.fetch({countryCode: this.countryCode})
.then((lookupResult) => {
console.log(lookupResult.phoneNumber);
callback(lookupResult.phoneNumber);
})
.catch((error) => {
console.error(error);
callback(null);
});
};
SMSVerify.prototype.request = function(phone) {
console.log('Requesting verification SMS to be sent to ' + phone);
this.getE164Number(phone, (formattedPhoneNumber) => {
this.twilioClient.verify.services(this.verificationServiceSID)
.verifications
.create({
to: formattedPhoneNumber,
channel: 'sms',
appHash: this.appHash,
})
.then((verification)=> console.log(verification.sid))
.catch((error) => console.error(error));
});
};
SMSVerify.prototype.verify = function(phone, smsMessage, callback) {
console.log('Verifying ' + phone + ':' + smsMessage);
// This regexp finds the last numeric code in the message, of any length
const code = smsMessage.match(/[0-9]+(?!.*[0-9])/);
console.log('Verifying code: (' + code + ')');
this.getE164Number(phone, (formattedPhoneNumber) => {
this.twilioClient.verify.services(this.verificationServiceSID)
.verificationChecks
.create({to: formattedPhoneNumber, code: code})
.then((verificationCheck) => {
console.log(verificationCheck);
callback(verificationCheck.status == 'approved');
})
.catch((error) => {
console.error(error);
callback(false);
});
});
};
SMSVerify.prototype.reset = function(phone) {
console.log('Resetting code for: ' + phone);
// Not needed for Verify
return true;
};