Nanny7 commited on
Commit
dbfeb5e
·
1 Parent(s): e0f232f

feat: replace auth module with updated Nova bridge and wire auth UI

Browse files
app.py CHANGED
@@ -17,6 +17,11 @@ from openai import OpenAI
17
  from config import Config
18
  from flask_cors import CORS
19
 
 
 
 
 
 
20
  # Groq SDK for Whisper
21
  try:
22
  from groq import Groq
@@ -33,6 +38,8 @@ logging.basicConfig(
33
  app = Flask(__name__)
34
  CORS(app)
35
  app.config.from_object(Config)
 
 
36
 
37
  START_TIME = time.time()
38
 
 
17
  from config import Config
18
  from flask_cors import CORS
19
 
20
+ try:
21
+ from auth_module.flask_auth_routes import auth_blueprint
22
+ except Exception:
23
+ auth_blueprint = None
24
+
25
  # Groq SDK for Whisper
26
  try:
27
  from groq import Groq
 
38
  app = Flask(__name__)
39
  CORS(app)
40
  app.config.from_object(Config)
41
+ if auth_blueprint is not None:
42
+ app.register_blueprint(auth_blueprint, url_prefix="/auth")
43
 
44
  START_TIME = time.time()
45
 
auth_module/README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🔐 RobovAI Auth Module — Standalone Package
2
+
3
+ نظام تسجيل + تسجيل دخول + تفعيل عبر Telegram OTP — جاهز للنقل لأي تطبيق FastAPI.
4
+ يدعم **البوت المركزي** (@robovainova_bot) على سيرفر مختلف عبر Nova API.
5
+
6
+ ## الملفات
7
+
8
+ | ملف | الوظيفة |
9
+ | -------------------- | ----------------------------------------------------------- |
10
+ | `security.py` | JWT tokens, password hashing, password validation |
11
+ | `database.py` | SQLite: users, sessions, OTP, CRUD |
12
+ | `auth_routes.py` | FastAPI routes: signup, login, logout, OTP, verify, me |
13
+ | `nova_client.py` | HTTP client — pushes OTP to Nova for Telegram bot delivery |
14
+ | `telegram_verify.py` | (اختياري) Telegram bot مستقل للتفعيل |
15
+ | `config.py` | Settings / environment variables |
16
+ | `models.py` | Pydantic request/response models |
17
+
18
+ ## الاستخدام السريع (سيرفر مختلف + بوت مركزي)
19
+
20
+ ```python
21
+ # main.py
22
+ from fastapi import FastAPI
23
+ from fastapi.middleware.cors import CORSMiddleware
24
+ from auth_module.auth_routes import auth_router, get_current_user
25
+
26
+ app = FastAPI(title="My App")
27
+
28
+ app.add_middleware(
29
+ CORSMiddleware,
30
+ allow_origins=["*"],
31
+ allow_credentials=True,
32
+ allow_methods=["*"],
33
+ allow_headers=["*"],
34
+ )
35
+
36
+ # Auth routes: /auth/signup, /auth/login, /auth/logout, /auth/me, etc.
37
+ app.include_router(auth_router, prefix="/auth", tags=["Auth"])
38
+
39
+ # Your app routes...
40
+ @app.get("/")
41
+ def root():
42
+ return {"app": "running"}
43
+ ```
44
+
45
+ ## الفلو
46
+
47
+ ```
48
+ 1. المستخدم يعمل signup → POST /auth/signup
49
+ 2. auth_module يولّد OTP → يخزنه محلياً + يبعته لـ Nova API
50
+ 3. المستخدم يروح @robovainova_bot → /verify → يدخل إيميله
51
+ 4. البوت يلاقي الـ OTP → يبعتهوله عبر تليجرام
52
+ 5. المستخدم يدخل الـ OTP في الموقع → POST /auth/verify-otp
53
+ 6. الحساب يتفعّل ✅
54
+ ```
55
+
56
+ ## المتطلبات
57
+
58
+ ```
59
+ fastapi>=0.100.0
60
+ uvicorn[standard]
61
+ pyjwt>=2.8.0
62
+ passlib[bcrypt]>=1.7.4
63
+ pydantic-settings>=2.0.0
64
+ python-dotenv>=1.0.0
65
+ python-multipart>=0.0.6
66
+ httpx>=0.25.0
67
+ ```
68
+
69
+ ## البيئة (.env)
70
+
71
+ ```env
72
+ # مطلوب — JWT Secret
73
+ JWT_SECRET_KEY=your-secret-key-min-32-chars
74
+
75
+ # مطلوب — ربط بالبوت المركزي
76
+ NOVA_API_URL=https://robovai-nova.onrender.com
77
+ NOVA_API_KEY=nova_ext_9f3k7Lm2Xp8qR4vW6yB1cD5eH0jN
78
+ APP_ID=my-new-app
79
+
80
+ # اختياري
81
+ DATABASE_PATH=users.db
82
+ ```
83
+
84
+ > **ملاحظة:** الـ `NOVA_API_KEY` لازم يكون نفس القيمة الموجودة في `EXTERNAL_API_KEY` على سيرفر Nova.
85
+
86
+ ## Signup Page JavaScript Example
87
+
88
+ ```javascript
89
+ // After successful signup, poll for verification
90
+ async function pollVerification(email) {
91
+ const interval = setInterval(async () => {
92
+ const res = await fetch(`/auth/check-verified?email=${email}`);
93
+ const data = await res.json();
94
+ if (data.verified) {
95
+ clearInterval(interval);
96
+ alert("✅ تم تفعيل حسابك!");
97
+ window.location.href = "/login";
98
+ }
99
+ }, 3000); // Poll every 3 seconds
100
+ }
101
+ ```
102
+
auth_module/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """
2
+ 🔐 RobovAI Auth Module — Standalone
3
+ ════════════════════════════════════
4
+ Reusable auth system: JWT, OTP, Telegram verification.
5
+ Supports centralized bot mode via Nova API.
6
+ """
auth_module/auth_routes.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 🌐 Auth Module — FastAPI Routes
3
+ ═══════════════════════════════════════════
4
+ Standalone auth router: signup, login, logout, OTP, verify, me.
5
+
6
+ Usage:
7
+ from auth_module.auth_routes import auth_router
8
+ app.include_router(auth_router, prefix="/auth", tags=["Auth"])
9
+ """
10
+
11
+ import os
12
+ import random
13
+ import logging
14
+ from datetime import datetime, timedelta
15
+ from typing import Dict, Any
16
+
17
+ from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
18
+ from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
19
+
20
+ from .models import UserCreate, OTPRequest, OTPVerify
21
+ from .security import (
22
+ create_access_token,
23
+ decode_access_token,
24
+ validate_password_strength,
25
+ )
26
+ from .database import auth_db
27
+
28
+ logger = logging.getLogger("auth_module.routes")
29
+
30
+ auth_router = APIRouter()
31
+
32
+ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login", auto_error=False)
33
+
34
+ # ─── Dependency: current user ─────────────────────────────────
35
+
36
+
37
+ async def get_current_user(
38
+ token: str = Depends(oauth2_scheme), request: Request = None
39
+ ):
40
+ """Extract current user from JWT (cookie or Authorization header)."""
41
+ # Try cookie first
42
+ if (not token) and request:
43
+ cookie_val = request.cookies.get("access_token")
44
+ if cookie_val:
45
+ token = (
46
+ cookie_val.split(" ")[-1]
47
+ if cookie_val.startswith("Bearer ")
48
+ else cookie_val
49
+ )
50
+
51
+ if not token:
52
+ raise HTTPException(
53
+ status_code=status.HTTP_401_UNAUTHORIZED,
54
+ detail="غير مصرح — سجّل دخولك أولاً",
55
+ )
56
+
57
+ payload = decode_access_token(token)
58
+ if not payload:
59
+ raise HTTPException(status_code=401, detail="جلسة منتهية — سجّل دخولك مرة أخرى")
60
+
61
+ user = await auth_db.get_user_by_email(payload.get("sub", ""))
62
+ if not user:
63
+ raise HTTPException(status_code=401, detail="المستخدم غير موجود")
64
+ return user
65
+
66
+
67
+ # ═══════════════════════════════════════════════════════════════
68
+ # 📝 SIGNUP
69
+ # ═══════════════════════════════════════════════════════════════
70
+
71
+
72
+ @auth_router.post("/signup")
73
+ async def register(user: UserCreate):
74
+ """Register a new user — account needs Telegram OTP verification."""
75
+ valid, msg = validate_password_strength(user.password)
76
+ if not valid:
77
+ raise HTTPException(status_code=400, detail=msg)
78
+
79
+ if "@" not in user.email or "." not in user.email:
80
+ raise HTTPException(status_code=400, detail="البريد الإلكتروني غير صحيح")
81
+
82
+ res = await auth_db.create_user(
83
+ user.email, user.password, user.full_name, phone=user.phone
84
+ )
85
+ if not res:
86
+ raise HTTPException(status_code=400, detail="البريد الإلكتروني مسجل بالفعل")
87
+
88
+ # Generate OTP
89
+ otp = str(random.randint(100000, 999999))
90
+ await auth_db.store_otp(res["id"], otp, "telegram_verify", minutes=10)
91
+
92
+ # Push OTP to centralized Nova bot (if configured)
93
+ try:
94
+ from .nova_client import nova_client
95
+ from .config import auth_settings
96
+
97
+ if nova_client.is_configured:
98
+ await nova_client.push_otp(
99
+ email=user.email,
100
+ code=otp,
101
+ app_id=auth_settings.APP_ID,
102
+ minutes=10,
103
+ )
104
+ except Exception as e:
105
+ logger.warning(f"Failed to push OTP to Nova (non-critical): {e}")
106
+
107
+ return {
108
+ "status": "pending_verification",
109
+ "message": "تم إنشاء الحساب! فعّل حسابك عبر تليجرام بوت @robovainova_bot ← /verify",
110
+ "user": res,
111
+ }
112
+
113
+
114
+ # ═══════════════════════════════════════════════════════════════
115
+ # 🔑 LOGIN
116
+ # ═══════════════════════════════════════════════════════════════
117
+
118
+
119
+ @auth_router.post("/login")
120
+ async def login(response: Response, form_data: OAuth2PasswordRequestForm = Depends()):
121
+ """Login and set session cookie."""
122
+ user = await auth_db.authenticate_user(form_data.username, form_data.password)
123
+ if not user:
124
+ raise HTTPException(
125
+ status_code=401,
126
+ detail="البريد الإلكتروني أو كلمة المرور غير صحيحة",
127
+ )
128
+
129
+ if not user.get("is_verified"):
130
+ raise HTTPException(
131
+ status_code=403,
132
+ detail="الحساب غير مُفعّل. افتح بوت @robovainova_bot في تليجرام وأرسل /verify",
133
+ )
134
+
135
+ access_token = create_access_token(data={"sub": user["email"]})
136
+ expires_at = (datetime.now() + timedelta(days=1)).isoformat()
137
+ await auth_db.create_session(user["id"], access_token, expires_at)
138
+
139
+ _is_prod = os.getenv("RENDER") or os.getenv("ENVIRONMENT") == "production"
140
+ response.set_cookie(
141
+ key="access_token",
142
+ value=f"Bearer {access_token}",
143
+ httponly=True,
144
+ secure=bool(_is_prod),
145
+ max_age=86400,
146
+ samesite="lax",
147
+ )
148
+ return {"access_token": access_token, "token_type": "bearer"}
149
+
150
+
151
+ # ═══════════════════════════════════════════════════════════════
152
+ # 🚪 LOGOUT
153
+ # ═══════════════════════════════════════════════════════════════
154
+
155
+
156
+ @auth_router.post("/logout")
157
+ async def logout(response: Response, request: Request):
158
+ token = request.cookies.get("access_token")
159
+ if token:
160
+ if token.startswith("Bearer "):
161
+ token = token.split(" ")[1]
162
+ await auth_db.delete_session(token)
163
+ response.delete_cookie("access_token")
164
+ return {"status": "success"}
165
+
166
+
167
+ # ═══════════════════════════════════════════════════════════════
168
+ # 👤 ME
169
+ # ═══════════════════════════════════════════════════════════════
170
+
171
+
172
+ @auth_router.get("/me")
173
+ async def read_users_me(current_user: dict = Depends(get_current_user)):
174
+ return {
175
+ "id": current_user["id"],
176
+ "email": current_user["email"],
177
+ "full_name": current_user.get("full_name", ""),
178
+ "role": current_user.get("role", "user"),
179
+ "balance": current_user.get("balance", 0),
180
+ }
181
+
182
+
183
+ # ═══════════════════════════════════════════════════════════════
184
+ # 📲 OTP ENDPOINTS
185
+ # ═══════════════════════════════════════════════════════════════
186
+
187
+
188
+ @auth_router.post("/request-otp")
189
+ async def request_telegram_otp(req: OTPRequest):
190
+ """Generate OTP for an unverified user. They then use /verify in the Telegram bot."""
191
+ email = req.email.strip().lower()
192
+ user = await auth_db.get_user_by_email_unverified(email)
193
+ if not user:
194
+ raise HTTPException(
195
+ status_code=404, detail="لم يتم العثور على حساب بهذا البريد"
196
+ )
197
+
198
+ if user.get("is_verified"):
199
+ return {"status": "already_verified", "message": "الحساب مفعّل بالفعل ✅"}
200
+
201
+ otp = str(random.randint(100000, 999999))
202
+ await auth_db.store_otp(user["id"], otp, "telegram_verify", minutes=10)
203
+
204
+ # Push to centralized Nova bot
205
+ try:
206
+ from .nova_client import nova_client
207
+ from .config import auth_settings
208
+
209
+ if nova_client.is_configured:
210
+ await nova_client.push_otp(
211
+ email=email, code=otp, app_id=auth_settings.APP_ID, minutes=10
212
+ )
213
+ except Exception as e:
214
+ logger.warning(f"Failed to push OTP to Nova: {e}")
215
+
216
+ return {
217
+ "status": "success",
218
+ "message": "تم إنشاء كود التحقق. افتح بوت RobovAI في تليجرام وأرسل /verify",
219
+ }
220
+
221
+
222
+ @auth_router.post("/verify-otp")
223
+ async def verify_otp_endpoint(req: OTPVerify):
224
+ """Verify OTP and activate account."""
225
+ email = req.email.strip().lower()
226
+ user = await auth_db.get_user_by_email_unverified(email)
227
+ if not user:
228
+ raise HTTPException(status_code=404, detail="المستخدم غير موجود")
229
+
230
+ if user.get("is_verified"):
231
+ return {"status": "already_verified", "message": "الحساب مفعّل بالفعل ✅"}
232
+
233
+ valid = await auth_db.verify_otp(user["id"], req.code, "telegram_verify")
234
+ if not valid:
235
+ raise HTTPException(
236
+ status_code=400, detail="كود التحقق غير صحيح أو منتهي الصلاحية"
237
+ )
238
+
239
+ await auth_db.set_user_verified(user["id"])
240
+
241
+ # Auto-login
242
+ access_token = create_access_token(data={"sub": email})
243
+ expires_at = (datetime.now() + timedelta(days=1)).isoformat()
244
+ await auth_db.create_session(user["id"], access_token, expires_at)
245
+
246
+ return {
247
+ "status": "success",
248
+ "message": "تم تفعيل الحساب بنجاح! ✅",
249
+ "access_token": access_token,
250
+ "user": {
251
+ "id": user["id"],
252
+ "email": email,
253
+ "full_name": user.get("full_name", ""),
254
+ },
255
+ }
256
+
257
+
258
+ @auth_router.get("/check-verified")
259
+ async def check_verified(email: str):
260
+ """Check if a user's account is verified.
261
+
262
+ First checks local DB, then polls the centralized Nova bot
263
+ (if configured) and auto-verifies locally when confirmed.
264
+ """
265
+ email = email.strip().lower()
266
+ user = await auth_db.get_user_by_email_unverified(email)
267
+ if not user:
268
+ raise HTTPException(status_code=404, detail="المستخدم غير موجود")
269
+
270
+ if user.get("is_verified"):
271
+ return {"verified": True}
272
+
273
+ # Poll Nova centralized bot
274
+ try:
275
+ from .nova_client import nova_client
276
+
277
+ if nova_client.is_configured:
278
+ remote_verified = await nova_client.check_verified(email)
279
+ if remote_verified:
280
+ # Auto-verify locally
281
+ await auth_db.set_user_verified(user["id"])
282
+ return {"verified": True}
283
+ except Exception as e:
284
+ logger.warning(f"Nova check-verified poll error: {e}")
285
+
286
+ return {"verified": False}
287
+
288
+
289
+ # ═══════════════════════════════════════════════════════════════
290
+ # 🗑️ DELETE ACCOUNT
291
+ # ═══════════════════════════════════════════════════════════════
292
+
293
+
294
+ @auth_router.delete("/delete-account")
295
+ async def delete_account(
296
+ response: Response, current_user: dict = Depends(get_current_user)
297
+ ):
298
+ """Permanently delete the current user's account."""
299
+ await auth_db.delete_user_account(current_user["id"])
300
+ response.delete_cookie("access_token")
301
+ return {"status": "success", "message": "تم حذف الحساب نهائياً"}
auth_module/config.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ⚙️ Auth Module — Configuration
3
+ """
4
+
5
+ import os
6
+ from pydantic_settings import BaseSettings
7
+ from dotenv import load_dotenv
8
+
9
+ load_dotenv()
10
+
11
+
12
+ class AuthSettings(BaseSettings):
13
+ # JWT
14
+ JWT_SECRET_KEY: str = os.getenv("JWT_SECRET_KEY", "")
15
+ JWT_ALGORITHM: str = "HS256"
16
+ ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 # 1 day
17
+
18
+ # Database
19
+ DATABASE_PATH: str = os.getenv("DATABASE_PATH", "users.db")
20
+
21
+ # Telegram (only needed if running your own bot)
22
+ TELEGRAM_BOT_TOKEN: str = os.getenv("TELEGRAM_BOT_TOKEN", "")
23
+
24
+ # App
25
+ EXTERNAL_URL: str = os.getenv(
26
+ "EXTERNAL_URL", os.getenv("RENDER_EXTERNAL_URL", "https://robovai.com")
27
+ )
28
+
29
+ # Centralized Nova Bot (for verification via @robovainova_bot)
30
+ NOVA_API_URL: str = os.getenv("NOVA_API_URL", "") # e.g. https://robovai-nova.onrender.com
31
+ NOVA_API_KEY: str = os.getenv("NOVA_API_KEY", "") # Shared secret with Nova
32
+ APP_ID: str = os.getenv("APP_ID", "default") # Your app identifier
33
+
34
+ class Config:
35
+ env_file = ".env"
36
+ extra = "ignore"
37
+
38
+
39
+ auth_settings = AuthSettings()
auth_module/database.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 🗄️ Auth Module — Database Layer (SQLite)
3
+ ═══════════════════════════════════════════
4
+ Standalone users/sessions/OTP database.
5
+ """
6
+
7
+ import sqlite3
8
+ import logging
9
+ from typing import Optional, Dict, Any, List
10
+ from datetime import datetime, timedelta
11
+
12
+ from .security import get_password_hash, verify_password_and_update
13
+ from .config import auth_settings
14
+
15
+ DB_PATH = auth_settings.DATABASE_PATH
16
+ logger = logging.getLogger("auth_module.database")
17
+
18
+
19
+ def _normalize_email(email: str) -> str:
20
+ return (email or "").strip().lower()
21
+
22
+
23
+ class AuthDatabase:
24
+ def __init__(self, db_path: str = None):
25
+ self.db_path = db_path or DB_PATH
26
+ self._init_db()
27
+
28
+ def _get_conn(self):
29
+ conn = sqlite3.connect(self.db_path)
30
+ conn.execute("PRAGMA journal_mode=WAL")
31
+ conn.execute("PRAGMA foreign_keys=ON")
32
+ return conn
33
+
34
+ def _init_db(self):
35
+ """Initialize SQLite database with users, sessions, OTP tables."""
36
+ with self._get_conn() as conn:
37
+ c = conn.cursor()
38
+
39
+ # Users Table
40
+ c.execute(
41
+ """
42
+ CREATE TABLE IF NOT EXISTS users (
43
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
44
+ email TEXT UNIQUE NOT NULL,
45
+ full_name TEXT,
46
+ password_hash TEXT NOT NULL,
47
+ phone TEXT,
48
+ role TEXT DEFAULT 'user',
49
+ balance INTEGER DEFAULT 100,
50
+ daily_used INTEGER DEFAULT 0,
51
+ daily_reset_date TEXT,
52
+ subscription_tier TEXT DEFAULT 'free',
53
+ subscription_expires TEXT,
54
+ is_verified INTEGER DEFAULT 0,
55
+ telegram_chat_id TEXT,
56
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
57
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
58
+ )
59
+ """
60
+ )
61
+
62
+ # Safe migrations for existing DBs
63
+ for col, defn in [
64
+ ("role", "TEXT DEFAULT 'user'"),
65
+ ("daily_used", "INTEGER DEFAULT 0"),
66
+ ("daily_reset_date", "TEXT"),
67
+ ("subscription_tier", "TEXT DEFAULT 'free'"),
68
+ ("subscription_expires", "TEXT"),
69
+ ("updated_at", "TIMESTAMP"),
70
+ ("is_verified", "INTEGER DEFAULT 0"),
71
+ ("telegram_chat_id", "TEXT"),
72
+ ("phone", "TEXT"),
73
+ ]:
74
+ try:
75
+ c.execute(f"ALTER TABLE users ADD COLUMN {col} {defn}")
76
+ except sqlite3.OperationalError:
77
+ pass
78
+
79
+ # Sessions Table
80
+ c.execute(
81
+ """
82
+ CREATE TABLE IF NOT EXISTS sessions (
83
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
84
+ user_id INTEGER,
85
+ token TEXT UNIQUE,
86
+ expires_at TIMESTAMP,
87
+ FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
88
+ )
89
+ """
90
+ )
91
+
92
+ # OTP Codes Table
93
+ c.execute(
94
+ """
95
+ CREATE TABLE IF NOT EXISTS otp_codes (
96
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
97
+ user_id TEXT,
98
+ code TEXT,
99
+ purpose TEXT,
100
+ expires_at TIMESTAMP,
101
+ used INTEGER DEFAULT 0,
102
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
103
+ )
104
+ """
105
+ )
106
+
107
+ # Indexes
108
+ for idx in [
109
+ "CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)",
110
+ "CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token)",
111
+ "CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id)",
112
+ "CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at)",
113
+ "CREATE INDEX IF NOT EXISTS idx_otp_user_purpose ON otp_codes(user_id, purpose, expires_at)",
114
+ ]:
115
+ c.execute(idx)
116
+
117
+ conn.commit()
118
+ logger.info("✅ Auth database initialized")
119
+
120
+ # ═══════════════════════════════════════════════════════════════
121
+ # 👤 USER CRUD
122
+ # ═══════════════════════════════════════════════════════════════
123
+
124
+ async def create_user(
125
+ self,
126
+ email: str,
127
+ password: str,
128
+ full_name: str,
129
+ phone: str = None,
130
+ role: str = "user",
131
+ ) -> Optional[Dict[str, Any]]:
132
+ try:
133
+ email = _normalize_email(email)
134
+ password_hash = get_password_hash(password)
135
+ today = datetime.now().strftime("%Y-%m-%d")
136
+ with self._get_conn() as conn:
137
+ c = conn.cursor()
138
+ c.execute(
139
+ """INSERT INTO users (email, password_hash, full_name, phone, role, balance, daily_used, daily_reset_date)
140
+ VALUES (?, ?, ?, ?, ?, 100, 0, ?)""",
141
+ (email, password_hash, full_name, phone, role, today),
142
+ )
143
+ conn.commit()
144
+ return {
145
+ "id": c.lastrowid,
146
+ "email": email,
147
+ "full_name": full_name,
148
+ "role": role,
149
+ "balance": 100,
150
+ }
151
+ except sqlite3.IntegrityError:
152
+ return None
153
+ except Exception as e:
154
+ logger.exception(f"create_user error: {e}")
155
+ raise
156
+
157
+ async def authenticate_user(
158
+ self, email: str, password: str
159
+ ) -> Optional[Dict[str, Any]]:
160
+ with self._get_conn() as conn:
161
+ conn.row_factory = sqlite3.Row
162
+ c = conn.cursor()
163
+ c.execute(
164
+ "SELECT * FROM users WHERE lower(email) = lower(?)",
165
+ (_normalize_email(email),),
166
+ )
167
+ user = c.fetchone()
168
+ if not user:
169
+ return None
170
+
171
+ ok, new_hash = verify_password_and_update(password, user["password_hash"])
172
+ if not ok:
173
+ return None
174
+
175
+ if new_hash:
176
+ try:
177
+ c.execute(
178
+ "UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
179
+ (new_hash, user["id"]),
180
+ )
181
+ conn.commit()
182
+ except Exception:
183
+ pass
184
+
185
+ return dict(user)
186
+ return None
187
+
188
+ async def get_user_by_email(self, email: str) -> Optional[Dict[str, Any]]:
189
+ with self._get_conn() as conn:
190
+ conn.row_factory = sqlite3.Row
191
+ c = conn.cursor()
192
+ c.execute(
193
+ "SELECT id, email, full_name, role, balance, daily_used, subscription_tier "
194
+ "FROM users WHERE lower(email) = lower(?)",
195
+ (_normalize_email(email),),
196
+ )
197
+ user = c.fetchone()
198
+ return dict(user) if user else None
199
+
200
+ async def get_user_by_id(self, user_id: int) -> Optional[Dict[str, Any]]:
201
+ with self._get_conn() as conn:
202
+ conn.row_factory = sqlite3.Row
203
+ c = conn.cursor()
204
+ c.execute(
205
+ "SELECT id, email, full_name, role, balance, daily_used, subscription_tier "
206
+ "FROM users WHERE id = ?",
207
+ (user_id,),
208
+ )
209
+ user = c.fetchone()
210
+ return dict(user) if user else None
211
+
212
+ async def get_user_by_email_unverified(
213
+ self, email: str
214
+ ) -> Optional[Dict[str, Any]]:
215
+ with self._get_conn() as conn:
216
+ conn.row_factory = sqlite3.Row
217
+ c = conn.cursor()
218
+ c.execute(
219
+ "SELECT id, email, full_name, is_verified FROM users WHERE lower(email) = lower(?)",
220
+ (_normalize_email(email),),
221
+ )
222
+ user = c.fetchone()
223
+ return dict(user) if user else None
224
+
225
+ async def get_user_by_telegram_or_phone(
226
+ self, telegram_chat_id: str, phone: str
227
+ ) -> Optional[Dict[str, Any]]:
228
+ """Find user by Telegram chat ID or phone number."""
229
+ with self._get_conn() as conn:
230
+ conn.row_factory = sqlite3.Row
231
+ c = conn.cursor()
232
+
233
+ c.execute(
234
+ "SELECT id, email, full_name, is_verified FROM users WHERE telegram_chat_id = ?",
235
+ (telegram_chat_id,),
236
+ )
237
+ user = c.fetchone()
238
+ if user:
239
+ return dict(user)
240
+
241
+ # Try phone
242
+ phone_clean = phone.lstrip("+")
243
+ c.execute(
244
+ "SELECT id, email, full_name, is_verified FROM users "
245
+ "WHERE phone = ? OR phone = ? OR phone = ?",
246
+ (phone, "+" + phone_clean, phone_clean),
247
+ )
248
+ user = c.fetchone()
249
+ return dict(user) if user else None
250
+
251
+ async def delete_user_account(self, user_id: int) -> bool:
252
+ with self._get_conn() as conn:
253
+ c = conn.cursor()
254
+ uid = str(user_id)
255
+ c.execute("DELETE FROM sessions WHERE user_id = ?", (user_id,))
256
+ c.execute("DELETE FROM otp_codes WHERE user_id = ?", (uid,))
257
+ c.execute("DELETE FROM users WHERE id = ?", (user_id,))
258
+ conn.commit()
259
+ return c.rowcount > 0
260
+
261
+ # ═══════════════════════════════════════════════════════════════
262
+ # 🔑 SESSION MANAGEMENT
263
+ # ═════════���═════════════════════════════════════════════════════
264
+
265
+ async def create_session(self, user_id: int, token: str, expires_at: str):
266
+ with self._get_conn() as conn:
267
+ c = conn.cursor()
268
+ c.execute(
269
+ "INSERT INTO sessions (user_id, token, expires_at) VALUES (?, ?, ?)",
270
+ (user_id, token, expires_at),
271
+ )
272
+ conn.commit()
273
+
274
+ async def get_session(self, token: str) -> Optional[Dict[str, Any]]:
275
+ with self._get_conn() as conn:
276
+ conn.row_factory = sqlite3.Row
277
+ c = conn.cursor()
278
+ c.execute("SELECT * FROM sessions WHERE token = ?", (token,))
279
+ row = c.fetchone()
280
+ return dict(row) if row else None
281
+
282
+ async def delete_session(self, token: str):
283
+ with self._get_conn() as conn:
284
+ c = conn.cursor()
285
+ c.execute("DELETE FROM sessions WHERE token = ?", (token,))
286
+ conn.commit()
287
+
288
+ async def cleanup_expired_sessions(self):
289
+ with self._get_conn() as conn:
290
+ c = conn.cursor()
291
+ c.execute(
292
+ "DELETE FROM sessions WHERE expires_at < ?",
293
+ (datetime.now().isoformat(),),
294
+ )
295
+ conn.commit()
296
+
297
+ # ═══════════════════════════════════════════════════════════════
298
+ # 📲 OTP / VERIFICATION
299
+ # ═══════════════════════════════════════════════════════════════
300
+
301
+ async def set_user_verified(
302
+ self, user_id: int, telegram_chat_id: str = None
303
+ ) -> bool:
304
+ with self._get_conn() as conn:
305
+ c = conn.cursor()
306
+ if telegram_chat_id:
307
+ c.execute(
308
+ "UPDATE users SET is_verified = 1, telegram_chat_id = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
309
+ (telegram_chat_id, user_id),
310
+ )
311
+ else:
312
+ c.execute(
313
+ "UPDATE users SET is_verified = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
314
+ (user_id,),
315
+ )
316
+ conn.commit()
317
+ return c.rowcount > 0
318
+
319
+ async def store_otp(
320
+ self,
321
+ user_id: int,
322
+ code: str,
323
+ purpose: str = "telegram_verify",
324
+ minutes: int = 10,
325
+ ):
326
+ expires_at = (datetime.now() + timedelta(minutes=minutes)).isoformat()
327
+ with self._get_conn() as conn:
328
+ c = conn.cursor()
329
+ c.execute(
330
+ "UPDATE otp_codes SET used = 1 WHERE user_id = ? AND purpose = ? AND used = 0",
331
+ (str(user_id), purpose),
332
+ )
333
+ c.execute(
334
+ "INSERT INTO otp_codes (user_id, code, purpose, expires_at) VALUES (?, ?, ?, ?)",
335
+ (str(user_id), code, purpose, expires_at),
336
+ )
337
+ conn.commit()
338
+
339
+ async def verify_otp(
340
+ self, user_id: int, code: str, purpose: str = "telegram_verify"
341
+ ) -> bool:
342
+ now = datetime.now().isoformat()
343
+ with self._get_conn() as conn:
344
+ conn.row_factory = sqlite3.Row
345
+ c = conn.cursor()
346
+ c.execute(
347
+ "SELECT id FROM otp_codes WHERE user_id = ? AND code = ? AND purpose = ? "
348
+ "AND used = 0 AND expires_at > ? ORDER BY id DESC LIMIT 1",
349
+ (str(user_id), code, purpose, now),
350
+ )
351
+ row = c.fetchone()
352
+ if not row:
353
+ return False
354
+ c.execute("UPDATE otp_codes SET used = 1 WHERE id = ?", (row["id"],))
355
+ conn.commit()
356
+ return True
357
+
358
+ async def cleanup_expired_otps(self):
359
+ with self._get_conn() as conn:
360
+ c = conn.cursor()
361
+ c.execute(
362
+ "DELETE FROM otp_codes WHERE used = 1 OR expires_at < ?",
363
+ (datetime.now().isoformat(),),
364
+ )
365
+ deleted = c.rowcount
366
+ conn.commit()
367
+ return deleted
368
+
369
+
370
+ # Singleton
371
+ auth_db = AuthDatabase()
auth_module/models.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 📦 Auth Module — Pydantic Models
3
+ """
4
+
5
+ from pydantic import BaseModel
6
+ from typing import Optional
7
+
8
+
9
+ class UserCreate(BaseModel):
10
+ email: str
11
+ password: str
12
+ full_name: str
13
+ phone: Optional[str] = None
14
+
15
+
16
+ class OTPRequest(BaseModel):
17
+ email: str
18
+
19
+
20
+ class OTPVerify(BaseModel):
21
+ email: str
22
+ code: str
23
+
24
+
25
+ class PasswordChange(BaseModel):
26
+ old_password: str
27
+ new_password: str
auth_module/nova_client.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 🌐 Auth Module — Nova API Client (Centralized Bot Bridge)
3
+ ═══════════════════════════════════════════════════════════
4
+ Sends OTP to the central RobovAI Nova server so the Telegram bot
5
+ (@robovainova_bot) can deliver it to the user.
6
+
7
+ Usage:
8
+ from auth_module.nova_client import nova_client
9
+ await nova_client.push_otp("user@example.com", "123456")
10
+ verified = await nova_client.check_verified("user@example.com")
11
+ """
12
+
13
+ import logging
14
+ from typing import Optional, Dict, Any
15
+
16
+ try:
17
+ import httpx
18
+ except ImportError:
19
+ httpx = None # Will raise clear error on first use
20
+
21
+ from .config import auth_settings
22
+
23
+ logger = logging.getLogger("auth_module.nova_client")
24
+
25
+
26
+ class NovaClient:
27
+ """HTTP client for communicating with the central RobovAI Nova API."""
28
+
29
+ def __init__(self):
30
+ self.base_url = (auth_settings.NOVA_API_URL or "").rstrip("/")
31
+ self.api_key = auth_settings.NOVA_API_KEY or ""
32
+
33
+ @property
34
+ def is_configured(self) -> bool:
35
+ return bool(self.base_url and self.api_key)
36
+
37
+ def _headers(self) -> dict:
38
+ return {
39
+ "X-API-Key": self.api_key,
40
+ "Content-Type": "application/json",
41
+ }
42
+
43
+ async def push_otp(
44
+ self,
45
+ email: str,
46
+ code: str,
47
+ app_id: str = "default",
48
+ minutes: int = 10,
49
+ ) -> Dict[str, Any]:
50
+ """Push OTP to Nova so the centralized Telegram bot can deliver it.
51
+
52
+ Args:
53
+ email: User email (must match what user enters in the bot)
54
+ code: The 6-digit OTP code (generated locally)
55
+ app_id: Identifier for your app (for Nova logging)
56
+ minutes: OTP validity in minutes
57
+
58
+ Returns:
59
+ {"status": "success", "bot": "@robovainova_bot"} on success
60
+ {"status": "error", "detail": "..."} on failure
61
+ """
62
+ if not self.is_configured:
63
+ logger.warning("Nova API not configured — OTP will only work locally")
64
+ return {"status": "skipped", "detail": "NOVA_API_URL not configured"}
65
+
66
+ if httpx is None:
67
+ logger.error("httpx not installed — pip install httpx")
68
+ return {"status": "error", "detail": "httpx package required"}
69
+
70
+ url = f"{self.base_url}/api/external/push-otp"
71
+ payload = {
72
+ "email": email.strip().lower(),
73
+ "code": code,
74
+ "app_id": app_id,
75
+ "minutes": minutes,
76
+ }
77
+
78
+ try:
79
+ async with httpx.AsyncClient(timeout=15) as client:
80
+ resp = await client.post(url, json=payload, headers=self._headers())
81
+
82
+ if resp.status_code == 200:
83
+ data = resp.json()
84
+ logger.info(f"✅ OTP pushed to Nova for {email}")
85
+ return data
86
+ else:
87
+ detail = resp.text[:200]
88
+ logger.error(
89
+ f"❌ Nova push-otp failed [{resp.status_code}]: {detail}"
90
+ )
91
+ return {"status": "error", "detail": detail}
92
+
93
+ except httpx.ConnectError:
94
+ logger.error(f"❌ Cannot reach Nova at {self.base_url}")
95
+ return {"status": "error", "detail": "Cannot connect to Nova server"}
96
+ except Exception as e:
97
+ logger.error(f"❌ Nova push-otp exception: {e}")
98
+ return {"status": "error", "detail": str(e)}
99
+
100
+ async def check_verified(self, email: str) -> bool:
101
+ """Check if the user verified via the centralized Telegram bot.
102
+
103
+ Returns True if the user successfully received and confirmed the OTP
104
+ through @robovainova_bot.
105
+ """
106
+ if not self.is_configured:
107
+ return False
108
+
109
+ if httpx is None:
110
+ return False
111
+
112
+ url = f"{self.base_url}/api/external/check-verified"
113
+ params = {"email": email.strip().lower()}
114
+
115
+ try:
116
+ async with httpx.AsyncClient(timeout=10) as client:
117
+ resp = await client.get(
118
+ url, params=params, headers=self._headers()
119
+ )
120
+
121
+ if resp.status_code == 200:
122
+ data = resp.json()
123
+ return data.get("verified", False)
124
+ else:
125
+ logger.warning(f"Nova check-verified [{resp.status_code}]")
126
+ return False
127
+
128
+ except Exception as e:
129
+ logger.error(f"Nova check-verified error: {e}")
130
+ return False
131
+
132
+
133
+ # Singleton
134
+ nova_client = NovaClient()
auth_module/security.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 🔑 Auth Module — Security (JWT + Password Hashing)
3
+ ═══════════════════════════════════════════════════
4
+ Standalone version — no external dependencies except pyjwt + passlib.
5
+ """
6
+
7
+ from datetime import datetime, timedelta
8
+ from typing import Optional, Dict, Any
9
+ import jwt
10
+ from passlib.context import CryptContext
11
+ import os
12
+ import secrets
13
+ import re
14
+
15
+ from .config import auth_settings
16
+
17
+ # ─── JWT Secret ────────────────────────────────────────────────
18
+ _SECRET_FILE = os.path.join(os.path.dirname(__file__), ".jwt_secret")
19
+
20
+
21
+ def _load_or_create_secret() -> str:
22
+ """Load JWT secret from env or file. Creates one if missing."""
23
+ env = auth_settings.JWT_SECRET_KEY
24
+ if env and len(env) >= 32:
25
+ return env
26
+
27
+ # Production guard
28
+ is_production = (
29
+ os.getenv("RENDER") or os.getenv("ENVIRONMENT", "").lower() == "production"
30
+ )
31
+ if is_production:
32
+ import sys
33
+
34
+ print(
35
+ "❌ CRITICAL: JWT_SECRET_KEY not set (min 32 chars). "
36
+ "Sessions will break on redeploy!",
37
+ file=sys.stderr,
38
+ )
39
+ return secrets.token_urlsafe(64)
40
+
41
+ # Dev fallback — persist to file
42
+ if os.path.exists(_SECRET_FILE):
43
+ with open(_SECRET_FILE, "r") as f:
44
+ stored = f.read().strip()
45
+ if len(stored) >= 32:
46
+ return stored
47
+
48
+ new_secret = secrets.token_urlsafe(64)
49
+ try:
50
+ with open(_SECRET_FILE, "w") as f:
51
+ f.write(new_secret)
52
+ except Exception:
53
+ pass
54
+ return new_secret
55
+
56
+
57
+ SECRET_KEY = _load_or_create_secret()
58
+ ALGORITHM = auth_settings.JWT_ALGORITHM
59
+ ACCESS_TOKEN_EXPIRE_MINUTES = auth_settings.ACCESS_TOKEN_EXPIRE_MINUTES
60
+
61
+ # ─── Password Hashing ─────────────────────────────────────────
62
+ pwd_context = CryptContext(schemes=["pbkdf2_sha256", "bcrypt"], deprecated="auto")
63
+
64
+
65
+ def verify_password(plain_password: str, hashed_password: str) -> bool:
66
+ return pwd_context.verify(plain_password, hashed_password)
67
+
68
+
69
+ def verify_password_and_update(
70
+ plain_password: str, hashed_password: str
71
+ ) -> tuple[bool, str | None]:
72
+ """Verify password and optionally return an upgraded hash."""
73
+ try:
74
+ ok, new_hash = pwd_context.verify_and_update(plain_password, hashed_password)
75
+ return bool(ok), new_hash
76
+ except Exception:
77
+ return False, None
78
+
79
+
80
+ def get_password_hash(password: str) -> str:
81
+ return pwd_context.hash(password)
82
+
83
+
84
+ def validate_password_strength(password: str) -> tuple[bool, str]:
85
+ """Check password meets minimum requirements:
86
+ 8+ chars, at least 1 letter, 1 digit, 1 special character."""
87
+ if len(password) < 8:
88
+ return False, "كلمة المرور يجب أن تكون 8 أحرف على الأقل"
89
+ if not re.search(r"[A-Za-z]", password):
90
+ return False, "كلمة المرور يجب أن تحتوي على حرف واحد على الأقل"
91
+ if not re.search(r"[0-9]", password):
92
+ return False, "كلمة المرور يجب أن تحتوي على رقم واحد على الأقل"
93
+ if not re.search(r'[!@#$%^&*()_+\-=\[\]{};\':",./<>?]', password):
94
+ return False, "كلمة المرور يجب أن تحتوي على رمز خاص واحد على الأقل (!@#$%...)"
95
+ return True, ""
96
+
97
+
98
+ # ─── JWT Tokens ────────────────────────────────────────────────
99
+ def create_access_token(
100
+ data: Dict[str, Any], expires_delta: Optional[timedelta] = None
101
+ ) -> str:
102
+ to_encode = data.copy()
103
+ expire = datetime.utcnow() + (
104
+ expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
105
+ )
106
+ to_encode.update({"exp": expire})
107
+ return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
108
+
109
+
110
+ def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
111
+ try:
112
+ return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
113
+ except jwt.PyJWTError:
114
+ return None
auth_module/telegram_verify.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 📱 Auth Module — Telegram Verification Bot
3
+ ═══════════════════════════════════════════
4
+ Inline-button driven verification flow with email + phone support.
5
+
6
+ Usage:
7
+ from auth_module.telegram_verify import create_verify_telegram_app
8
+ telegram_app = create_verify_telegram_app()
9
+ """
10
+
11
+ import os
12
+ import re
13
+ import random
14
+ import logging
15
+
16
+ from telegram import (
17
+ Update,
18
+ ReplyKeyboardMarkup,
19
+ KeyboardButton,
20
+ InlineKeyboardButton,
21
+ InlineKeyboardMarkup,
22
+ )
23
+ from telegram.ext import (
24
+ Application,
25
+ CommandHandler,
26
+ MessageHandler,
27
+ CallbackQueryHandler,
28
+ filters,
29
+ ContextTypes,
30
+ )
31
+
32
+ from .config import auth_settings
33
+
34
+ logger = logging.getLogger("auth_module.telegram")
35
+
36
+ # ═══════════════════════════════════════════════════════════════
37
+ # 📊 STATE
38
+ # ═══════════════════════════════════════════════════════════════
39
+
40
+ VERIFY_STATE: dict = {}
41
+ # chat_id -> {"step": ..., "method": "email"|"phone", "email": ..., "user_id": ..., "otp": ...}
42
+
43
+
44
+ # ═══════════════════════════════════════════════════════════════
45
+ # ⌨️ KEYBOARDS
46
+ # ═══════════════════════════════════════════════════════════════
47
+
48
+
49
+ def _main_keyboard():
50
+ return ReplyKeyboardMarkup(
51
+ [[KeyboardButton("🔐 تفعيل الحساب"), KeyboardButton("ℹ️ مساعدة")]],
52
+ resize_keyboard=True,
53
+ is_persistent=True,
54
+ )
55
+
56
+
57
+ def _verify_method_keyboard():
58
+ return InlineKeyboardMarkup(
59
+ [
60
+ [InlineKeyboardButton("📧 بالإيميل", callback_data="verify_email")],
61
+ [InlineKeyboardButton("📱 برقم الهاتف", callback_data="verify_phone")],
62
+ [InlineKeyboardButton("❌ إلغاء", callback_data="verify_cancel")],
63
+ ]
64
+ )
65
+
66
+
67
+ def _cancel_keyboard():
68
+ return InlineKeyboardMarkup(
69
+ [
70
+ [InlineKeyboardButton("❌ إلغاء التفعيل", callback_data="verify_cancel")],
71
+ ]
72
+ )
73
+
74
+
75
+ def _confirm_otp_keyboard(otp: str):
76
+ return InlineKeyboardMarkup(
77
+ [
78
+ [
79
+ InlineKeyboardButton(
80
+ f"📋 نسخ الكود: {otp}", callback_data=f"copy_otp_{otp}"
81
+ )
82
+ ],
83
+ [
84
+ InlineKeyboardButton(
85
+ f"✅ تأكيد الكود ({otp})", callback_data=f"confirm_otp_{otp}"
86
+ )
87
+ ],
88
+ [InlineKeyboardButton("🔄 كود جديد", callback_data="resend_otp")],
89
+ [InlineKeyboardButton("❌ إلغاء", callback_data="verify_cancel")],
90
+ ]
91
+ )
92
+
93
+
94
+ def _phone_share_keyboard():
95
+ return ReplyKeyboardMarkup(
96
+ [[KeyboardButton("📱 مشاركة رقم الهاتف", request_contact=True)]],
97
+ resize_keyboard=True,
98
+ one_time_keyboard=True,
99
+ )
100
+
101
+
102
+ # ═══════════════════════════════════════════════════════════════
103
+ # 🛡️ SAFE REPLY
104
+ # ═══════════════════════════════════════════════════════════════
105
+
106
+
107
+ async def safe_reply(update: Update, text: str, reply_markup=None, parse_mode="HTML"):
108
+ try:
109
+ await update.message.reply_text(
110
+ text, reply_markup=reply_markup, parse_mode=parse_mode
111
+ )
112
+ except Exception as e:
113
+ logger.warning(f"HTML reply failed: {e}")
114
+ try:
115
+ await update.message.reply_text(text, reply_markup=reply_markup)
116
+ except Exception as e2:
117
+ logger.error(f"Reply failed: {e2}")
118
+
119
+
120
+ # ═══════════════════════════════════════════════════════════════
121
+ # 🎯 COMMANDS
122
+ # ═══════════════════════════════════════════════════════════════
123
+
124
+
125
+ async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
126
+ user_name = update.effective_user.first_name or "مستخدم"
127
+ msg = f"""✨ <b>مرحباً {user_name}!</b>
128
+
129
+ 🔐 هذا بوت التفعيل لـ <b>RobovAI Nova</b>.
130
+
131
+ اضغط الزر لتفعيل حسابك 👇"""
132
+
133
+ inline_kb = InlineKeyboardMarkup(
134
+ [
135
+ [
136
+ InlineKeyboardButton("🔐 تفعيل بالإيميل", callback_data="verify_email"),
137
+ InlineKeyboardButton("📱 تفعيل بالهاتف", callback_data="verify_phone"),
138
+ ],
139
+ ]
140
+ )
141
+ await safe_reply(update, msg, reply_markup=_main_keyboard())
142
+ await update.message.reply_text(
143
+ "⚡ اختر طريقة التفعيل:", parse_mode="HTML", reply_markup=inline_kb
144
+ )
145
+
146
+
147
+ async def verify_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
148
+ msg = """🔐 <b>تفعيل الحساب</b>
149
+
150
+ اختر طريقة التفعيل:
151
+
152
+ 📧 <b>بالإيميل</b> — أدخل بريدك واحصل على كود
153
+ 📱 <b>برقم الهاتف</b> — شارك رقمك
154
+
155
+ اضغط الزر المناسب 👇"""
156
+ await safe_reply(update, msg, reply_markup=_verify_method_keyboard())
157
+
158
+
159
+ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
160
+ msg = """📖 <b>كيفية التفعيل</b>
161
+
162
+ 1️⃣ سجّل حسابك من الموقع
163
+ 2️⃣ اضغط <b>🔐 تفعيل الحساب</b>
164
+ 3️⃣ اختر الطريقة (إيميل أو هاتف)
165
+ 4️⃣ ستحصل على كود — اضغط <b>تأكيد</b>
166
+ 5️⃣ تم! سجّل دخولك من الموقع ✅"""
167
+ await safe_reply(update, msg, reply_markup=_main_keyboard())
168
+
169
+
170
+ # ═══════════════════════════════════════════════════════════════
171
+ # 🔘 CALLBACK QUERY HANDLER
172
+ # ═══════════════════════════════════════════════════════════════
173
+
174
+
175
+ async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
176
+ query = update.callback_query
177
+ await query.answer()
178
+ chat_id = str(query.message.chat_id)
179
+ data = query.data
180
+
181
+ if data == "verify_email":
182
+ VERIFY_STATE[chat_id] = {"step": "awaiting_email", "method": "email"}
183
+ await query.message.reply_text(
184
+ "📧 <b>أدخل بريدك الإلكتروني:</b>\n\n<i>مثال: user@example.com</i>",
185
+ parse_mode="HTML",
186
+ reply_markup=_cancel_keyboard(),
187
+ )
188
+
189
+ elif data == "verify_phone":
190
+ VERIFY_STATE[chat_id] = {"step": "awaiting_phone", "method": "phone"}
191
+ await query.message.reply_text(
192
+ "📱 اضغط الزر لمشاركة رقمك 👇\n\n<i>أو اكتب بريدك الإلكتروني</i>",
193
+ parse_mode="HTML",
194
+ reply_markup=_phone_share_keyboard(),
195
+ )
196
+
197
+ elif data == "verify_cancel":
198
+ VERIFY_STATE.pop(chat_id, None)
199
+ await query.message.reply_text("❌ تم الإلغاء.", reply_markup=_main_keyboard())
200
+
201
+ elif data.startswith("confirm_otp_"):
202
+ otp_code = data.replace("confirm_otp_", "")
203
+ state = VERIFY_STATE.get(chat_id)
204
+ if (
205
+ state
206
+ and state.get("step") == "awaiting_otp"
207
+ and state.get("otp") == otp_code
208
+ ):
209
+ await _do_verify(query.message, chat_id, state, otp_code)
210
+ else:
211
+ await query.message.reply_text(
212
+ "⚠️ انتهت الجلسة. أعد المحاولة بـ /verify", reply_markup=_main_keyboard()
213
+ )
214
+
215
+ elif data.startswith("copy_otp_"):
216
+ otp_code = data.replace("copy_otp_", "")
217
+ await query.message.reply_text(
218
+ f"🔑 <b>الكود:</b> <code>{otp_code}</code>\n📋 اضغط لنسخه",
219
+ parse_mode="HTML",
220
+ )
221
+
222
+ elif data == "resend_otp":
223
+ state = VERIFY_STATE.get(chat_id)
224
+ if state and state.get("user_id"):
225
+ await _send_otp(query.message, chat_id, state)
226
+ else:
227
+ await query.message.reply_text(
228
+ "⚠️ ابدأ من جديد بـ /verify", reply_markup=_main_keyboard()
229
+ )
230
+
231
+
232
+ # ═══════════════════════════════════════════════════════════════
233
+ # 📲 CONTACT (Phone share)
234
+ # ═══════════════════════════════════════════════════════════════
235
+
236
+
237
+ async def handle_contact(update: Update, context: ContextTypes.DEFAULT_TYPE):
238
+ chat_id = str(update.effective_chat.id)
239
+ state = VERIFY_STATE.get(chat_id)
240
+ if not state or state.get("method") != "phone":
241
+ return
242
+
243
+ contact = update.message.contact
244
+ phone = contact.phone_number if contact else None
245
+ if not phone:
246
+ await safe_reply(update, "⚠️ لم أتلق الرقم. حاول مرة أخرى.")
247
+ return
248
+
249
+ phone = re.sub(r"[\s\-()]", "", phone)
250
+ if not phone.startswith("+"):
251
+ phone = "+" + phone
252
+
253
+ try:
254
+ from .database import auth_db
255
+
256
+ user = await auth_db.get_user_by_telegram_or_phone(chat_id, phone)
257
+
258
+ if not user:
259
+ await safe_reply(
260
+ update,
261
+ f"❌ لم يتم العثور على حساب برقم <code>{phone}</code>\n\nجرّب بالإيميل 👇",
262
+ reply_markup=_verify_method_keyboard(),
263
+ )
264
+ VERIFY_STATE.pop(chat_id, None)
265
+ return
266
+
267
+ if user.get("is_verified"):
268
+ await safe_reply(
269
+ update, "✅ حسابك مُفعّل بالفعل!", reply_markup=_main_keyboard()
270
+ )
271
+ VERIFY_STATE.pop(chat_id, None)
272
+ return
273
+
274
+ state["user_id"] = user["id"]
275
+ state["email"] = user.get("email", "")
276
+ state["phone"] = phone
277
+ VERIFY_STATE[chat_id] = state
278
+ await _send_otp(update.message, chat_id, state)
279
+
280
+ except Exception as e:
281
+ logger.error(f"Phone verify error: {e}", exc_info=True)
282
+ await safe_reply(update, "❌ خطأ تقني. حاول مرة أخرى.")
283
+ VERIFY_STATE.pop(chat_id, None)
284
+
285
+
286
+ # ═══════════════════════════════════════════════════════════════
287
+ # 💬 TEXT MESSAGE HANDLER
288
+ # ═══════════════════════════════════════════════════════════════
289
+
290
+
291
+ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
292
+ chat_id = str(update.effective_chat.id)
293
+ state = VERIFY_STATE.get(chat_id)
294
+ message = (update.message.text or "").strip()
295
+
296
+ # Menu buttons
297
+ if message == "🔐 تفعيل الحساب":
298
+ await verify_command(update, context)
299
+ return
300
+ if message == "ℹ️ مساعدة":
301
+ await help_command(update, context)
302
+ return
303
+
304
+ if not state:
305
+ await safe_reply(
306
+ update, "اضغط 🔐 <b>تفعيل الحساب</b> للبدء", reply_markup=_main_keyboard()
307
+ )
308
+ return
309
+
310
+ # Cancel
311
+ if message in ("الغاء", "إلغاء", "/cancel", "cancel"):
312
+ VERIFY_STATE.pop(chat_id, None)
313
+ await safe_reply(update, "❌ تم الإلغاء.", reply_markup=_main_keyboard())
314
+ return
315
+
316
+ # Awaiting email
317
+ if state["step"] == "awaiting_email":
318
+ email = message.lower()
319
+ if "@" not in email or "." not in email:
320
+ await safe_reply(
321
+ update,
322
+ "⚠️ بريد غير صحيح. حاول مرة أخرى:",
323
+ reply_markup=_cancel_keyboard(),
324
+ )
325
+ return
326
+
327
+ try:
328
+ from .database import auth_db
329
+
330
+ user = await auth_db.get_user_by_email_unverified(email)
331
+
332
+ if not user:
333
+ await safe_reply(
334
+ update,
335
+ "❌ لا يوجد حساب بهذا البريد. سجّل من الموقع أولاً.",
336
+ reply_markup=_verify_method_keyboard(),
337
+ )
338
+ VERIFY_STATE.pop(chat_id, None)
339
+ return
340
+
341
+ if user.get("is_verified"):
342
+ await safe_reply(
343
+ update, "✅ حسابك مُفعّل بالفعل!", reply_markup=_main_keyboard()
344
+ )
345
+ VERIFY_STATE.pop(chat_id, None)
346
+ return
347
+
348
+ state["user_id"] = user["id"]
349
+ state["email"] = email
350
+ VERIFY_STATE[chat_id] = state
351
+ await _send_otp(update.message, chat_id, state)
352
+
353
+ except Exception as e:
354
+ logger.error(f"Email verify error: {e}", exc_info=True)
355
+ await safe_reply(update, "❌ خطأ تقني.")
356
+ VERIFY_STATE.pop(chat_id, None)
357
+ return
358
+
359
+ # Awaiting phone but got text
360
+ if state["step"] == "awaiting_phone":
361
+ email = message.lower()
362
+ if "@" in email and "." in email:
363
+ state["step"] = "awaiting_email"
364
+ state["method"] = "email"
365
+ VERIFY_STATE[chat_id] = state
366
+ await handle_message(update, context)
367
+ else:
368
+ await safe_reply(
369
+ update,
370
+ "📱 اضغط زر مشاركة الرقم أو اكتب بريدك.",
371
+ reply_markup=_phone_share_keyboard(),
372
+ )
373
+ return
374
+
375
+ # Awaiting OTP (manual entry)
376
+ if state["step"] == "awaiting_otp":
377
+ code = message.strip()
378
+ if not code.isdigit() or len(code) != 6:
379
+ await safe_reply(
380
+ update,
381
+ "⚠️ الكود 6 أرقام. حاول مرة أخرى:",
382
+ reply_markup=_cancel_keyboard(),
383
+ )
384
+ return
385
+ await _do_verify(update.message, chat_id, state, code)
386
+ return
387
+
388
+
389
+ # ═══════════════════════════════════════════��═══════════════════
390
+ # 🔧 HELPERS
391
+ # ═══════════════════════════════════════════════════════════════
392
+
393
+
394
+ async def _send_otp(message, chat_id: str, state: dict):
395
+ try:
396
+ from .database import auth_db
397
+
398
+ otp = str(random.randint(100000, 999999))
399
+ await auth_db.store_otp(state["user_id"], otp, "telegram_verify", minutes=10)
400
+
401
+ state["otp"] = otp
402
+ state["step"] = "awaiting_otp"
403
+ VERIFY_STATE[chat_id] = state
404
+
405
+ msg = f"""✅ <b>تم العثور على الحساب!</b>
406
+
407
+ 📧 {state.get('email', '')}
408
+
409
+ ━━━━━━━━━━━━━━━━━━━━
410
+
411
+ 🔑 <b>كود التحقق:</b> <code>{otp}</code>
412
+
413
+ ⏱️ صلاحية: <b>10 دقائق</b>
414
+
415
+ اضغط <b>✅ تأكيد</b> للتفعيل الفوري 👇"""
416
+
417
+ await message.reply_text(
418
+ msg, parse_mode="HTML", reply_markup=_confirm_otp_keyboard(otp)
419
+ )
420
+
421
+ except Exception as e:
422
+ logger.error(f"OTP error: {e}", exc_info=True)
423
+ await message.reply_text("❌ خطأ تقني.")
424
+ VERIFY_STATE.pop(chat_id, None)
425
+
426
+
427
+ async def _do_verify(message, chat_id: str, state: dict, code: str):
428
+ try:
429
+ from .database import auth_db
430
+
431
+ valid = await auth_db.verify_otp(state["user_id"], code, "telegram_verify")
432
+
433
+ if valid:
434
+ await auth_db.set_user_verified(state["user_id"], telegram_chat_id=chat_id)
435
+ VERIFY_STATE.pop(chat_id, None)
436
+ await message.reply_text(
437
+ "🎉 <b>تم تفعيل حسابك بنجاح!</b>\n\n✅ سجّل دخولك من الموقع الآن.",
438
+ parse_mode="HTML",
439
+ reply_markup=_main_keyboard(),
440
+ )
441
+ else:
442
+ VERIFY_STATE.pop(chat_id, None)
443
+ await message.reply_text(
444
+ "❌ كود غير صحيح أو منتهي. اضغط /verify للمحاولة مرة أخرى.",
445
+ reply_markup=_main_keyboard(),
446
+ )
447
+
448
+ except Exception as e:
449
+ logger.error(f"Verify error: {e}", exc_info=True)
450
+ await message.reply_text("❌ خطأ تقني.")
451
+ VERIFY_STATE.pop(chat_id, None)
452
+
453
+
454
+ # ═══════════════════════════════════════════════════════════════
455
+ # 🚀 APP FACTORY
456
+ # ═══════════════════════════════════════════════════════════════
457
+
458
+
459
+ def create_verify_telegram_app(token: str = None):
460
+ """Create a standalone Telegram bot app for account verification."""
461
+ token = token or auth_settings.TELEGRAM_BOT_TOKEN
462
+ if not token:
463
+ logger.error("TELEGRAM_BOT_TOKEN not set")
464
+ return None
465
+
466
+ app = Application.builder().token(token).build()
467
+
468
+ app.add_handler(CommandHandler("start", start_command))
469
+ app.add_handler(CommandHandler("verify", verify_command))
470
+ app.add_handler(CommandHandler("help", help_command))
471
+ app.add_handler(CallbackQueryHandler(handle_callback))
472
+ app.add_handler(MessageHandler(filters.CONTACT, handle_contact))
473
+ app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
474
+
475
+ logger.info("✅ Verification Telegram app created")
476
+ return app
main.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+
4
+ from auth_module.auth_routes import auth_router
5
+
6
+ app = FastAPI(title="Echo Tutor Auth API")
7
+
8
+ app.add_middleware(
9
+ CORSMiddleware,
10
+ allow_origins=["*"],
11
+ allow_credentials=True,
12
+ allow_methods=["*"],
13
+ allow_headers=["*"],
14
+ )
15
+
16
+ app.include_router(auth_router, prefix="/auth", tags=["Auth"])
17
+
18
+
19
+ @app.get("/")
20
+ def root():
21
+ return {"status": "ok", "service": "auth"}
requirements.txt CHANGED
@@ -4,4 +4,11 @@ requests
4
  flask_cors
5
  openai
6
  python-dotenv
7
- groq
 
 
 
 
 
 
 
 
4
  flask_cors
5
  openai
6
  python-dotenv
7
+ groq
8
+ pyjwt>=2.8.0
9
+ passlib[bcrypt]>=1.7.4
10
+ pydantic-settings>=2.0.0
11
+ fastapi
12
+ uvicorn
13
+ python-multipart
14
+ httpx
static/css/style.css CHANGED
@@ -2573,6 +2573,55 @@ body.no-waveform .waveform-canvas {
2573
  border-color: var(--accent);
2574
  }
2575
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2576
  /* ============================================
2577
  RESPONSIVE ADJUSTMENTS (Phase 3)
2578
  ============================================ */
 
2573
  border-color: var(--accent);
2574
  }
2575
 
2576
+ /* ============================================
2577
+ AUTH MODAL
2578
+ ============================================ */
2579
+ .auth-card {
2580
+ max-width: 460px;
2581
+ }
2582
+ .auth-tabs {
2583
+ display: flex;
2584
+ gap: 8px;
2585
+ margin-bottom: 14px;
2586
+ }
2587
+ .auth-tab {
2588
+ flex: 1;
2589
+ padding: 10px 12px;
2590
+ border-radius: var(--radius-sm);
2591
+ border: 1px solid var(--border-glass);
2592
+ background: var(--bg-glass);
2593
+ color: var(--text-secondary);
2594
+ cursor: pointer;
2595
+ font-family: var(--font-body);
2596
+ }
2597
+ .auth-tab.active {
2598
+ border-color: var(--accent);
2599
+ color: var(--accent-bright);
2600
+ background: var(--bg-glass-hover);
2601
+ }
2602
+ .auth-panel {
2603
+ display: flex;
2604
+ flex-direction: column;
2605
+ gap: 8px;
2606
+ }
2607
+ .auth-otp-box {
2608
+ margin-top: 8px;
2609
+ border-top: 1px solid var(--border-glass);
2610
+ padding-top: 10px;
2611
+ }
2612
+ .auth-actions {
2613
+ display: flex;
2614
+ gap: 8px;
2615
+ }
2616
+ .auth-current {
2617
+ margin-top: 10px;
2618
+ font-size: 0.8rem;
2619
+ color: var(--text-secondary);
2620
+ }
2621
+ .auth-footer {
2622
+ margin-top: 10px;
2623
+ }
2624
+
2625
  /* ============================================
2626
  RESPONSIVE ADJUSTMENTS (Phase 3)
2627
  ============================================ */
static/js/script.js CHANGED
@@ -28,6 +28,8 @@ document.addEventListener('DOMContentLoaded', () => {
28
  const waveformCanvas = $('waveform-canvas');
29
  const toastEl = $('toast');
30
  const emotionIndicator = $('emotion-indicator');
 
 
31
 
32
  // ─── STATE ───
33
  let conversationHistory = [];
@@ -61,6 +63,7 @@ document.addEventListener('DOMContentLoaded', () => {
61
  let voiceProfiles = [];
62
  let activeVoiceProfileId = null;
63
  let editingVoiceProfileId = null;
 
64
  const DEFAULT_APP_SETTINGS = {
65
  autoListen: true,
66
  autoSpeak: true,
@@ -955,6 +958,11 @@ document.addEventListener('DOMContentLoaded', () => {
955
  });
956
 
957
  startBtn.addEventListener('click', () => {
 
 
 
 
 
958
  onboardingScreen.classList.add('hidden');
959
  appContainer.classList.remove('hidden');
960
  window._echoLevel = selectedLevel;
@@ -1752,7 +1760,147 @@ document.addEventListener('DOMContentLoaded', () => {
1752
  }
1753
 
1754
  // ============================================
1755
- // 15. PERSISTENCE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1756
  // ============================================
1757
  function saveHistory() {
1758
  try {
@@ -1812,6 +1960,8 @@ document.addEventListener('DOMContentLoaded', () => {
1812
  updateSttButton();
1813
  loadVocab();
1814
  renderVocabList();
 
 
1815
 
1816
  if ('speechSynthesis' in window) {
1817
  window.speechSynthesis.onvoiceschanged = () => {
 
28
  const waveformCanvas = $('waveform-canvas');
29
  const toastEl = $('toast');
30
  const emotionIndicator = $('emotion-indicator');
31
+ const authBtn = $('auth-btn');
32
+ const authUserLabel = $('auth-user-label');
33
 
34
  // ─── STATE ───
35
  let conversationHistory = [];
 
63
  let voiceProfiles = [];
64
  let activeVoiceProfileId = null;
65
  let editingVoiceProfileId = null;
66
+ let currentUser = null;
67
  const DEFAULT_APP_SETTINGS = {
68
  autoListen: true,
69
  autoSpeak: true,
 
958
  });
959
 
960
  startBtn.addEventListener('click', () => {
961
+ if (!currentUser) {
962
+ showToast('Please login first', 'error');
963
+ $('auth-modal')?.classList.remove('hidden');
964
+ return;
965
+ }
966
  onboardingScreen.classList.add('hidden');
967
  appContainer.classList.remove('hidden');
968
  window._echoLevel = selectedLevel;
 
1760
  }
1761
 
1762
  // ============================================
1763
+ // 15. AUTH INTEGRATION
1764
+ // ============================================
1765
+ function setAuthUI(user) {
1766
+ currentUser = user || null;
1767
+ if (authUserLabel) {
1768
+ authUserLabel.textContent = currentUser
1769
+ ? (currentUser.full_name || currentUser.email || 'U').slice(0, 1).toUpperCase()
1770
+ : '👤';
1771
+ }
1772
+
1773
+ const currentEl = $('auth-current');
1774
+ if (currentEl) {
1775
+ currentEl.textContent = currentUser
1776
+ ? `Signed in as ${currentUser.full_name || currentUser.email}`
1777
+ : 'Not signed in';
1778
+ }
1779
+
1780
+ $('auth-logout')?.classList.toggle('hidden', !currentUser);
1781
+ }
1782
+
1783
+ async function authRequest(path, options = {}) {
1784
+ const res = await fetch(path, {
1785
+ credentials: 'include',
1786
+ ...options,
1787
+ headers: {
1788
+ 'Content-Type': 'application/json',
1789
+ ...(options.headers || {}),
1790
+ },
1791
+ });
1792
+
1793
+ let payload = null;
1794
+ try {
1795
+ payload = await res.json();
1796
+ } catch (e) {}
1797
+
1798
+ if (!res.ok) {
1799
+ throw new Error(payload?.detail || payload?.error || 'Request failed');
1800
+ }
1801
+ return payload || {};
1802
+ }
1803
+
1804
+ async function refreshCurrentUser() {
1805
+ try {
1806
+ const me = await authRequest('/auth/me', { method: 'GET' });
1807
+ setAuthUI(me || null);
1808
+ } catch (e) {
1809
+ setAuthUI(null);
1810
+ }
1811
+ }
1812
+
1813
+ function bindAuthUI() {
1814
+ authBtn?.addEventListener('click', () => {
1815
+ $('auth-modal')?.classList.remove('hidden');
1816
+ });
1817
+
1818
+ $('auth-close')?.addEventListener('click', () => {
1819
+ $('auth-modal')?.classList.add('hidden');
1820
+ });
1821
+
1822
+ document.querySelectorAll('.auth-tab').forEach((tab) => {
1823
+ tab.addEventListener('click', () => {
1824
+ document.querySelectorAll('.auth-tab').forEach((t) => t.classList.remove('active'));
1825
+ tab.classList.add('active');
1826
+ const isLogin = tab.dataset.authTab === 'login';
1827
+ $('auth-login-panel')?.classList.toggle('hidden', !isLogin);
1828
+ $('auth-signup-panel')?.classList.toggle('hidden', isLogin);
1829
+ });
1830
+ });
1831
+
1832
+ $('auth-login-submit')?.addEventListener('click', async () => {
1833
+ try {
1834
+ const email = ($('auth-login-email')?.value || '').trim();
1835
+ const password = $('auth-login-password')?.value || '';
1836
+ await authRequest('/auth/login', {
1837
+ method: 'POST',
1838
+ body: JSON.stringify({ email, password }),
1839
+ });
1840
+ await refreshCurrentUser();
1841
+ $('auth-modal')?.classList.add('hidden');
1842
+ showToast('Login successful', 'success');
1843
+ } catch (e) {
1844
+ showToast(e.message || 'Login failed', 'error');
1845
+ }
1846
+ });
1847
+
1848
+ $('auth-signup-submit')?.addEventListener('click', async () => {
1849
+ try {
1850
+ const full_name = ($('auth-signup-name')?.value || '').trim();
1851
+ const email = ($('auth-signup-email')?.value || '').trim();
1852
+ const phone = ($('auth-signup-phone')?.value || '').trim();
1853
+ const password = $('auth-signup-password')?.value || '';
1854
+ await authRequest('/auth/signup', {
1855
+ method: 'POST',
1856
+ body: JSON.stringify({ full_name, email, phone, password }),
1857
+ });
1858
+ $('auth-otp-email').value = email;
1859
+ showToast('Account created. Verify with OTP', 'success');
1860
+ } catch (e) {
1861
+ showToast(e.message || 'Signup failed', 'error');
1862
+ }
1863
+ });
1864
+
1865
+ $('auth-otp-request')?.addEventListener('click', async () => {
1866
+ try {
1867
+ const email = ($('auth-otp-email')?.value || '').trim();
1868
+ await authRequest('/auth/request-otp', {
1869
+ method: 'POST',
1870
+ body: JSON.stringify({ email }),
1871
+ });
1872
+ showToast('OTP sent. Check Telegram bot', 'success');
1873
+ } catch (e) {
1874
+ showToast(e.message || 'OTP request failed', 'error');
1875
+ }
1876
+ });
1877
+
1878
+ $('auth-otp-verify')?.addEventListener('click', async () => {
1879
+ try {
1880
+ const email = ($('auth-otp-email')?.value || '').trim();
1881
+ const code = ($('auth-otp-code')?.value || '').trim();
1882
+ await authRequest('/auth/verify-otp', {
1883
+ method: 'POST',
1884
+ body: JSON.stringify({ email, code }),
1885
+ });
1886
+ await refreshCurrentUser();
1887
+ showToast('Account verified', 'success');
1888
+ } catch (e) {
1889
+ showToast(e.message || 'OTP verification failed', 'error');
1890
+ }
1891
+ });
1892
+
1893
+ $('auth-logout')?.addEventListener('click', async () => {
1894
+ try {
1895
+ await authRequest('/auth/logout', { method: 'POST' });
1896
+ } catch (e) {}
1897
+ setAuthUI(null);
1898
+ showToast('Logged out', 'success');
1899
+ });
1900
+ }
1901
+
1902
+ // ============================================
1903
+ // 16. PERSISTENCE
1904
  // ============================================
1905
  function saveHistory() {
1906
  try {
 
1960
  updateSttButton();
1961
  loadVocab();
1962
  renderVocabList();
1963
+ bindAuthUI();
1964
+ refreshCurrentUser();
1965
 
1966
  if ('speechSynthesis' in window) {
1967
  window.speechSynthesis.onvoiceschanged = () => {
templates/index.html CHANGED
@@ -172,6 +172,9 @@
172
  <span class="stat" id="stat-time" title="Session time">⏱ 0:00</span>
173
  <span class="stat" id="stat-msgs" title="Messages">💬 0</span>
174
  </div>
 
 
 
175
  <!-- Theme Toggle -->
176
  <button class="icon-btn" id="theme-btn" title="Toggle Theme">
177
  <svg
@@ -513,6 +516,105 @@
513
  </div>
514
  </div>
515
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
516
  <!-- ============ SIDE PANEL (Grammar + Vocab) ============ -->
517
  <div class="side-panel hidden" id="side-panel">
518
  <div class="panel-header">
 
172
  <span class="stat" id="stat-time" title="Session time">⏱ 0:00</span>
173
  <span class="stat" id="stat-msgs" title="Messages">💬 0</span>
174
  </div>
175
+ <button class="icon-btn" id="auth-btn" title="Login / Account">
176
+ <span id="auth-user-label">👤</span>
177
+ </button>
178
  <!-- Theme Toggle -->
179
  <button class="icon-btn" id="theme-btn" title="Toggle Theme">
180
  <svg
 
516
  </div>
517
  </div>
518
 
519
+ <!-- ============ AUTH MODAL ============ -->
520
+ <div class="modal-overlay hidden" id="auth-modal">
521
+ <div class="modal-card auth-card">
522
+ <div class="modal-header">
523
+ <h2>Account</h2>
524
+ <button class="modal-close" id="auth-close">&times;</button>
525
+ </div>
526
+
527
+ <div class="auth-tabs" id="auth-tabs">
528
+ <button class="auth-tab active" data-auth-tab="login">Login</button>
529
+ <button class="auth-tab" data-auth-tab="signup">Sign Up</button>
530
+ </div>
531
+
532
+ <div class="auth-panel" id="auth-login-panel">
533
+ <input
534
+ class="voice-input"
535
+ id="auth-login-email"
536
+ type="email"
537
+ placeholder="Email"
538
+ autocomplete="email"
539
+ />
540
+ <input
541
+ class="voice-input"
542
+ id="auth-login-password"
543
+ type="password"
544
+ placeholder="Password"
545
+ autocomplete="current-password"
546
+ />
547
+ <div class="auth-actions">
548
+ <button class="btn-primary" id="auth-login-submit">Login</button>
549
+ </div>
550
+ </div>
551
+
552
+ <div class="auth-panel hidden" id="auth-signup-panel">
553
+ <input
554
+ class="voice-input"
555
+ id="auth-signup-name"
556
+ type="text"
557
+ placeholder="Full name"
558
+ autocomplete="name"
559
+ />
560
+ <input
561
+ class="voice-input"
562
+ id="auth-signup-email"
563
+ type="email"
564
+ placeholder="Email"
565
+ autocomplete="email"
566
+ />
567
+ <input
568
+ class="voice-input"
569
+ id="auth-signup-phone"
570
+ type="text"
571
+ placeholder="Phone (optional)"
572
+ autocomplete="tel"
573
+ />
574
+ <input
575
+ class="voice-input"
576
+ id="auth-signup-password"
577
+ type="password"
578
+ placeholder="Password"
579
+ autocomplete="new-password"
580
+ />
581
+ <div class="auth-actions">
582
+ <button class="btn-primary" id="auth-signup-submit">Create account</button>
583
+ </div>
584
+
585
+ <div class="auth-otp-box">
586
+ <label class="voice-label" for="auth-otp-email">OTP verification</label>
587
+ <input
588
+ class="voice-input"
589
+ id="auth-otp-email"
590
+ type="email"
591
+ placeholder="Email for OTP"
592
+ autocomplete="email"
593
+ />
594
+ <div class="auth-actions">
595
+ <button class="btn-secondary" id="auth-otp-request">Request OTP</button>
596
+ </div>
597
+ <input
598
+ class="voice-input"
599
+ id="auth-otp-code"
600
+ type="text"
601
+ placeholder="6-digit code"
602
+ maxlength="6"
603
+ inputmode="numeric"
604
+ />
605
+ <div class="auth-actions">
606
+ <button class="btn-primary" id="auth-otp-verify">Verify OTP</button>
607
+ </div>
608
+ </div>
609
+ </div>
610
+
611
+ <div class="auth-current" id="auth-current"></div>
612
+ <div class="auth-actions auth-footer">
613
+ <button class="btn-secondary" id="auth-logout">Logout</button>
614
+ </div>
615
+ </div>
616
+ </div>
617
+
618
  <!-- ============ SIDE PANEL (Grammar + Vocab) ============ -->
619
  <div class="side-panel hidden" id="side-panel">
620
  <div class="panel-header">