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
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
from flask import Blueprint, request, jsonify, make_response
import re
import logging
from models.user_model import User
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required, get_jwt
import datetime
from functools import wraps

# Cấu hình logging
logger = logging.getLogger(__name__)

# Tạo blueprint
auth_routes = Blueprint('auth', __name__)

def validate_email(email):
    """Kiểm tra định dạng email"""
    pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    return re.match(pattern, email) is not None

def validate_password(password):
    """Kiểm tra mật khẩu có đủ mạnh không"""
    return len(password) >= 6

# SỬA: Decorator đơn giản hơn để check admin
def require_admin(f):
    """Decorator đơn giản để kiểm tra admin"""
    @wraps(f)
    @jwt_required()
    def decorated_function(*args, **kwargs):
        try:
            user_id = get_jwt_identity()
            user = User.find_by_id(user_id)
            
            if not user:
                return jsonify({
                    "success": False,
                    "error": "User không tồn tại"
                }), 403
            
            # Kiểm tra có phải admin không
            if not user.is_admin():
                return jsonify({
                    "success": False,
                    "error": "Không có quyền truy cập admin"
                }), 403
            
            # Thêm user vào request context
            request.current_user = user
            return f(*args, **kwargs)
            
        except Exception as e:
            logger.error(f"Lỗi xác thực admin: {e}")
            return jsonify({
                "success": False,
                "error": "Lỗi xác thực"
            }), 500
    return decorated_function

def register_user(name, email, password, gender=None):
    """Đăng ký người dùng mới"""
    if not name or not email or not password:
        return False, "Vui lòng nhập đầy đủ thông tin"
    
    if not validate_email(email):
        return False, "Email không hợp lệ"
    
    if not validate_password(password):
        return False, "Mật khẩu phải có ít nhất 6 ký tự"
    
    success, result = User.register(name, email, password, gender)
    if success:
        return True, {"user_id": result}
    else:
        return False, result

def login_user(email, password):
    """Đăng nhập người dùng"""
    if not email or not password:
        return False, "Vui lòng nhập đầy đủ thông tin đăng nhập"
    
    success, result = User.login(email, password)
    if success:
        user = result
        
        # Tạo JWT token với thời gian hết hạn 24 giờ
        expires = datetime.timedelta(hours=24)
        access_token = create_access_token(
            identity=str(user.user_id), 
            expires_delta=expires,
            additional_claims={
                "name": user.name,
                "email": user.email,
                "gender": user.gender,
                "role": user.role,
                "permissions": user.permissions,
                "is_admin": user.is_admin()
            }
        )
        
        return True, {
            "user_id": str(user.user_id),
            "user": {
                "id": str(user.user_id),
                "name": user.name,
                "email": user.email,
                "gender": user.gender,
                "role": user.role,
                "permissions": user.permissions,
                "is_admin": user.is_admin()
            },
            "access_token": access_token,
            "expires_in": 86400
        }
    else:
        return False, result

@auth_routes.route('/register', methods=['POST'])
def register():
    """API endpoint để đăng ký người dùng mới"""
    try:
        data = request.json
        
        name = data.get('fullName')
        email = data.get('email')
        password = data.get('password')
        gender = data.get('gender')
        
        success, result = register_user(name, email, password, gender)
        
        if success:
            return jsonify({
                "success": True,
                "message": "Đăng ký thành công",
                "user_id": result.get("user_id")
            })
        else:
            return jsonify({
                "success": False,
                "error": result
            }), 400
            
    except Exception as e:
        logger.error(f"Lỗi đăng ký người dùng: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@auth_routes.route('/login', methods=['POST'])
def login():
    """API endpoint để đăng nhập"""
    try:
        data = request.json
        
        email = data.get('email')
        password = data.get('password')
        remember_me = data.get('rememberMe', False)
        
        success, result = login_user(email, password)
        
        if success:
            access_token = result.get("access_token")
            
            response = make_response(jsonify({
                "success": True,
                "user_id": result.get("user_id"),
                "user": result.get("user"),
                "access_token": access_token,
                "expires_in": result.get("expires_in")
            }))
            
            cookie_max_age = 86400 if remember_me else None
            response.set_cookie(
                'access_token_cookie',
                access_token,
                max_age=cookie_max_age,
                httponly=True,
                path='/api',
                samesite='Lax',
                secure=False
            )
            
            return response
        else:
            return jsonify({
                "success": False,
                "error": result
            }), 401
            
    except Exception as e:
        logger.error(f"Lỗi đăng nhập: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@auth_routes.route('/logout', methods=['POST'])
def logout():
    """API endpoint để đăng xuất"""
    response = make_response(jsonify({
        "success": True,
        "message": "Đăng xuất thành công"
    }))
    response.delete_cookie('access_token_cookie', path='/api')
    return response

@auth_routes.route('/verify-token', methods=['POST'])
@jwt_required()
def verify_token():
    """API endpoint để kiểm tra token có hợp lệ không"""
    try:
        current_user_id = get_jwt_identity()
        
        user = User.find_by_id(current_user_id)
        if not user:
            return jsonify({
                "success": False,
                "error": "User không tồn tại"
            }), 401
        
        return jsonify({
            "success": True,
            "user_id": current_user_id,
            "user": {
                "id": str(user.user_id),
                "name": user.name,
                "email": user.email,
                "gender": user.gender,
                "role": user.role,
                "permissions": user.permissions,
                "is_admin": user.is_admin()
            }
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 401

@auth_routes.route('/profile', methods=['GET'])
@jwt_required()
def user_profile():
    """API endpoint để lấy thông tin người dùng"""
    try:
        user_id = get_jwt_identity()
        user = User.find_by_id(user_id)
        
        if user:
            profile = {
                "id": str(user.user_id),
                "name": user.name,
                "email": user.email,
                "gender": user.gender,
                "role": user.role,
                "permissions": user.permissions,
                "is_admin": user.is_admin(),
                "created_at": user.created_at.isoformat() if user.created_at else None,
                "updated_at": user.updated_at.isoformat() if user.updated_at else None,
                "last_login": user.last_login.isoformat() if user.last_login else None
            }
            
            return jsonify({
                "success": True,
                "user": profile
            })
        else:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy thông tin người dùng"
            }), 404
            
    except Exception as e:
        logger.error(f"Lỗi lấy thông tin người dùng: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@auth_routes.route('/profile', methods=['PUT'])
@jwt_required()
def update_profile():
    """API endpoint để cập nhật thông tin người dùng"""
    try:
        data = request.json
        user_id = get_jwt_identity()
        
        user = User.find_by_id(user_id)
        if not user:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy người dùng"
            }), 404
        
        if 'name' in data:
            user.name = data['name']
        
        if 'gender' in data:
            user.gender = data['gender']
        
        user.save()
        
        return jsonify({
            "success": True,
            "message": "Cập nhật thông tin thành công"
        })
            
    except Exception as e:
        logger.error(f"Lỗi cập nhật thông tin người dùng: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@auth_routes.route('/change-password', methods=['POST'])
@jwt_required()
def update_password():
    """API endpoint để đổi mật khẩu"""
    try:
        data = request.json
        user_id = get_jwt_identity()
            
        current_password = data.get('currentPassword')
        new_password = data.get('newPassword')
        
        user = User.find_by_id(user_id)
        if not user:
            return jsonify({
                "success": False,
                "error": "Không tìm thấy người dùng"
            }), 404
        
        if not User.check_password(user.password, current_password):
            return jsonify({
                "success": False,
                "error": "Mật khẩu hiện tại không chính xác"
            }), 400
        
        if not validate_password(new_password):
            return jsonify({
                "success": False,
                "error": "Mật khẩu mới phải có ít nhất 6 ký tự"
            }), 400
        
        user.password = User.hash_password(new_password)
        user.save()
        
        return jsonify({
            "success": True,
            "message": "Đổi mật khẩu thành công"
        })
            
    except Exception as e:
        logger.error(f"Lỗi đổi mật khẩu: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

# === ADMIN ENDPOINTS - SỬA LẠI ĐỂ SỬ DỤNG CHUNG TOKEN ===

@auth_routes.route('/admin/stats/overview', methods=['GET'])
@require_admin
def get_admin_overview_stats():
    """API endpoint để lấy thống kê tổng quan cho admin"""
    try:
        from models.conversation_model import get_db
        
        db = get_db()
        
        # Đếm tổng conversations
        total_conversations = db.conversations.count_documents({})
        
        # Conversations trong 24h qua
        day_ago = datetime.datetime.now() - datetime.timedelta(days=1)
        recent_conversations = db.conversations.count_documents({
            "created_at": {"$gte": day_ago}
        })
        
        # Đếm tổng tin nhắn
        pipeline = [
            {"$project": {"message_count": {"$size": "$messages"}}},
            {"$group": {"_id": None, "total_messages": {"$sum": "$message_count"}}}
        ]
        message_result = list(db.conversations.aggregate(pipeline))
        total_messages = message_result[0]["total_messages"] if message_result else 0
        
        # Mock users data (có thể thay bằng query thực tế)
        total_users = db.users.count_documents({}) if hasattr(db, 'users') else 1
        
        return jsonify({
            "success": True,
            "stats": {
                "users": {
                    "total": total_users,
                    "new_today": 0
                },
                "conversations": {
                    "total": total_conversations,
                    "recent": recent_conversations
                },
                "data": {
                    "total_chunks": total_messages,
                    "total_tables": 0,
                    "total_figures": 0,
                    "total_items": total_messages,
                    "embeddings": 0
                },
                "admins": {
                    "total": 1
                }
            }
        })
        
    except Exception as e:
        logger.error(f"Lỗi lấy thống kê admin: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@auth_routes.route('/admin/recent-activities', methods=['GET'])
@require_admin
def get_admin_recent_activities():
    """API endpoint để lấy hoạt động gần đây cho admin"""
    try:
        limit = int(request.args.get('limit', 10))
        
        from models.conversation_model import get_db
        db = get_db()
        
        # Lấy conversations gần đây
        recent_conversations = list(db.conversations.find(
            {},
            {"title": 1, "created_at": 1, "updated_at": 1}
        ).sort("updated_at", -1).limit(limit))
        
        activities = []
        for conv in recent_conversations:
            activities.append({
                "type": "conversation_created",
                "title": "Cuộc hội thoại mới",
                "description": conv.get("title", "Cuộc hội thoại"),
                "timestamp": conv.get("updated_at", datetime.datetime.now()).isoformat()
            })
        
        return jsonify({
            "success": True,
            "activities": activities
        })
        
    except Exception as e:
        logger.error(f"Lỗi lấy hoạt động gần đây: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@auth_routes.route('/admin/alerts', methods=['GET'])
@require_admin
def get_admin_system_alerts():
    """API endpoint để lấy cảnh báo hệ thống cho admin"""
    try:
        # Mock alerts - có thể thay bằng logic thực tế
        alerts = [
            {
                "type": "info",
                "title": "Hệ thống hoạt động bình thường",
                "message": "Tất cả các dịch vụ đang chạy ổn định",
                "severity": "low"
            }
        ]
        
        return jsonify({
            "success": True,
            "alerts": alerts
        })
        
    except Exception as e:
        logger.error(f"Lỗi lấy cảnh báo hệ thống: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@auth_routes.route('/init-admin', methods=['POST'])
def init_admin():
    """API endpoint để khởi tạo admin mặc định"""
    try:
        success, result = User.create_default_admin()
        
        if success:
            return jsonify({
                "success": True,
                "message": "Khởi tạo admin thành công",
                "data": result
            })
        else:
            return jsonify({
                "success": False,
                "error": result
            }), 400
            
    except Exception as e:
        logger.error(f"Lỗi khởi tạo admin: {str(e)}")
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500