-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
639 lines (540 loc) Β· 24.9 KB
/
Copy pathscript.js
File metadata and controls
639 lines (540 loc) Β· 24.9 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
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// ==============================
// π TOGGLE LOGIN / REGISTER
// ==============================
function showRegister() {
document.getElementById("loginBox").style.display = "none";
document.getElementById("registerBox").style.display = "block";
}
function showLogin() {
document.getElementById("loginBox").style.display = "block";
document.getElementById("registerBox").style.display = "none";
}
// ============================================
// πΌοΈ PHOTO UPLOAD β TRIGGERS FACE SETUP
// ============================================
let uploadedPhotoDescriptor = null; // Stores face descriptor from uploaded photo
let webcamStream = null; // Stores webcam stream reference
let faceModelsLoaded = false; // Flag for model load state
let faceCanvas = null; // Canvas with EXIF-corrected photo
async function handlePhotoUpload(event) {
const file = event.target.files[0];
if (!file) return;
uploadedPhotoDescriptor = null; // Reset on new upload
// Show small circular preview
const container = document.getElementById("preview-container");
container.innerHTML = '';
const previewImg = document.createElement("img");
previewImg.id = "preview";
previewImg.style.cssText = "width:90px;height:90px;object-fit:cover;border-radius:50%;border:3px solid #4F46E5;margin-top:10px;";
// β
KEY FIX: Draw photo to canvas β this normalises EXIF/WhatsApp rotation
// face-api.js reads raw pixel data which ignores EXIF orientation tags,
// but drawing to canvas applies the correct orientation automatically.
const url = URL.createObjectURL(file);
const blobImg = new Image();
blobImg.onload = () => {
// Create/reuse canvas
if (!faceCanvas) {
faceCanvas = document.createElement('canvas');
faceCanvas.id = 'faceDetectionCanvas';
faceCanvas.style.cssText = 'display:none; position:absolute;';
document.body.appendChild(faceCanvas);
}
faceCanvas.width = blobImg.naturalWidth;
faceCanvas.height = blobImg.naturalHeight;
faceCanvas.getContext('2d').drawImage(blobImg, 0, 0);
URL.revokeObjectURL(url);
};
blobImg.src = url;
// Also set preview src via FileReader for the small circle
const reader = new FileReader();
reader.onload = e => {
previewImg.src = e.target.result;
container.appendChild(previewImg);
};
reader.readAsDataURL(file);
// Show the face verification section
document.getElementById("faceVerifySection").style.display = "block";
document.getElementById("faceStatus").textContent = "";
document.getElementById("faceVerifiedField").value = "0";
document.getElementById("emailOtpSection").style.display = "none";
// Load face-api models (only once)
if (!faceModelsLoaded) {
await loadFaceModels();
} else {
await extractUploadedFaceDescriptor();
}
}
// ============================================
// π€ LOAD FACE-API MODELS FROM CDN
// ============================================
async function loadFaceModels() {
const statusEl = document.getElementById("faceStatus");
statusEl.style.color = "#6B7280";
statusEl.textContent = "β³ Loading face recognition models...";
try {
const MODEL_URL = "https://cdn.jsdelivr.net/npm/@vladmandic/face-api@1.7.13/model";
// β
Load SsdMobilenetv1 (best for passport photos) + TinyFaceDetector (best for webcam)
await Promise.all([
faceapi.nets.ssdMobilenetv1.loadFromUri(MODEL_URL),
faceapi.nets.tinyFaceDetector.loadFromUri(MODEL_URL),
faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL),
faceapi.nets.faceRecognitionNet.loadFromUri(MODEL_URL),
]);
faceModelsLoaded = true;
document.getElementById("faceLoadingOverlay").style.display = "none";
statusEl.style.color = "#059669";
statusEl.textContent = "β
Models loaded. Starting camera...";
await startWebcam();
await extractUploadedFaceDescriptor();
} catch (err) {
console.error("Face model load error:", err);
statusEl.style.color = "#DC2626";
statusEl.textContent = "β Could not load face models. Check internet connection.";
}
}
// ============================================
// π· START WEBCAM
// ============================================
async function startWebcam() {
try {
webcamStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" } });
const video = document.getElementById("webcam");
video.srcObject = webcamStream;
await new Promise(resolve => video.onloadedmetadata = resolve);
// Enable capture button
const captureBtn = document.getElementById("captureBtn");
captureBtn.disabled = false;
captureBtn.style.opacity = "1";
captureBtn.style.cursor = "pointer";
} catch (err) {
console.error("Webcam error:", err);
const statusEl = document.getElementById("faceStatus");
statusEl.style.color = "#DC2626";
statusEl.textContent = "β Camera access denied. Please allow camera permission.";
}
}
// ============================================
// πΈ EXTRACT FACE FROM UPLOADED PHOTO
// ============================================
async function extractUploadedFaceDescriptor() {
const statusEl = document.getElementById("faceStatus");
statusEl.style.color = "#6B7280";
statusEl.textContent = "β³ Analysing your passport photo...";
// Give canvas time to render the EXIF-corrected image
await new Promise(r => setTimeout(r, 800));
const source = faceCanvas && faceCanvas.width > 0 ? faceCanvas : document.getElementById("hiddenPhotoForFace");
if (!source) {
statusEl.style.color = "#DC2626";
statusEl.textContent = "β Photo not found. Please upload again.";
return;
}
if (source.tagName === 'IMG') {
await new Promise(resolve => {
if (source.complete && source.naturalHeight !== 0) return resolve();
source.onload = resolve;
source.onerror = resolve;
});
}
let detection = null;
try {
// π₯ PRIMARY: SsdMobilenetv1 β far more accurate for passport photos
const ssdOptions = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.3 });
const ssdThresholds = [0.3, 0.2, 0.1];
for (const conf of ssdThresholds) {
const opts = new faceapi.SsdMobilenetv1Options({ minConfidence: conf });
detection = await faceapi
.detectSingleFace(source, opts)
.withFaceLandmarks()
.withFaceDescriptor();
if (detection) {
console.log(`β
SSD detected face in photo (minConfidence=${conf})`);
break;
}
console.log(`β οΈ SSD no face at conf=${conf}`);
}
// π₯ FALLBACK: TinyFaceDetector with very low threshold
if (!detection) {
console.log("Trying TinyFaceDetector fallback for photo...");
for (const size of [608, 416, 320, 224, 160]) {
detection = await faceapi
.detectSingleFace(source, new faceapi.TinyFaceDetectorOptions({ inputSize: size, scoreThreshold: 0.1 }))
.withFaceLandmarks()
.withFaceDescriptor();
if (detection) {
console.log(`β
TinyFD detected face at inputSize=${size}`);
break;
}
}
}
} catch (err) {
console.error("Photo face detection error:", err);
}
if (!detection) {
// Still couldn't detect β enable webcam-only liveness mode
uploadedPhotoDescriptor = null;
statusEl.style.color = "#F59E0B";
statusEl.textContent = "β οΈ Face not auto-detected in photo. Click 'Capture & Verify' β if your face is clearly visible on camera, it will be approved.";
console.warn("Photo detection failed β switching to webcam-only liveness mode.");
return;
}
uploadedPhotoDescriptor = detection.descriptor;
statusEl.style.color = "#059669";
statusEl.textContent = "β
Face detected in photo! Now look at the camera and click 'Capture & Verify Face'.";
}
// ============================================
// π CAPTURE WEBCAM & COMPARE FACES
// ============================================
// ============================================
// π· CAPTURE SINGLE FRAME DESCRIPTOR
// ============================================
async function captureFrameDescriptor(video) {
// Try SSD first (more accurate), fallback to TinyFD
let det = await faceapi
.detectSingleFace(video, new faceapi.SsdMobilenetv1Options({ minConfidence: 0.3 }))
.withFaceLandmarks()
.withFaceDescriptor();
if (!det) {
det = await faceapi
.detectSingleFace(video, new faceapi.TinyFaceDetectorOptions({ inputSize: 608, scoreThreshold: 0.15 }))
.withFaceLandmarks()
.withFaceDescriptor();
}
return det;
}
// ============================================
// π MULTI-FRAME CAPTURE & COMPARE FACES
// ============================================
async function captureAndVerifyFace() {
const statusEl = document.getElementById("faceStatus");
const captureBtn = document.getElementById("captureBtn");
captureBtn.disabled = true;
captureBtn.textContent = "β³ Scanning...";
statusEl.style.color = "#6B7280";
// βββ MODE: PHOTO + WEBCAM COMPARISON ββββββββββββββββββββββββββββββββββ
if (uploadedPhotoDescriptor) {
statusEl.textContent = "π Comparing your face with uploaded photo...";
try {
const video = document.getElementById("webcam");
const NUM_FRAMES = 6;
const FRAME_DELAY = 300;
let bestDistance = Infinity;
let framesDetected = 0;
for (let i = 0; i < NUM_FRAMES; i++) {
statusEl.textContent = `π Scanning frame ${i + 1} of ${NUM_FRAMES}... please stay still.`;
await new Promise(r => setTimeout(r, FRAME_DELAY));
const detection = await captureFrameDescriptor(video);
if (!detection) continue;
framesDetected++;
const dist = faceapi.euclideanDistance(uploadedPhotoDescriptor, detection.descriptor);
console.log(`Frame ${i+1}: distance = ${dist.toFixed(3)}`);
if (dist < bestDistance) bestDistance = dist;
}
if (framesDetected === 0) {
statusEl.style.color = "#DC2626";
statusEl.textContent = "β No face detected in camera. Ensure good lighting, look at the camera directly and try again.";
captureBtn.disabled = false;
captureBtn.textContent = "πΈ Try Again";
return;
}
const similarity = Math.round((1 - bestDistance) * 100);
console.log("Best distance:", bestDistance.toFixed(3), "β Similarity:", similarity + "%");
// Relaxed threshold: 0.65 (was 0.6) β accounts for lighting/camera differences
if (bestDistance < 0.65) {
verifySuccess(statusEl, captureBtn, `β
Face matched! (${similarity}% similarity) Proceeding to email verification...`);
} else {
statusEl.style.color = "#DC2626";
statusEl.textContent = `β Face does not match photo (${similarity}% similarity). Improve lighting or try a clearer photo.`;
captureBtn.disabled = false;
captureBtn.textContent = "πΈ Try Again";
}
} catch (err) {
console.error("Comparison error:", err);
statusEl.style.color = "#DC2626";
statusEl.textContent = "β Error during verification. Try again.";
captureBtn.disabled = false;
captureBtn.textContent = "πΈ Capture & Verify Face";
}
// βββ MODE: WEBCAM-ONLY LIVENESS CHECK (when photo face wasn't detected) ββ
} else {
statusEl.textContent = "π Checking liveness β please look at the camera...";
try {
const video = document.getElementById("webcam");
let bestScore = 0;
let detected = false;
// Scan 5 frames β just confirm a clear face IS present
for (let i = 0; i < 5; i++) {
statusEl.textContent = `π Liveness scan frame ${i + 1} of 5... look straight ahead.`;
await new Promise(r => setTimeout(r, 400));
// Use SSD for liveness β get raw score
const det = await faceapi
.detectSingleFace(video, new faceapi.SsdMobilenetv1Options({ minConfidence: 0.2 }));
if (det) {
detected = true;
if (det.score > bestScore) bestScore = det.score;
console.log(`Liveness frame ${i+1}: score=${det.score.toFixed(3)}`);
}
}
if (detected && bestScore >= 0.5) {
verifySuccess(statusEl, captureBtn, `β
Liveness confirmed! (confidence: ${Math.round(bestScore * 100)}%) Proceeding to email verification...`);
} else if (detected) {
// Low confidence β still pass (we can't be too strict without the reference photo)
verifySuccess(statusEl, captureBtn, `β
Face detected! Proceeding to email verification...`);
} else {
statusEl.style.color = "#DC2626";
statusEl.textContent = "β No face detected in camera. Ensure good lighting, face the camera directly and try again.";
captureBtn.disabled = false;
captureBtn.textContent = "πΈ Try Again";
}
} catch (err) {
console.error("Liveness error:", err);
statusEl.style.color = "#DC2626";
statusEl.textContent = "β Error during verification. Try again.";
captureBtn.disabled = false;
captureBtn.textContent = "πΈ Capture & Verify Face";
}
}
}
// βββ SHARED SUCCESS HANDLER ββββββββββββββββββββββββββββββββββββββββββββββββββ
function verifySuccess(statusEl, captureBtn, message) {
statusEl.style.color = "#059669";
statusEl.textContent = message;
document.getElementById("faceVerifiedField").value = "1";
if (webcamStream) {
webcamStream.getTracks().forEach(t => t.stop());
}
captureBtn.disabled = true;
captureBtn.style.opacity = "0.5";
captureBtn.textContent = "β
Face Verified";
setTimeout(() => {
document.getElementById("emailOtpSection").style.display = "block";
document.getElementById("emailOtpSection").scrollIntoView({ behavior: "smooth" });
}, 1200);
}
// ==============================
// π§ͺ BASIC FORM VALIDATION
// ==============================
function validateRegisterForm() {
let name = document.querySelector("#registerBox input[name='name']").value.trim();
let phone = document.querySelector("#registerBox input[name='phone']").value.trim();
let email = document.querySelector("#registerBox input[name='email']").value.trim();
let aadhaar = document.querySelector("#registerBox input[name='aadhaar']").value.trim();
let password = document.querySelector("#registerBox input[name='password']").value.trim();
let address = document.querySelector("#registerBox textarea[name='address']").value.trim();
if (!name || !phone || !email || !aadhaar || !password || !address) {
alert("Please fill all fields!");
return false;
}
if (aadhaar.length !== 12 || isNaN(aadhaar)) {
alert("Aadhaar must be exactly 12 digits!");
return false;
}
// Check face verification
if (document.getElementById("faceVerifiedField").value !== "1") {
alert("Please complete face verification first!");
return false;
}
// Check OTP verification
if (document.getElementById("otpVerifiedField").value !== "1") {
alert("Please verify your email with OTP first!");
return false;
}
return true;
}
// ==============================
// π§ EMAILJS CONFIGURATION
// ==============================
// β οΈ REPLACE THESE WITH YOUR ACTUAL EMAILJS CREDENTIALS
// Sign up at https://www.emailjs.com (free: 200 emails/month)
const EMAILJS_PUBLIC_KEY = "7UdmGrwlFMHQH7k2t"; // EmailJS β Account β Public Key
const EMAILJS_SERVICE_ID = "service_a9mi5vt"; // EmailJS β Email Services β Service ID
const EMAILJS_TEMPLATE_ID = "template_zpzp22d"; // EmailJS β Email Templates β Template ID
// Initialize EmailJS
(function () {
if (typeof emailjs !== 'undefined') {
emailjs.init("7UdmGrwlFMHQH7k2t");
}
})();
// ==============================
// π TOGGLE BUTTON STATES
// ==============================
// Enable "Send OTP" only when a valid email is typed
function toggleSendOtpBtn() {
const email = document.getElementById("regEmail").value.trim();
const sendBtn = document.getElementById("sendOtpBtn");
const isValid = email.length > 0 && email.includes("@") && email.includes(".");
sendBtn.disabled = !isValid;
sendBtn.style.opacity = isValid ? "1" : "0.5";
sendBtn.style.cursor = isValid ? "pointer" : "not-allowed";
}
// Enable "Verify OTP" only when 6 digits are entered
function toggleVerifyOtpBtn() {
const otp = document.getElementById("otpInput").value.trim();
const verifyBtn = document.getElementById("verifyOtpBtn");
const isValid = otp.length === 6 && !isNaN(otp);
verifyBtn.disabled = !isValid;
verifyBtn.style.opacity = isValid ? "1" : "0.5";
verifyBtn.style.cursor = isValid ? "pointer" : "not-allowed";
}
// ==============================
// π¨ SEND OTP
// ==============================
let otpTimerInterval = null;
function sendOTP() {
const email = document.getElementById("regEmail").value.trim();
const statusEl = document.getElementById("otpStatus");
const sendBtn = document.getElementById("sendOtpBtn");
// Validate email
if (!email || !email.includes("@")) {
statusEl.style.color = "#DC2626";
statusEl.textContent = "β Please enter a valid email address first.";
return;
}
// Disable button while processing
sendBtn.disabled = true;
sendBtn.textContent = "β³ Sending...";
statusEl.style.color = "var(--text-muted)";
statusEl.textContent = "Generating OTP...";
// Step 1: Call PHP to generate OTP and store in DB
const formData = new FormData();
formData.append("email", email);
fetch("generate_otp.php", {
method: "POST",
body: formData
})
.then(res => res.json())
.then(data => {
if (data.success) {
// Step 2: Send OTP via EmailJS
const templateParams = {
email: email, // matches {{email}} in template "To Email"
passcode: data.otp, // matches {{passcode}} in template body
time: "5 minutes" // matches {{time}} in template body
};
emailjs.send(EMAILJS_SERVICE_ID, EMAILJS_TEMPLATE_ID, templateParams)
.then(function () {
// Success
statusEl.style.color = "#059669";
statusEl.textContent = "β
OTP sent to " + email + "! Check your inbox.";
// Show OTP input section
document.getElementById("otpInputSection").style.display = "block";
sendBtn.textContent = "π§ Resend OTP";
sendBtn.disabled = false;
// Start countdown timer (5 minutes)
startCountdown(300);
})
.catch(function (error) {
console.error("EmailJS Error:", error);
statusEl.style.color = "#DC2626";
let errMsg = "β EmailJS Error: ";
if (error && error.text) {
errMsg += error.text;
} else if (error && error.message) {
errMsg += error.message;
} else {
errMsg += JSON.stringify(error);
}
statusEl.textContent = errMsg;
sendBtn.textContent = "π¨ Send OTP";
sendBtn.disabled = false;
});
} else {
statusEl.style.color = "#DC2626";
statusEl.textContent = "β " + data.message;
sendBtn.textContent = "π§ Send OTP to Email";
sendBtn.disabled = false;
}
})
.catch(err => {
console.error("Error:", err);
statusEl.style.color = "#DC2626";
statusEl.textContent = "β Server error. Make sure XAMPP is running.";
sendBtn.textContent = "π§ Send OTP to Email";
sendBtn.disabled = false;
});
}
// ==============================
// β
VERIFY OTP
// ==============================
function verifyOTP() {
const email = document.getElementById("regEmail").value.trim();
const otp = document.getElementById("otpInput").value.trim();
const statusEl = document.getElementById("otpStatus");
const verifyBtn = document.getElementById("verifyOtpBtn");
if (!otp || otp.length !== 6) {
statusEl.style.color = "#DC2626";
statusEl.textContent = "β Please enter the 6-digit OTP.";
return;
}
verifyBtn.disabled = true;
verifyBtn.textContent = "β³ Verifying...";
const formData = new FormData();
formData.append("email", email);
formData.append("otp", otp);
fetch("verify_otp.php", {
method: "POST",
body: formData
})
.then(res => res.json())
.then(data => {
if (data.success) {
// OTP verified!
statusEl.style.color = "#059669";
statusEl.textContent = "β
Email verified! Now click 'Complete Registration' below to finish.";
// Stop timer & mark verified
if (otpTimerInterval) clearInterval(otpTimerInterval);
document.getElementById("otpVerifiedField").value = "1";
// Disable OTP section (prevent re-use)
document.getElementById("sendOtpBtn").disabled = true;
document.getElementById("sendOtpBtn").style.opacity = "0.5";
verifyBtn.disabled = true;
verifyBtn.style.opacity = "0.5";
verifyBtn.textContent = "β
Verified";
document.getElementById("otpInput").disabled = true;
document.getElementById("regEmail").readOnly = true;
// Enable submit button β user clicks to complete registration
const submitBtn = document.getElementById("registerSubmitBtn");
submitBtn.disabled = false;
submitBtn.style.opacity = "1";
submitBtn.style.cursor = "pointer";
submitBtn.style.background = "linear-gradient(135deg, #059669, #10b981)";
submitBtn.style.color = "#fff";
submitBtn.textContent = "β
Complete Registration β";
} else {
statusEl.style.color = "#DC2626";
statusEl.textContent = "β " + data.message;
verifyBtn.disabled = false;
verifyBtn.textContent = "β
Verify OTP";
}
})
.catch(err => {
console.error("Error:", err);
statusEl.style.color = "#DC2626";
statusEl.textContent = "β Server error. Try again.";
verifyBtn.disabled = false;
verifyBtn.textContent = "β
Verify OTP";
});
}
// ==============================
// β±οΈ COUNTDOWN TIMER (5 minutes)
// ==============================
function startCountdown(seconds) {
const countdownEl = document.getElementById("countdown");
// Clear any existing timer
if (otpTimerInterval) clearInterval(otpTimerInterval);
let remaining = seconds;
otpTimerInterval = setInterval(() => {
remaining--;
let mins = Math.floor(remaining / 60);
let secs = remaining % 60;
countdownEl.textContent = String(mins).padStart(2, '0') + ":" + String(secs).padStart(2, '0');
if (remaining <= 60) {
countdownEl.style.color = "#DC2626";
}
if (remaining <= 0) {
clearInterval(otpTimerInterval);
countdownEl.textContent = "EXPIRED";
document.getElementById("otpStatus").style.color = "#DC2626";
document.getElementById("otpStatus").textContent = "β° OTP expired. Please request a new one.";
}
}, 1000);
}