fix: 100% immune to native form reloads with pure Vanilla JS and instant OTP transition

This commit is contained in:
Hamza-Ayed
2026-08-26 23:21:28 +03:00
parent e386716ed5
commit 0d63554a1f
2 changed files with 638 additions and 531 deletions
+329 -270
View File
@@ -18,7 +18,7 @@ class StudentPortal
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800;900&display=swap" rel="stylesheet">
<!-- Pure Self-Contained Luxury CSS (Zero External CDN Failure Risk) -->
<!-- Pure Self-Contained Luxury CSS (Zero External CDN Dependency) -->
<style>
:root {
--bg-dark: #0B132B;
@@ -531,185 +531,8 @@ class StudentPortal
to { transform: rotate(360deg); }
}
</style>
<!-- Alpine Component in Head -->
<script>
function studentAuth() {
return {
isLoggedIn: false,
authStep: 'phone', // 'phone' | 'otp'
phone: '',
fullName: '',
otpCode: '',
phoneDisplay: '',
loading: false,
errorMessage: '',
successMessage: '',
timer: 0,
timerInterval: null,
deviceFingerprint: '',
studentData: {},
async initApp() {
try {
this.deviceFingerprint = await this.generateDeviceFingerprint();
const token = localStorage.getItem('saqel_student_jwt');
if (token) {
await this.fetchProfile(token);
}
} catch (e) {
console.error('Student App init error:', e);
}
},
async generateDeviceFingerprint() {
try {
const raw = [
navigator.userAgent,
navigator.language,
screen.width + 'x' + screen.height,
Intl.DateTimeFormat().resolvedOptions().timeZone
].join('###');
const msgUint8 = new TextEncoder().encode(raw);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
} catch (e) {
return 'student_web_' + Math.random().toString(36).substring(2);
}
},
async sendOtp() {
if (!this.phone) {
this.errorMessage = 'يرجى إدخال رقم الهاتف';
return;
}
this.loading = true;
this.errorMessage = '';
this.successMessage = '';
try {
const res = await fetch('/api/auth/otp/request', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: this.phone,
role: 'student',
full_name: this.fullName
})
});
const data = await res.json();
if (res.ok) {
this.authStep = 'otp';
this.phoneDisplay = data.data?.phone_masked || this.phone;
this.successMessage = data.message;
if (data.debug_otp) {
this.otpCode = data.debug_otp;
}
this.startTimer(60);
} else {
this.errorMessage = data.message || 'فشل إرسال رمز التحقق. يرجى مراجعة إعدادات NABEH في السيرفر.';
}
} catch (e) {
this.errorMessage = 'حدث خطأ في الاتصال بالخادم. يرجى فحص /api/test/nabeh';
} finally {
this.loading = false;
}
},
async verifyOtp() {
if (!this.otpCode || this.otpCode.length < 6) {
this.errorMessage = 'يرجى إدخال رمز التحقق المكون من 6 أرقام';
return;
}
this.loading = true;
this.errorMessage = '';
try {
const res = await fetch('/api/auth/otp/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: this.phone,
otp: this.otpCode,
role: 'student',
full_name: this.fullName,
device_fingerprint: this.deviceFingerprint
})
});
const data = await res.json();
if (res.ok && data.data?.token) {
localStorage.setItem('saqel_student_jwt', data.data.token);
this.studentData = data.data.user;
this.isLoggedIn = true;
this.successMessage = 'تم تسجيل الدخول بنجاح!';
} else {
this.errorMessage = data.message || 'رمز التحقق غير صحيح';
}
} catch (e) {
this.errorMessage = 'حدث خطأ أثناء التحقق من الرمز';
} finally {
this.loading = false;
}
},
async fetchProfile(token) {
try {
const res = await fetch('/api/auth/me', {
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await res.json();
if (res.ok && data.data) {
this.studentData = {
name: data.data.full_name,
phone: data.data.phone_number,
role: data.data.role
};
this.isLoggedIn = true;
} else {
localStorage.removeItem('saqel_student_jwt');
this.isLoggedIn = false;
}
} catch (e) {
this.isLoggedIn = false;
}
},
logout() {
const token = localStorage.getItem('saqel_student_jwt');
if (token) {
fetch('/api/auth/logout', {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token }
}).catch(() => {});
}
localStorage.removeItem('saqel_student_jwt');
this.isLoggedIn = false;
this.authStep = 'phone';
this.otpCode = '';
this.errorMessage = '';
this.successMessage = '';
},
startTimer(seconds) {
this.timer = seconds;
clearInterval(this.timerInterval);
this.timerInterval = setInterval(() => {
if (this.timer > 0) {
this.timer--;
} else {
clearInterval(this.timerInterval);
}
}, 1000);
}
};
}
</script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
</head>
<body x-data="studentAuth()" x-init="initApp()">
<body>
<!-- Header -->
<header>
@@ -723,21 +546,17 @@ class StudentPortal
</div>
</a>
<div>
<template x-if="isLoggedIn">
<div style="display: flex; align-items: center; gap: 12px;">
<span style="font-size: 13px; color: var(--text-secondary);" x-text="'مرحباً، ' + (studentData.name || 'طالب صَقِل')"></span>
<button @click="logout()" style="background: none; border: 1px solid rgba(239,68,68,0.4); color: #F87171; border-radius: 8px; padding: 6px 12px; font-size: 12px; cursor: pointer;">
تسجيل الخروج
</button>
</div>
</template>
<template x-if="!isLoggedIn">
<a href="/teacher" class="nav-link">
<span>أنت معلم؟</span>
<span class="nav-link-highlight">بوابة المعلمين ←</span>
</a>
</template>
<div id="header_user_actions">
<a href="/teacher" class="nav-link" id="switch_to_teacher_link">
<span>أنت معلم؟</span>
<span class="nav-link-highlight">بوابة المعلمين ←</span>
</a>
<div id="auth_user_badge" style="display: none; align-items: center; gap: 12px;">
<span style="font-size: 13px; color: var(--text-secondary);" id="student_display_name"></span>
<button onclick="handleLogout()" style="background: none; border: 1px solid rgba(239,68,68,0.4); color: #F87171; border-radius: 8px; padding: 6px 12px; font-size: 12px; cursor: pointer;">
تسجيل الخروج
</button>
</div>
</div>
</div>
</div>
@@ -750,7 +569,7 @@ class StudentPortal
<!-- ========================================== -->
<!-- 1. AUTHENTICATION BOX (LOGIN / OTP) -->
<!-- ========================================== -->
<div x-show="!isLoggedIn" class="auth-card-wrapper">
<div id="auth_container" class="auth-card-wrapper">
<div class="auth-header">
<div class="icon-box">
@@ -764,77 +583,61 @@ class StudentPortal
<div class="auth-box">
<!-- Alerts -->
<template x-if="errorMessage">
<div class="alert alert-error">
<span>⚠️</span>
<span x-text="errorMessage"></span>
</div>
</template>
<template x-if="successMessage">
<div class="alert alert-success">
<span>✓</span>
<span x-text="successMessage"></span>
</div>
</template>
<!-- STEP 1: Phone Number (Shown by default) -->
<div x-show="authStep === 'phone'">
<form @submit.prevent="sendOtp()">
<div class="form-group">
<label class="form-label">الاسم الكامل للطالب (اختياري للشهادات)</label>
<input type="text" x-model="fullName" placeholder="مثال: أحمد محمد خالد" class="input-text">
</div>
<div class="form-group">
<label class="form-label">رقم الهاتف (الواتساب) <span style="color: #EF4444;">*</span></label>
<div class="phone-input-group">
<div class="country-badge">🇯🇴 +962</div>
<input type="tel" x-model="phone" required placeholder="790000000" class="input-text input-phone">
</div>
<span class="form-hint">يصلك رمز التحقق مباشرة على الواتساب المعتمد.</span>
</div>
<button type="submit" :disabled="loading" class="btn-primary">
<template x-if="loading">
<div class="spinner"></div>
</template>
<span x-text="loading ? 'جارٍ الإرسال...' : 'إرسال رمز التحقق (OTP) ←'">إرسال رمز التحقق (OTP) ←</span>
</button>
</form>
<!-- Alert Messages -->
<div id="alert_box_error" class="alert alert-error" style="display: none;">
<span>⚠️</span>
<span id="alert_error_msg"></span>
</div>
<!-- STEP 2: OTP Verification (Hidden initially via CSS) -->
<div x-show="authStep === 'otp'" style="display: none;">
<div style="text-align: center; margin-bottom: 20px;">
<span style="font-size: 12px; color: var(--text-muted);">تم إرسال رمز التحقق إلى:</span>
<div style="font-family: monospace; font-size: 15px; font-weight: 800; color: var(--accent-cyan); margin-top: 4px;" x-text="phoneDisplay"></div>
<div id="alert_box_success" class="alert alert-success" style="display: none;">
<span>✓</span>
<span id="alert_success_msg"></span>
</div>
<!-- STEP 1: Phone Number (Always Visible First) -->
<div id="step_phone_container">
<div class="form-group">
<label class="form-label">الاسم الكامل للطالب (اختياري للشهادات)</label>
<input type="text" id="student_fullname" placeholder="مثال: أحمد محمد خالد" class="input-text">
</div>
<form @submit.prevent="verifyOtp()">
<div class="form-group">
<label class="form-label" style="text-align: center;">أدخل رمز التحقق (6 أرقام)</label>
<input type="text" x-model="otpCode" maxlength="6" autofocus placeholder="• • • • • •" class="input-text otp-input">
<div class="form-group">
<label class="form-label">رقم الهاتف (الواتساب) <span style="color: #EF4444;">*</span></label>
<div class="phone-input-group">
<div class="country-badge">🇯🇴 +962</div>
<input type="tel" id="student_phone" required placeholder="790000000" class="input-text input-phone">
</div>
<span class="form-hint">يصلك رمز التحقق مباشرة على الواتساب المعتمد.</span>
</div>
<button type="submit" :disabled="loading || otpCode.length < 6" class="btn-primary">
<template x-if="loading">
<div class="spinner"></div>
</template>
<span x-text="loading ? 'جارٍ التحقق...' : 'تأكيد الدخول للمنصة ✨'">تأكيد الدخول للمنصة ✨</span>
</button>
<button type="button" id="btn_send_otp" onclick="handleSendOtp(event)" class="btn-primary">
<span id="btn_send_text">إرسال رمز التحقق (OTP) ←</span>
<div id="btn_send_spinner" class="spinner" style="display: none;"></div>
</button>
</div>
<div style="display: flex; align-items: center; justify-content: space-between; margin-top: 18px;">
<button type="button" @click="authStep = 'phone'" class="btn-secondary">← تعديل الرقم</button>
<template x-if="timer > 0">
<span style="font-size: 12px; color: var(--text-muted);" x-text="'إعادة الإرسال بعد (' + timer + 'ث)'"></span>
</template>
<template x-if="timer === 0">
<button type="button" @click="sendOtp()" class="btn-secondary btn-link-cyan">إعادة إرسال الرمز ↺</button>
</template>
</div>
</form>
<!-- STEP 2: OTP Verification (Hidden Initially) -->
<div id="step_otp_container" style="display: none;">
<div style="text-align: center; margin-bottom: 20px;">
<span style="font-size: 12px; color: var(--text-muted);">تم إرسال رمز التحقق إلى:</span>
<div style="font-family: monospace; font-size: 15px; font-weight: 800; color: var(--accent-cyan); margin-top: 4px;" id="otp_target_display"></div>
</div>
<div class="form-group">
<label class="form-label" style="text-align: center;">أدخل رمز التحقق (6 أرقام)</label>
<input type="text" id="student_otp_code" maxlength="6" autofocus placeholder="• • • • • •" class="input-text otp-input">
</div>
<button type="button" id="btn_verify_otp" onclick="handleVerifyOtp(event)" class="btn-primary">
<span id="btn_verify_text">تأكيد الدخول للمنصة ✨</span>
<div id="btn_verify_spinner" class="spinner" style="display: none;"></div>
</button>
<div style="display: flex; align-items: center; justify-content: space-between; margin-top: 18px;">
<button type="button" onclick="switchToPhoneStep()" class="btn-secondary">← تعديل الرقم</button>
<span id="resend_timer_label" style="font-size: 12px; color: var(--text-muted); display: none;"></span>
<button type="button" id="btn_resend" onclick="handleSendOtp(event)" class="btn-secondary btn-link-cyan" style="display: none;">إعادة إرسال الرمز ↺</button>
</div>
</div>
<div class="auth-footer">
@@ -848,12 +651,12 @@ class StudentPortal
<!-- ========================================== -->
<!-- 2. STUDENT DASHBOARD (AUTHENTICATED) -->
<!-- ========================================== -->
<div x-show="isLoggedIn" style="width: 100%; display: none;">
<div id="dashboard_container" style="width: 100%; display: none;">
<div class="dashboard-hero">
<div>
<span style="display: inline-block; font-size: 11px; font-weight: 800; color: var(--accent-cyan); background: rgba(0,245,212,0.12); border: 1px solid rgba(0,245,212,0.3); padding: 4px 12px; border-radius: 999px; margin-bottom: 12px;">دفعة التوجيهي 2007/2008</span>
<h2 style="font-size: 26px; font-weight: 900; color: #FFFFFF;" x-text="'أهلاً بك، ' + (studentData.name || 'طالبنا المتميز') + ' 🚀'"></h2>
<h2 style="font-size: 26px; font-weight: 900; color: #FFFFFF;" id="dashboard_welcome_title">أهلاً بك يا بطلنا 🚀</h2>
<p style="font-size: 13px; color: var(--text-secondary); margin-top: 4px;">رحلتك لصقل الفهم وتحقيق أعلى معدل وزاري تبدأ هنا.</p>
</div>
@@ -902,27 +705,25 @@ class StudentPortal
<h3 style="font-size: 20px; font-weight: 900;">كيف يعمل الكويز الصدمي داخل الفيديو؟</h3>
<p style="font-size: 12px; color: var(--text-muted); margin-top: 4px;">يتوقف الفيديو تلقائياً عند لحظة قياس الفهم. إذا أخطأت، يعيدك المشغل 45 ثانية لمشاهدة شرح المفهوم مجدداً.</p>
<div class="interactive-quiz-container" x-data="{ selectedOpt: null, answered: false, isCorrect: false }">
<div class="interactive-quiz-container">
<div style="font-size: 11px; font-weight: 800; color: var(--accent-gold); margin-bottom: 8px;">سؤال اللحظة (الدقيقة 08:30 من درس الاشتقاق):</div>
<p style="font-size: 14px; font-weight: 800; margin-bottom: 14px;">ما هو مشتق اقتران الجيب f(x) = sin(x) بالنسبة لـ x؟</p>
<div>
<div @click="selectedOpt = 1; answered = true; isCorrect = true"
:class="answered && selectedOpt === 1 ? 'quiz-option correct' : 'quiz-option'">
<div id="quiz_options_container">
<div class="quiz-option" onclick="handleQuizAnswer(this, true)">
<span>أ) cos(x)</span>
<span x-show="answered && selectedOpt === 1" style="color: #34D399;">✓ إجابة صحيحة! استئناف الفيديو</span>
<span class="quiz-status" style="display: none; color: #34D399;">✓ إجابة صحيحة! استئناف الفيديو</span>
</div>
<div @click="selectedOpt = 2; answered = true; isCorrect = false"
:class="answered && selectedOpt === 2 ? 'quiz-option incorrect' : 'quiz-option'">
<div class="quiz-option" onclick="handleQuizAnswer(this, false)">
<span>ب) -cos(x)</span>
<span x-show="answered && selectedOpt === 2" style="color: #F87171;">✗ خطأ — سيتم إرجاعك 45 ثانية للشرح</span>
<span class="quiz-status" style="display: none; color: #F87171;">✗ خطأ — سيتم إرجاعك 45 ثانية للشرح</span>
</div>
</div>
</div>
</div>
<div class="watermark-anim">
<span x-text="'SAQEL-DRM • ' + (studentData.phone || '079XXXXXXX')"></span>
<span id="drm_watermark_text">SAQEL-DRM • 079XXXXXXX</span>
</div>
</div>
@@ -943,6 +744,264 @@ class StudentPortal
</div>
</footer>
<!-- Pure Bulletproof Vanilla JavaScript Logic (100% Native Reliability) -->
<script>
let countdownTimer = null;
let timerSeconds = 0;
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('saqel_student_jwt');
if (token) {
await checkActiveSession(token);
}
});
function showError(msg) {
const errBox = document.getElementById('alert_box_error');
const errSpan = document.getElementById('alert_error_msg');
const okBox = document.getElementById('alert_box_success');
okBox.style.display = 'none';
errSpan.textContent = msg;
errBox.style.display = 'flex';
}
function showSuccess(msg) {
const okBox = document.getElementById('alert_box_success');
const okSpan = document.getElementById('alert_success_msg');
const errBox = document.getElementById('alert_box_error');
errBox.style.display = 'none';
okSpan.textContent = msg;
okBox.style.display = 'flex';
}
function clearAlerts() {
document.getElementById('alert_box_error').style.display = 'none';
document.getElementById('alert_box_success').style.display = 'none';
}
function switchToPhoneStep() {
document.getElementById('step_otp_container').style.display = 'none';
document.getElementById('step_phone_container').style.display = 'block';
clearAlerts();
clearInterval(countdownTimer);
}
function switchToOtpStep(maskedPhone, debugOtp) {
document.getElementById('step_phone_container').style.display = 'none';
document.getElementById('step_otp_container').style.display = 'block';
document.getElementById('otp_target_display').textContent = maskedPhone;
if (debugOtp) {
document.getElementById('student_otp_code').value = debugOtp;
}
startTimer(60);
}
function startTimer(seconds) {
timerSeconds = seconds;
clearInterval(countdownTimer);
const timerLabel = document.getElementById('resend_timer_label');
const resendBtn = document.getElementById('btn_resend');
resendBtn.style.display = 'none';
timerLabel.style.display = 'inline';
timerLabel.textContent = `إعادة الإرسال بعد (${timerSeconds}ث)`;
countdownTimer = setInterval(() => {
timerSeconds--;
if (timerSeconds > 0) {
timerLabel.textContent = `إعادة الإرسال بعد (${timerSeconds}ث)`;
} else {
clearInterval(countdownTimer);
timerLabel.style.display = 'none';
resendBtn.style.display = 'inline';
}
}, 1000);
}
async function getDeviceFingerprint() {
try {
const raw = [
navigator.userAgent,
navigator.language,
screen.width + 'x' + screen.height,
Intl.DateTimeFormat().resolvedOptions().timeZone
].join('###');
const msgUint8 = new TextEncoder().encode(raw);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
} catch (e) {
return 'student_web_' + Math.random().toString(36).substring(2);
}
}
async function handleSendOtp(e) {
if (e) e.preventDefault();
clearAlerts();
const phoneInput = document.getElementById('student_phone');
const nameInput = document.getElementById('student_fullname');
const sendBtn = document.getElementById('btn_send_otp');
const sendText = document.getElementById('btn_send_text');
const sendSpinner = document.getElementById('btn_send_spinner');
const phone = phoneInput.value.trim();
const fullName = nameInput.value.trim();
if (!phone) {
showError('يرجى إدخال رقم الهاتف');
phoneInput.focus();
return;
}
sendBtn.disabled = true;
sendText.textContent = 'جارٍ إرسال البطاقة عبر الواتساب...';
sendSpinner.style.display = 'block';
try {
const res = await fetch('/api/auth/otp/request', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: phone,
role: 'student',
full_name: fullName
})
});
const data = await res.json();
console.log('Nabeh Student OTP Response:', data);
if (res.ok && data.status === 'success') {
showSuccess(data.message || 'تم إرسال بطاقة التحقق عبر الواتساب!');
switchToOtpStep(data.data?.phone_masked || phone, data.debug_otp);
} else {
showError(data.message || 'فشل إرسال رمز التحقق من منصة نبيه.');
}
} catch (err) {
console.error('Fetch error:', err);
showError('حدث خطأ في الاتصال بالسيرفر. تأكد من اتصال الإنترنت.');
} finally {
sendBtn.disabled = false;
sendText.textContent = 'إرسال رمز التحقق (OTP) ←';
sendSpinner.style.display = 'none';
}
}
async function handleVerifyOtp(e) {
if (e) e.preventDefault();
clearAlerts();
const phone = document.getElementById('student_phone').value.trim();
const fullName = document.getElementById('student_fullname').value.trim();
const otpInput = document.getElementById('student_otp_code');
const otpCode = otpInput.value.trim();
const verifyBtn = document.getElementById('btn_verify_otp');
const verifyText = document.getElementById('btn_verify_text');
const verifySpinner = document.getElementById('btn_verify_spinner');
if (!otpCode || otpCode.length < 6) {
showError('يرجى إدخال رمز التحقق المكون من 6 أرقام');
otpInput.focus();
return;
}
verifyBtn.disabled = true;
verifyText.textContent = 'جارٍ التحقق وتأكيد الجلسة...';
verifySpinner.style.display = 'block';
try {
const fingerprint = await getDeviceFingerprint();
const res = await fetch('/api/auth/otp/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: phone,
otp: otpCode,
role: 'student',
full_name: fullName,
device_fingerprint: fingerprint
})
});
const data = await res.json();
console.log('Verify Student Response:', data);
if (res.ok && data.status === 'success' && data.data?.token) {
localStorage.setItem('saqel_student_jwt', data.data.token);
renderDashboard(data.data.user);
} else {
showError(data.message || 'رمز التحقق غير صحيح أو منتهي الصلاحية');
}
} catch (err) {
console.error('Verify error:', err);
showError('حدث خطأ في التحقق من الرمز.');
} finally {
verifyBtn.disabled = false;
verifyText.textContent = 'تأكيد الدخول للمنصة ✨';
verifySpinner.style.display = 'none';
}
}
async function checkActiveSession(token) {
try {
const res = await fetch('/api/auth/me', {
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await res.json();
if (res.ok && data.data) {
renderDashboard({
name: data.data.full_name,
phone: data.data.phone_number
});
} else {
localStorage.removeItem('saqel_student_jwt');
}
} catch (e) {
console.error('Session check error:', e);
}
}
function renderDashboard(user) {
document.getElementById('auth_container').style.display = 'none';
document.getElementById('dashboard_container').style.display = 'block';
document.getElementById('switch_to_teacher_link').style.display = 'none';
document.getElementById('auth_user_badge').style.display = 'flex';
const displayName = user?.name || 'طالبنا المتميز';
document.getElementById('student_display_name').textContent = `مرحباً، ${displayName}`;
document.getElementById('dashboard_welcome_title').textContent = `أهلاً بك، ${displayName} 🚀`;
document.getElementById('drm_watermark_text').textContent = `SAQEL-DRM • ${user?.phone || '079XXXXXXX'}`;
}
function handleLogout() {
const token = localStorage.getItem('saqel_student_jwt');
if (token) {
fetch('/api/auth/logout', {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token }
}).catch(() => {});
}
localStorage.removeItem('saqel_student_jwt');
location.reload();
}
function handleQuizAnswer(el, isCorrect) {
const options = document.querySelectorAll('.quiz-option');
options.forEach(opt => {
opt.classList.remove('correct', 'incorrect');
opt.querySelector('.quiz-status').style.display = 'none';
});
if (isCorrect) {
el.classList.add('correct');
} else {
el.classList.add('incorrect');
}
el.querySelector('.quiz-status').style.display = 'inline';
}
</script>
</body>
</html>
HTML;
+309 -261
View File
@@ -18,7 +18,7 @@ class TeacherPortal
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800;900&display=swap" rel="stylesheet">
<!-- 1. Pure Self-Contained Luxury CSS (Zero External CDN Failure Risk) -->
<!-- Pure Self-Contained Luxury CSS (Zero External CDN Dependency) -->
<style>
:root {
--bg-dark: #0B132B;
@@ -472,184 +472,8 @@ class TeacherPortal
to { transform: rotate(360deg); }
}
</style>
<!-- 2. Alpine Component Setup -->
<script>
function teacherAuth() {
return {
isLoggedIn: false,
authStep: 'phone', // 'phone' | 'otp'
phone: '',
fullName: '',
otpCode: '',
phoneDisplay: '',
loading: false,
errorMessage: '',
successMessage: '',
timer: 0,
timerInterval: null,
deviceFingerprint: '',
teacherData: {},
async initApp() {
try {
this.deviceFingerprint = await this.generateDeviceFingerprint();
const token = localStorage.getItem('saqel_teacher_jwt');
if (token) {
await this.fetchProfile(token);
}
} catch (e) {
console.error('Teacher App init error:', e);
}
},
async generateDeviceFingerprint() {
try {
const raw = [
navigator.userAgent,
screen.width + 'x' + screen.height,
Intl.DateTimeFormat().resolvedOptions().timeZone
].join('###');
const msgUint8 = new TextEncoder().encode(raw);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
} catch (e) {
return 'teacher_web_' + Math.random().toString(36).substring(2);
}
},
async sendOtp() {
if (!this.phone) {
this.errorMessage = 'يرجى إدخال رقم الهاتف المسجل';
return;
}
this.loading = true;
this.errorMessage = '';
this.successMessage = '';
try {
const res = await fetch('/api/auth/otp/request', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: this.phone,
role: 'teacher',
full_name: this.fullName
})
});
const data = await res.json();
if (res.ok) {
this.authStep = 'otp';
this.phoneDisplay = data.data?.phone_masked || this.phone;
this.successMessage = data.message;
if (data.debug_otp) {
this.otpCode = data.debug_otp;
}
this.startTimer(60);
} else {
this.errorMessage = data.message || 'فشل إرسال رمز التحقق. يرجى مراجعة إعدادات NABEH في السيرفر.';
}
} catch (e) {
this.errorMessage = 'حدث خطأ في الاتصال بالخادم. يرجى فحص /api/test/nabeh';
} finally {
this.loading = false;
}
},
async verifyOtp() {
if (!this.otpCode || this.otpCode.length < 6) {
this.errorMessage = 'يرجى إدخال رمز التحقق المكون من 6 أرقام';
return;
}
this.loading = true;
this.errorMessage = '';
try {
const res = await fetch('/api/auth/otp/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: this.phone,
otp: this.otpCode,
role: 'teacher',
full_name: this.fullName,
device_fingerprint: this.deviceFingerprint
})
});
const data = await res.json();
if (res.ok && data.data?.token) {
localStorage.setItem('saqel_teacher_jwt', data.data.token);
this.teacherData = data.data.user;
this.isLoggedIn = true;
this.successMessage = 'تم تسجيل الدخول بنجاح!';
} else {
this.errorMessage = data.message || 'رمز التحقق غير صحيح أو غير مصرح للمعلم';
}
} catch (e) {
this.errorMessage = 'حدث خطأ أثناء التحقق من الرمز';
} finally {
this.loading = false;
}
},
async fetchProfile(token) {
try {
const res = await fetch('/api/auth/me', {
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await res.json();
if (res.ok && data.data && (data.data.role === 'teacher' || data.data.role === 'super_admin')) {
this.teacherData = {
name: data.data.full_name,
phone: data.data.phone_number,
role: data.data.role
};
this.isLoggedIn = true;
} else {
localStorage.removeItem('saqel_teacher_jwt');
this.isLoggedIn = false;
}
} catch (e) {
this.isLoggedIn = false;
}
},
logout() {
const token = localStorage.getItem('saqel_teacher_jwt');
if (token) {
fetch('/api/auth/logout', {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token }
}).catch(() => {});
}
localStorage.removeItem('saqel_teacher_jwt');
this.isLoggedIn = false;
this.authStep = 'phone';
this.otpCode = '';
this.errorMessage = '';
this.successMessage = '';
},
startTimer(seconds) {
this.timer = seconds;
clearInterval(this.timerInterval);
this.timerInterval = setInterval(() => {
if (this.timer > 0) {
this.timer--;
} else {
clearInterval(this.timerInterval);
}
}, 1000);
}
};
}
</script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
</head>
<body x-data="teacherAuth()" x-init="initApp()">
<body>
<!-- Header -->
<header>
@@ -663,21 +487,17 @@ class TeacherPortal
</div>
</a>
<div>
<template x-if="isLoggedIn">
<div style="display: flex; align-items: center; gap: 12px;">
<span style="font-size: 13px; color: var(--text-secondary);" x-text="'أهلاً، ' + (teacherData.name || 'أستاذنا')"></span>
<button @click="logout()" style="background: none; border: 1px solid rgba(239,68,68,0.4); color: #F87171; border-radius: 8px; padding: 6px 12px; font-size: 12px; cursor: pointer;">
تسجيل الخروج
</button>
</div>
</template>
<template x-if="!isLoggedIn">
<a href="/student" class="nav-link">
<span>أنت طالب؟</span>
<span class="nav-link-highlight">بوابة الطلاب ←</span>
</a>
</template>
<div id="header_user_actions">
<a href="/student" class="nav-link" id="switch_to_student_link">
<span>أنت طالب؟</span>
<span class="nav-link-highlight">بوابة الطلاب ←</span>
</a>
<div id="auth_user_badge" style="display: none; align-items: center; gap: 12px;">
<span style="font-size: 13px; color: var(--text-secondary);" id="teacher_display_name"></span>
<button onclick="handleLogout()" style="background: none; border: 1px solid rgba(239,68,68,0.4); color: #F87171; border-radius: 8px; padding: 6px 12px; font-size: 12px; cursor: pointer;">
تسجيل الخروج
</button>
</div>
</div>
</div>
</div>
@@ -690,7 +510,7 @@ class TeacherPortal
<!-- ========================================== -->
<!-- 1. AUTHENTICATION BOX (LOGIN / OTP) -->
<!-- ========================================== -->
<div x-show="!isLoggedIn" class="auth-card-wrapper">
<div id="auth_container" class="auth-card-wrapper">
<div class="auth-header">
<div class="icon-box">
@@ -704,77 +524,61 @@ class TeacherPortal
<div class="auth-box">
<!-- Alerts -->
<template x-if="errorMessage">
<div class="alert alert-error">
<span>⚠️</span>
<span x-text="errorMessage"></span>
</div>
</template>
<template x-if="successMessage">
<div class="alert alert-success">
<span>✓</span>
<span x-text="successMessage"></span>
</div>
</template>
<!-- STEP 1: Phone Number (Shown by default) -->
<div x-show="authStep === 'phone'">
<form @submit.prevent="sendOtp()">
<div class="form-group">
<label class="form-label">اسم الأستاذ / المعلم</label>
<input type="text" x-model="fullName" placeholder="مثال: الأستاذ حمزة النجار" class="input-text">
</div>
<div class="form-group">
<label class="form-label">رقم الهاتف (الواتساب) <span style="color: #EF4444;">*</span></label>
<div class="phone-input-group">
<div class="country-badge">🇯🇴 +962</div>
<input type="tel" x-model="phone" required placeholder="790000000" class="input-text input-phone">
</div>
<span class="form-hint">يصلك رمز التحقق مباشرة على الواتساب المعتمد.</span>
</div>
<button type="submit" :disabled="loading" class="btn-primary">
<template x-if="loading">
<div class="spinner"></div>
</template>
<span x-text="loading ? 'جارٍ التحقق...' : 'دخول استوديو المعلم (OTP) ←'">دخول استوديو المعلم (OTP) ←</span>
</button>
</form>
<!-- Alert Messages -->
<div id="alert_box_error" class="alert alert-error" style="display: none;">
<span>⚠️</span>
<span id="alert_error_msg"></span>
</div>
<!-- STEP 2: OTP Verification (Hidden initially via CSS until authStep === 'otp') -->
<div x-show="authStep === 'otp'" style="display: none;">
<div style="text-align: center; margin-bottom: 20px;">
<span style="font-size: 12px; color: var(--text-muted);">تم إرسال رمز التحقق إلى:</span>
<div style="font-family: monospace; font-size: 15px; font-weight: 800; color: var(--accent-gold); margin-top: 4px;" x-text="phoneDisplay"></div>
<div id="alert_box_success" class="alert alert-success" style="display: none;">
<span>✓</span>
<span id="alert_success_msg"></span>
</div>
<!-- STEP 1: Phone Number (Always Visible First) -->
<div id="step_phone_container">
<div class="form-group">
<label class="form-label">اسم الأستاذ / المعلم (اختياري)</label>
<input type="text" id="teacher_fullname" placeholder="مثال: الأستاذ حمزة النجار" class="input-text">
</div>
<form @submit.prevent="verifyOtp()">
<div class="form-group">
<label class="form-label" style="text-align: center;">أدخل رمز التحقق (6 أرقام)</label>
<input type="text" x-model="otpCode" maxlength="6" autofocus placeholder="• • • • • •" class="input-text otp-input">
<div class="form-group">
<label class="form-label">رقم الهاتف (الواتساب) <span style="color: #EF4444;">*</span></label>
<div class="phone-input-group">
<div class="country-badge">🇯🇴 +962</div>
<input type="tel" id="teacher_phone" required placeholder="790000000" class="input-text input-phone">
</div>
<span class="form-hint">يصلك رمز التحقق مباشرة على الواتساب المعتمد.</span>
</div>
<button type="submit" :disabled="loading || otpCode.length < 6" class="btn-primary">
<template x-if="loading">
<div class="spinner"></div>
</template>
<span x-text="loading ? 'جارٍ التحقق...' : 'تأكيد الدخول للاستوديو 🎓'">تأكيد الدخول للاستوديو 🎓</span>
</button>
<button type="button" id="btn_send_otp" onclick="handleSendOtp(event)" class="btn-primary">
<span id="btn_send_text">دخول استوديو المعلم (OTP) ←</span>
<div id="btn_send_spinner" class="spinner" style="display: none;"></div>
</button>
</div>
<div style="display: flex; align-items: center; justify-content: space-between; margin-top: 18px;">
<button type="button" @click="authStep = 'phone'" class="btn-secondary">← تعديل الرقم</button>
<template x-if="timer > 0">
<span style="font-size: 12px; color: var(--text-muted);" x-text="'إعادة الإرسال بعد (' + timer + 'ث)'"></span>
</template>
<template x-if="timer === 0">
<button type="button" @click="sendOtp()" class="btn-secondary btn-link-gold">إعادة إرسال الرمز ↺</button>
</template>
</div>
</form>
<!-- STEP 2: OTP Verification (Hidden Initially) -->
<div id="step_otp_container" style="display: none;">
<div style="text-align: center; margin-bottom: 20px;">
<span style="font-size: 12px; color: var(--text-muted);">تم إرسال رمز التحقق إلى:</span>
<div style="font-family: monospace; font-size: 15px; font-weight: 800; color: var(--accent-gold); margin-top: 4px;" id="otp_target_display"></div>
</div>
<div class="form-group">
<label class="form-label" style="text-align: center;">أدخل رمز التحقق (6 أرقام)</label>
<input type="text" id="teacher_otp_code" maxlength="6" autofocus placeholder="• • • • • •" class="input-text otp-input">
</div>
<button type="button" id="btn_verify_otp" onclick="handleVerifyOtp(event)" class="btn-primary">
<span id="btn_verify_text">تأكيد الدخول للاستوديو 🎓</span>
<div id="btn_verify_spinner" class="spinner" style="display: none;"></div>
</button>
<div style="display: flex; align-items: center; justify-content: space-between; margin-top: 18px;">
<button type="button" onclick="switchToPhoneStep()" class="btn-secondary">← تعديل الرقم</button>
<span id="resend_timer_label" style="font-size: 12px; color: var(--text-muted); display: none;"></span>
<button type="button" id="btn_resend" onclick="handleSendOtp(event)" class="btn-secondary btn-link-gold" style="display: none;">إعادة إرسال الرمز ↺</button>
</div>
</div>
<div class="auth-footer">
@@ -788,12 +592,12 @@ class TeacherPortal
<!-- ========================================== -->
<!-- 2. TEACHER DASHBOARD (AUTHENTICATED) -->
<!-- ========================================== -->
<div x-show="isLoggedIn" style="width: 100%; display: none;">
<div id="dashboard_container" style="width: 100%; display: none;">
<div class="dashboard-hero">
<div>
<span style="display: inline-block; font-size: 11px; font-weight: 800; color: var(--accent-gold); background: rgba(255,209,102,0.12); border: 1px solid rgba(255,209,102,0.3); padding: 4px 12px; border-radius: 999px; margin-bottom: 12px;">استوديو المعلم المعتمد</span>
<h2 style="font-size: 26px; font-weight: 900; color: #FFFFFF;" x-text="'أهلاً بك، ' + (teacherData.name || 'أستاذنا الفاضل') + ' 👨‍🏫'"></h2>
<h2 style="font-size: 26px; font-weight: 900; color: #FFFFFF;" id="dashboard_welcome_title">أهلاً بك يا أستاذنا 👨‍🏫</h2>
<p style="font-size: 13px; color: var(--text-secondary); margin-top: 4px;">إدارة دوراتك، إدراج كويزات الفيديو التفاعلية، ومتابعة نمو طلابك.</p>
</div>
@@ -854,7 +658,7 @@ class TeacherPortal
<input type="text" placeholder="الخيار الثاني (الخاطئ)" class="input-text">
</div>
<button class="btn-primary" style="padding: 10px;">حفظ الكويز داخل الفيديو ✓</button>
<button type="button" class="btn-primary" style="padding: 10px;">حفظ الكويز داخل الفيديو ✓</button>
</div>
</div>
</div>
@@ -877,6 +681,250 @@ class TeacherPortal
</div>
</footer>
<!-- Pure Bulletproof Vanilla JavaScript Logic (100% Native Reliability) -->
<script>
let countdownTimer = null;
let timerSeconds = 0;
// On Page Load: Check existing session
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('saqel_teacher_jwt');
if (token) {
await checkActiveSession(token);
}
});
function showError(msg) {
const errBox = document.getElementById('alert_box_error');
const errSpan = document.getElementById('alert_error_msg');
const okBox = document.getElementById('alert_box_success');
okBox.style.display = 'none';
errSpan.textContent = msg;
errBox.style.display = 'flex';
}
function showSuccess(msg) {
const okBox = document.getElementById('alert_box_success');
const okSpan = document.getElementById('alert_success_msg');
const errBox = document.getElementById('alert_box_error');
errBox.style.display = 'none';
okSpan.textContent = msg;
okBox.style.display = 'flex';
}
function clearAlerts() {
document.getElementById('alert_box_error').style.display = 'none';
document.getElementById('alert_box_success').style.display = 'none';
}
function switchToPhoneStep() {
document.getElementById('step_otp_container').style.display = 'none';
document.getElementById('step_phone_container').style.display = 'block';
clearAlerts();
clearInterval(countdownTimer);
}
function switchToOtpStep(maskedPhone, debugOtp) {
document.getElementById('step_phone_container').style.display = 'none';
document.getElementById('step_otp_container').style.display = 'block';
document.getElementById('otp_target_display').textContent = maskedPhone;
if (debugOtp) {
document.getElementById('teacher_otp_code').value = debugOtp;
}
startTimer(60);
}
function startTimer(seconds) {
timerSeconds = seconds;
clearInterval(countdownTimer);
const timerLabel = document.getElementById('resend_timer_label');
const resendBtn = document.getElementById('btn_resend');
resendBtn.style.display = 'none';
timerLabel.style.display = 'inline';
timerLabel.textContent = `إعادة الإرسال بعد (${timerSeconds}ث)`;
countdownTimer = setInterval(() => {
timerSeconds--;
if (timerSeconds > 0) {
timerLabel.textContent = `إعادة الإرسال بعد (${timerSeconds}ث)`;
} else {
clearInterval(countdownTimer);
timerLabel.style.display = 'none';
resendBtn.style.display = 'inline';
}
}, 1000);
}
async function getDeviceFingerprint() {
try {
const raw = [
navigator.userAgent,
screen.width + 'x' + screen.height,
Intl.DateTimeFormat().resolvedOptions().timeZone
].join('###');
const msgUint8 = new TextEncoder().encode(raw);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
} catch (e) {
return 'teacher_web_' + Math.random().toString(36).substring(2);
}
}
// 1. Send OTP Handler
async function handleSendOtp(e) {
if (e) e.preventDefault();
clearAlerts();
const phoneInput = document.getElementById('teacher_phone');
const nameInput = document.getElementById('teacher_fullname');
const sendBtn = document.getElementById('btn_send_otp');
const sendText = document.getElementById('btn_send_text');
const sendSpinner = document.getElementById('btn_send_spinner');
const phone = phoneInput.value.trim();
const fullName = nameInput.value.trim();
if (!phone) {
showError('يرجى إدخال رقم الهاتف المسجل');
phoneInput.focus();
return;
}
sendBtn.disabled = true;
sendText.textContent = 'جارٍ إرسال البطاقة عبر الواتساب...';
sendSpinner.style.display = 'block';
try {
const res = await fetch('/api/auth/otp/request', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: phone,
role: 'teacher',
full_name: fullName
})
});
const data = await res.json();
console.log('Nabeh OTP Response:', data);
if (res.ok && data.status === 'success') {
showSuccess(data.message || 'تم إرسال بطاقة التحقق عبر الواتساب!');
switchToOtpStep(data.data?.phone_masked || phone, data.debug_otp);
} else {
showError(data.message || 'فشل إرسال رمز التحقق من منصة نبيه.');
}
} catch (err) {
console.error('Fetch error:', err);
showError('حدث خطأ في الاتصال بالسيرفر. تأكد من اتصال الإنترنت.');
} finally {
sendBtn.disabled = false;
sendText.textContent = 'دخول استوديو المعلم (OTP) ←';
sendSpinner.style.display = 'none';
}
}
// 2. Verify OTP Handler
async function handleVerifyOtp(e) {
if (e) e.preventDefault();
clearAlerts();
const phone = document.getElementById('teacher_phone').value.trim();
const fullName = document.getElementById('teacher_fullname').value.trim();
const otpInput = document.getElementById('teacher_otp_code');
const otpCode = otpInput.value.trim();
const verifyBtn = document.getElementById('btn_verify_otp');
const verifyText = document.getElementById('btn_verify_text');
const verifySpinner = document.getElementById('btn_verify_spinner');
if (!otpCode || otpCode.length < 6) {
showError('يرجى إدخال رمز التحقق المكون من 6 أرقام');
otpInput.focus();
return;
}
verifyBtn.disabled = true;
verifyText.textContent = 'جارٍ التحقق وتأكيد الجلسة...';
verifySpinner.style.display = 'block';
try {
const fingerprint = await getDeviceFingerprint();
const res = await fetch('/api/auth/otp/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone_number: phone,
otp: otpCode,
role: 'teacher',
full_name: fullName,
device_fingerprint: fingerprint
})
});
const data = await res.json();
console.log('Verify Response:', data);
if (res.ok && data.status === 'success' && data.data?.token) {
localStorage.setItem('saqel_teacher_jwt', data.data.token);
renderDashboard(data.data.user);
} else {
showError(data.message || 'رمز التحقق غير صحيح أو منتهي الصلاحية');
}
} catch (err) {
console.error('Verify error:', err);
showError('حدث خطأ في التحقق من الرمز.');
} finally {
verifyBtn.disabled = false;
verifyText.textContent = 'تأكيد الدخول للاستوديو 🎓';
verifySpinner.style.display = 'none';
}
}
async function checkActiveSession(token) {
try {
const res = await fetch('/api/auth/me', {
headers: { 'Authorization': 'Bearer ' + token }
});
const data = await res.json();
if (res.ok && data.data && (data.data.role === 'teacher' || data.data.role === 'super_admin')) {
renderDashboard({
name: data.data.full_name,
phone: data.data.phone_number
});
} else {
localStorage.removeItem('saqel_teacher_jwt');
}
} catch (e) {
console.error('Session check error:', e);
}
}
function renderDashboard(user) {
document.getElementById('auth_container').style.display = 'none';
document.getElementById('dashboard_container').style.display = 'block';
document.getElementById('switch_to_student_link').style.display = 'none';
document.getElementById('auth_user_badge').style.display = 'flex';
const displayName = user?.name || 'أستاذنا الفاضل';
document.getElementById('teacher_display_name').textContent = `أهلاً، ${displayName}`;
document.getElementById('dashboard_welcome_title').textContent = `أهلاً بك، ${displayName} 👨‍🏫`;
}
function handleLogout() {
const token = localStorage.getItem('saqel_teacher_jwt');
if (token) {
fetch('/api/auth/logout', {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + token }
}).catch(() => {});
}
localStorage.removeItem('saqel_teacher_jwt');
location.reload();
}
</script>
</body>
</html>
HTML;