File size: 12,806 Bytes
a74b879
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# ═══════════════════════════════════════════════════════════════════════════════
# NEW FEATURES: NOTIFICATIONS, 2FA, SUPPORT
# ═══════════════════════════════════════════════════════════════════════════════

# These endpoints should be added to server/api.py

# ── NOTIFICATIONS ──────────────────────────────────────────────────────────────

from server import notifications as notif_service

class NotificationPrefsRequest(BaseModel):
    email_enabled: bool = True
    sms_enabled: bool = False
    web_enabled: bool = True
    crawl_complete: bool = True
    analysis_complete: bool = True
    alert_triggered: bool = True
    weekly_report: bool = True

@app.get('/api/notifications')
async def api_get_notifications(request: Request, unread_only: bool = False):
    """Get user notifications"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        notifs = notif_service.get_notifications(uid, unread_only)
        return {'ok': True, 'notifications': notifs, 'count': len(notifs)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/notifications/{notification_id}/read')
async def api_mark_notification_read(notification_id: int, request: Request):
    """Mark notification as read"""
    try:
        notif_service.mark_as_read(notification_id)
        return {'ok': True}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/notifications/preferences')
async def api_get_notification_prefs(request: Request):
    """Get notification preferences"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        prefs = notif_service.get_preferences(uid)
        return {'ok': True, 'preferences': prefs}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/notifications/preferences')
async def api_update_notification_prefs(req: NotificationPrefsRequest, request: Request):
    """Update notification preferences"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        prefs_dict = req.dict()
        notif_service.update_preferences(uid, prefs_dict)
        return {'ok': True}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# ── 2FA (TWO-FACTOR AUTHENTICATION) ────────────────────────────────────────────

from server import two_factor_auth as tfa_service

@app.post('/api/2fa/setup')
async def api_setup_2fa(request: Request):
    """Generate 2FA secret and QR code"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        user = user_mgmt.get_user(uid)
        secret, qr_code = tfa_service.generate_secret(uid, user['email'])
        
        return {
            'ok': True,
            'secret': secret,
            'qr_code': qr_code,
            'backup_codes': tfa_service.get_backup_codes(uid) or []
        }
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/2fa/enable')
async def api_enable_2fa(request: Request):
    """Enable 2FA with verification"""
    try:
        data = await request.json()
        secret = data.get('secret')
        token_code = data.get('token')
        
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        # Verify token before enabling
        import pyotp
        totp = pyotp.TOTP(secret)
        if not totp.verify(token_code):
            return JSONResponse({'ok': False, 'error': 'Invalid token'}, status_code=400)
        
        tfa_service.enable_2fa(uid, secret)
        backup_codes = tfa_service.get_backup_codes(uid)
        
        return {
            'ok': True,
            'message': '2FA enabled successfully',
            'backup_codes': backup_codes
        }
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/2fa/disable')
async def api_disable_2fa(request: Request):
    """Disable 2FA"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        tfa_service.disable_2fa(uid)
        return {'ok': True, 'message': '2FA disabled'}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/2fa/status')
async def api_2fa_status(request: Request):
    """Check 2FA status"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        enabled = tfa_service.is_2fa_enabled(uid)
        return {'ok': True, 'enabled': enabled}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/2fa/login-history')
async def api_login_history(request: Request, days: int = 30):
    """Get login history"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        history = tfa_service.get_login_history(uid, days)
        return {'ok': True, 'history': history}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/2fa/suspicious-activity')
async def api_check_suspicious_activity(request: Request):
    """Check for suspicious login activity"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        activity = tfa_service.detect_suspicious_activity(uid)
        return {'ok': True, **activity}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

# ── SUPPORT SYSTEM ─────────────────────────────────────────────────────────────

from server import support as support_service

class SupportTicketRequest(BaseModel):
    subject: str
    description: str
    category: str
    priority: str = 'medium'

class TicketMessageRequest(BaseModel):
    message: str
    attachment_url: Optional[str] = None

@app.post('/api/support/tickets')
async def api_create_ticket(req: SupportTicketRequest, request: Request):
    """Create support ticket"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        ticket_id = support_service.create_ticket(
            uid, req.subject, req.description, req.category, req.priority
        )
        return {'ok': True, 'ticket_id': ticket_id}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/support/tickets')
async def api_list_tickets(request: Request, status: Optional[str] = None):
    """List user tickets"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        tickets = support_service.get_user_tickets(uid, status)
        return {'ok': True, 'tickets': tickets, 'count': len(tickets)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/support/tickets/{ticket_id}')
async def api_get_ticket(ticket_id: int, request: Request):
    """Get ticket details"""
    try:
        ticket = support_service.get_ticket(ticket_id)
        if not ticket:
            return JSONResponse({'ok': False, 'error': 'Ticket not found'}, status_code=404)
        
        messages = support_service.get_ticket_messages(ticket_id)
        return {'ok': True, 'ticket': ticket, 'messages': messages}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/support/tickets/{ticket_id}/messages')
async def api_add_ticket_message(ticket_id: int, req: TicketMessageRequest, request: Request):
    """Add message to ticket"""
    try:
        auth = request.headers.get('authorization', '')
        token = auth.split(' ', 1)[1].strip()
        uid = user_mgmt.verify_token(token)
        if not uid:
            return JSONResponse({'ok': False, 'error': 'unauthorized'}, status_code=401)
        
        msg_id = support_service.add_ticket_message(ticket_id, uid, req.message, req.attachment_url)
        return {'ok': True, 'message_id': msg_id}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.post('/api/support/tickets/{ticket_id}/status')
async def api_update_ticket_status(ticket_id: int, request: Request):
    """Update ticket status"""
    try:
        data = await request.json()
        status = data.get('status')
        
        support_service.update_ticket_status(ticket_id, status)
        return {'ok': True}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/support/kb')
async def api_get_kb_articles(category: Optional[str] = None):
    """Get knowledge base articles"""
    try:
        articles = support_service.get_kb_articles(category)
        return {'ok': True, 'articles': articles, 'count': len(articles)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/support/kb/search')
async def api_search_kb(q: str):
    """Search knowledge base"""
    try:
        results = support_service.search_kb(q)
        return {'ok': True, 'results': results, 'count': len(results)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/support/faqs')
async def api_get_faqs(category: Optional[str] = None):
    """Get FAQs"""
    try:
        faqs = support_service.get_faqs(category)
        return {'ok': True, 'faqs': faqs, 'count': len(faqs)}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)

@app.get('/api/support/stats')
async def api_support_stats():
    """Get support statistics"""
    try:
        stats = support_service.get_ticket_stats()
        return {'ok': True, 'stats': stats}
    except Exception as e:
        return JSONResponse({'ok': False, 'error': str(e)}, status_code=500)