-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathotp.js
More file actions
45 lines (40 loc) · 1.53 KB
/
otp.js
File metadata and controls
45 lines (40 loc) · 1.53 KB
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
import app from './firebase.js';
import { getAuth, signInWithPhoneNumber, RecaptchaVerifier } from 'firebase/auth';
const auth = getAuth(app);
// Initialize invisible reCAPTCHA verifier
window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', { size: 'invisible' }, auth);
const phoneInput = document.getElementById('phone-number');
const sendBtn = document.getElementById('send-otp');
const verifyBtn = document.getElementById('verify-otp');
const statusEl = document.getElementById('status');
sendBtn?.addEventListener('click', () => {
const phoneNumber = phoneInput?.value?.trim();
if (!phoneNumber) {
statusEl.textContent = 'Please enter a valid phone number (E.164 format e.g. +91XXXXXXXXXX).';
return;
}
signInWithPhoneNumber(auth, phoneNumber, window.recaptchaVerifier)
.then((confirmationResult) => {
window.confirmationResult = confirmationResult;
statusEl.textContent = 'OTP sent!';
})
.catch((error) => {
statusEl.textContent = 'Error sending OTP: ' + error.message;
});
});
verifyBtn?.addEventListener('click', () => {
const code = document.getElementById('otp')?.value?.trim();
if (!code) {
statusEl.textContent = 'Please enter the OTP code.';
return;
}
window.confirmationResult.confirm(code)
.then((result) => {
const user = result.user;
statusEl.textContent = 'OTP verified! User logged in.';
console.log('Logged in user:', user);
})
.catch((error) => {
statusEl.textContent = 'Error verifying OTP: ' + error.message;
});
});