-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1923 lines (1610 loc) · 70.2 KB
/
app.py
File metadata and controls
1923 lines (1610 loc) · 70.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import json
import psycopg2
from psycopg2 import extras
from flask import jsonify
from flask_cors import CORS
from flask import (
Flask,
render_template,
request,
make_response,
Response,
redirect,
url_for,
)
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
import datetime
from functools import wraps
import traceback
import requests
from user_agents import parse
from config import DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASS, JWT_SECRET_KEY
# ── Add parent directory so imports still work ────────────────────────────────
current_dir = os.path.dirname(__file__)
parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
app = Flask(__name__)
# Simplified CORS configuration - let Flask-CORS handle everything
CORS(app,
origins=["https://ap.projectkryptos.xyz", "http://localhost:3000", "http://localhost:5173"],
methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "Authorization", "X-Requested-With"],
supports_credentials=True,
expose_headers=["Content-Type", "Authorization"])
# JWT Configuration
app.config['JWT_SECRET_KEY'] = JWT_SECRET_KEY
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(days=7)
# Upload folder for custom backgrounds
UPLOAD_FOLDER = os.path.join(current_dir, "static", "uploads")
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "gif"}
# In-memory storage for blacklisted tokens (use Redis in production)
blacklisted_tokens = set()
def allowed_file(filename):
return (
"." in filename
and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
)
def get_pg_connection():
"""Return a new psycopg2 connection + NamedTupleCursor factory."""
try:
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASS,
connect_timeout=10
)
return conn
except psycopg2.Error as e:
print(f"[!] Database connection error: {e}")
raise
def get_client_ip():
"""Get the real client IP address."""
if request.headers.get('X-Forwarded-For'):
return request.headers.get('X-Forwarded-For').split(',')[0].strip()
elif request.headers.get('X-Real-IP'):
return request.headers.get('X-Real-IP')
else:
return request.remote_addr
def get_location_from_ip(ip_address):
"""Get location information from IP address using a free service."""
try:
# Skip localhost/private IPs
if ip_address in ['127.0.0.1', 'localhost'] or ip_address.startswith('192.168.') or ip_address.startswith('10.'):
return {'country': 'Local', 'city': 'Local', 'region': 'Local'}
# Use ipapi.co for geolocation (free tier: 1000 requests/day)
response = requests.get(f'https://ipapi.co/{ip_address}/json/', timeout=5)
if response.status_code == 200:
data = response.json()
return {
'country': data.get('country_name', 'Unknown'),
'city': data.get('city', 'Unknown'),
'region': data.get('region', 'Unknown')
}
except Exception as e:
print(f"[!] Error getting location for IP {ip_address}: {e}")
return {'country': 'Unknown', 'city': 'Unknown', 'region': 'Unknown'}
def should_track_visit(ip_address, user_id, page_path):
"""
Determine if we should track this visit to avoid duplicate counting.
Returns True if this is a new visit that should be tracked.
"""
try:
conn = get_pg_connection()
cur = conn.cursor()
# Check if this IP/user has visited this page in the last 30 minutes
time_threshold = datetime.datetime.utcnow() - datetime.timedelta(minutes=30)
if user_id:
# For logged-in users, check by user_id
cur.execute("""
SELECT COUNT(*) FROM site_analytics
WHERE user_id = %s AND page_path = %s AND visit_time > %s
""", (user_id, page_path, time_threshold))
else:
# For anonymous users, check by IP
cur.execute("""
SELECT COUNT(*) FROM site_analytics
WHERE ip_address = %s AND page_path = %s AND visit_time > %s AND user_id IS NULL
""", (ip_address, page_path, time_threshold))
recent_visits = cur.fetchone()[0]
cur.close()
conn.close()
# Only track if no recent visits
return recent_visits == 0
except Exception as e:
print(f"[!] Error checking visit tracking: {e}")
# If there's an error, err on the side of not tracking to avoid duplicates
return False
def track_page_visit(page_path, user_id=None):
"""Track a page visit with analytics data, avoiding duplicates."""
try:
ip_address = get_client_ip()
# Skip tracking for certain conditions
if not should_track_visit(ip_address, user_id, page_path):
print(f"[*] Skipping duplicate visit tracking for {page_path} from {ip_address}")
return
user_agent_string = request.headers.get('User-Agent', '')
user_agent = parse(user_agent_string)
# Get location data
location = get_location_from_ip(ip_address)
conn = get_pg_connection()
cur = conn.cursor()
# Insert analytics record
cur.execute("""
INSERT INTO site_analytics (
user_id, ip_address, page_path, user_agent, browser, browser_version,
os, os_version, device_type, country, city, region, visit_time
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
user_id,
ip_address,
page_path,
user_agent_string,
user_agent.browser.family,
user_agent.browser.version_string,
user_agent.os.family,
user_agent.os.version_string,
'Mobile' if user_agent.is_mobile else 'Desktop',
location['country'],
location['city'],
location['region'],
datetime.datetime.utcnow()
))
conn.commit()
cur.close()
conn.close()
print(f"[*] Tracked new visit: {page_path} from {ip_address} (User: {user_id or 'Anonymous'})")
except Exception as e:
print(f"[!] Error tracking page visit: {e}")
def init_auth_tables():
"""Initialize authentication tables if they don't exist."""
try:
conn = get_pg_connection()
cur = conn.cursor()
# Create users table with privileges
cur.execute("""
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
privilege_level VARCHAR(20) DEFAULT 'user' CHECK (privilege_level IN ('user', 'premium', 'moderator', 'admin', 'godmode')),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_login TIMESTAMP,
is_active BOOLEAN DEFAULT TRUE
)
""")
# Create user_ratings table for storing user ratings
cur.execute("""
CREATE TABLE IF NOT EXISTS user_ratings (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
url VARCHAR(500) NOT NULL,
rating INTEGER CHECK (rating >= 1 AND rating <= 5),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, url)
)
""")
# Create user_preferences table
cur.execute("""
CREATE TABLE IF NOT EXISTS user_preferences (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
wallpaper VARCHAR(255),
blur_intensity INTEGER DEFAULT 10,
accent_color VARCHAR(7) DEFAULT '#4fc3f7',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id)
)
""")
# Create site analytics table
cur.execute("""
CREATE TABLE IF NOT EXISTS site_analytics (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
ip_address INET NOT NULL,
page_path VARCHAR(255) NOT NULL,
user_agent TEXT,
browser VARCHAR(100),
browser_version VARCHAR(50),
os VARCHAR(100),
os_version VARCHAR(50),
device_type VARCHAR(20),
country VARCHAR(100),
city VARCHAR(100),
region VARCHAR(100),
visit_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
session_duration INTEGER DEFAULT 0
)
""")
# Create session tracking table
cur.execute("""
CREATE TABLE IF NOT EXISTS user_sessions (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
ip_address INET NOT NULL,
session_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
session_end TIMESTAMP,
pages_visited INTEGER DEFAULT 1,
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Create indexes for better performance
cur.execute("CREATE INDEX IF NOT EXISTS idx_analytics_visit_time ON site_analytics(visit_time)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_analytics_ip ON site_analytics(ip_address)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_analytics_user_id ON site_analytics(user_id)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_analytics_ip_time ON site_analytics(ip_address, visit_time)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_analytics_user_time ON site_analytics(user_id, visit_time)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON user_sessions(user_id)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_users_privilege ON users(privilege_level)")
cur.execute("CREATE INDEX IF NOT EXISTS idx_users_active ON users(is_active)")
conn.commit()
cur.close()
conn.close()
print("[*] Authentication and analytics tables initialized successfully")
except Exception as e:
print(f"[!] Error initializing auth tables: {e}")
raise
def token_required(f):
"""Decorator to require JWT token for protected routes."""
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if not token:
return jsonify({'message': 'Access token required'}), 401
try:
# Remove 'Bearer ' prefix
token = token.split(' ')[1] if token.startswith('Bearer ') else token
# Check if token is blacklisted
if token in blacklisted_tokens:
return jsonify({'message': 'Token has been revoked'}), 401
# Decode token
data = jwt.decode(token, app.config['JWT_SECRET_KEY'], algorithms=['HS256'])
# Get user from database
conn = get_pg_connection()
cur = conn.cursor(cursor_factory=extras.NamedTupleCursor)
cur.execute("SELECT id, username, email, privilege_level FROM users WHERE id = %s", (data['user_id'],))
current_user = cur.fetchone()
cur.close()
conn.close()
if not current_user:
return jsonify({'message': 'User not found'}), 401
except jwt.ExpiredSignatureError:
return jsonify({'message': 'Token has expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'message': 'Token is invalid'}), 401
except Exception as e:
print(f"[!] Token verification error: {e}")
return jsonify({'message': 'Token verification failed'}), 401
return f(current_user, *args, **kwargs)
return decorated
def godmode_required(f):
"""Decorator to require godmode privileges."""
@wraps(f)
@token_required
def decorated(current_user, *args, **kwargs):
if current_user.privilege_level != 'godmode':
return jsonify({'message': 'Godmode privileges required'}), 403
return f(current_user, *args, **kwargs)
return decorated
def admin_required(f):
"""Decorator to require admin or godmode privileges."""
@wraps(f)
@token_required
def decorated(current_user, *args, **kwargs):
if current_user.privilege_level not in ['admin', 'godmode']:
return jsonify({'message': 'Admin privileges required'}), 403
return f(current_user, *args, **kwargs)
return decorated
def optional_token(f):
"""Decorator that optionally checks for JWT token but doesn't require it."""
@wraps(f)
def decorated(*args, **kwargs):
current_user = None
token = request.headers.get('Authorization')
if token:
try:
token = token.split(' ')[1] if token.startswith('Bearer ') else token
if token not in blacklisted_tokens:
data = jwt.decode(token, app.config['JWT_SECRET_KEY'], algorithms=['HS256'])
conn = get_pg_connection()
cur = conn.cursor(cursor_factory=extras.NamedTupleCursor)
cur.execute("SELECT id, username, email, privilege_level FROM users WHERE id = %s", (data['user_id'],))
current_user = cur.fetchone()
cur.close()
conn.close()
except Exception as e:
print(f"[!] Optional token verification failed: {e}")
pass # Invalid token, but that's okay for optional auth
return f(current_user, *args, **kwargs)
return decorated
# Add error handlers
@app.errorhandler(404)
def not_found(error):
return jsonify({'message': 'Endpoint not found'}), 404
@app.errorhandler(500)
def internal_error(error):
print(f"[!] Internal server error: {error}")
print(f"[!] Traceback: {traceback.format_exc()}")
return jsonify({'message': 'Internal server error'}), 500
@app.errorhandler(400)
def bad_request(error):
return jsonify({'message': 'Bad request'}), 400
# Health check endpoint
@app.route('/api/health', methods=['GET'])
def health_check():
"""Health check endpoint to verify API is running."""
try:
# Test database connection
conn = get_pg_connection()
cur = conn.cursor()
cur.execute("SELECT 1")
cur.close()
conn.close()
return jsonify({
'status': 'healthy',
'message': 'API is running and database is accessible',
'timestamp': datetime.datetime.utcnow().isoformat()
}), 200
except Exception as e:
return jsonify({
'status': 'unhealthy',
'message': f'Database connection failed: {str(e)}',
'timestamp': datetime.datetime.utcnow().isoformat()
}), 500
@app.route('/api/stats', methods=['GET'])
def get_site_stats():
"""Get site statistics like total indexed pages."""
try:
conn = get_pg_connection()
cur = conn.cursor()
# Get total number of indexed pages
cur.execute("SELECT COUNT(*) FROM webpages")
total_pages = cur.fetchone()[0]
# Get total number of registered users
cur.execute("SELECT COUNT(*) FROM users")
total_users = cur.fetchone()[0]
# Get pages indexed in the last 24 hours
cur.execute("""
SELECT COUNT(*) FROM webpages
WHERE timestamp >= NOW() - INTERVAL '24 hours'
""")
recent_pages = cur.fetchone()[0]
cur.close()
conn.close()
return jsonify({
'total_pages': total_pages,
'total_users': total_users,
'recent_pages': recent_pages,
'last_updated': datetime.datetime.utcnow().isoformat()
}), 200
except Exception as e:
print(f"[!] Error fetching site stats: {e}")
return jsonify({
'total_pages': 0,
'total_users': 0,
'recent_pages': 0,
'error': str(e)
}), 500
# ═══════════════════════════════════════════════════════════════════════════════
# ADMIN USER MANAGEMENT ROUTES
# ═══════════════════════════════════════════════════════════════════════════════
@app.route('/api/admin/users', methods=['GET', 'OPTIONS'])
@godmode_required
def get_all_users(current_user):
"""Get all registered users - Godmode only."""
if request.method == 'OPTIONS':
return '', 200
try:
# Get query parameters for filtering and pagination
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 50))
search = request.args.get('search', '').strip()
privilege_filter = request.args.get('privilege', '')
active_filter = request.args.get('active', '')
conn = get_pg_connection()
cur = conn.cursor(cursor_factory=extras.NamedTupleCursor)
# Build the query with filters
base_query = """
SELECT
u.id,
u.username,
u.email,
u.privilege_level,
u.created_at,
u.updated_at,
u.last_login,
u.is_active,
COUNT(ur.id) as total_ratings,
COUNT(DISTINCT sa.id) as total_visits
FROM users u
LEFT JOIN user_ratings ur ON u.id = ur.user_id
LEFT JOIN site_analytics sa ON u.id = sa.user_id
WHERE 1=1
"""
count_query = "SELECT COUNT(*) FROM users u WHERE 1=1"
params = []
count_params = []
# Add search filter
if search:
search_condition = " AND (u.username ILIKE %s OR u.email ILIKE %s)"
base_query += search_condition
count_query += search_condition
search_param = f"%{search}%"
params.extend([search_param, search_param])
count_params.extend([search_param, search_param])
# Add privilege filter
if privilege_filter:
privilege_condition = " AND u.privilege_level = %s"
base_query += privilege_condition
count_query += privilege_condition
params.append(privilege_filter)
count_params.append(privilege_filter)
# Add active filter
if active_filter:
active_value = active_filter.lower() == 'true'
active_condition = " AND u.is_active = %s"
base_query += active_condition
count_query += active_condition
params.append(active_value)
count_params.append(active_value)
# Add grouping and ordering
base_query += """
GROUP BY u.id, u.username, u.email, u.privilege_level, u.created_at, u.updated_at, u.last_login, u.is_active
ORDER BY u.created_at DESC
"""
# Add pagination
offset = (page - 1) * per_page
base_query += " LIMIT %s OFFSET %s"
params.extend([per_page, offset])
# Execute queries
cur.execute(base_query, params)
users = cur.fetchall()
cur.execute(count_query, count_params)
total_users = cur.fetchone()[0]
# Get overall statistics
cur.execute("""
SELECT
COUNT(*) as total_users,
COUNT(CASE WHEN privilege_level = 'user' THEN 1 END) as regular_users,
COUNT(CASE WHEN privilege_level = 'premium' THEN 1 END) as premium_users,
COUNT(CASE WHEN privilege_level = 'moderator' THEN 1 END) as moderators,
COUNT(CASE WHEN privilege_level = 'admin' THEN 1 END) as admins,
COUNT(CASE WHEN privilege_level = 'godmode' THEN 1 END) as godmode_users,
COUNT(CASE WHEN is_active = true THEN 1 END) as active_users,
COUNT(CASE WHEN last_login >= NOW() - INTERVAL '7 days' THEN 1 END) as recent_logins
FROM users
""")
stats = cur.fetchone()
cur.close()
conn.close()
# Format user data
users_data = []
for user in users:
users_data.append({
'id': user.id,
'username': user.username,
'email': user.email,
'privilege_level': user.privilege_level,
'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,
'is_active': user.is_active,
'total_ratings': user.total_ratings,
'total_visits': user.total_visits
})
response_data = {
'users': users_data,
'pagination': {
'page': page,
'per_page': per_page,
'total': total_users,
'pages': (total_users + per_page - 1) // per_page
},
'stats': {
'total_users': stats.total_users,
'regular_users': stats.regular_users,
'premium_users': stats.premium_users,
'moderators': stats.moderators,
'admins': stats.admins,
'godmode_users': stats.godmode_users,
'active_users': stats.active_users,
'recent_logins': stats.recent_logins
}
}
print(f"[*] Admin {current_user.username} fetched {len(users_data)} users")
return jsonify(response_data), 200
except Exception as e:
print(f"[!] Error fetching users: {e}")
print(f"[!] Traceback: {traceback.format_exc()}")
return jsonify({'message': 'Failed to fetch users'}), 500
@app.route('/api/admin/users/<int:user_id>/privileges', methods=['PUT', 'OPTIONS'])
@godmode_required
def update_user_privileges(current_user, user_id):
"""Update user privilege level - Godmode only."""
if request.method == 'OPTIONS':
return '', 200
try:
data = request.get_json()
new_privilege = data.get('privilege_level', '').strip()
# Validate privilege level
valid_privileges = ['user', 'premium', 'moderator', 'admin', 'godmode']
if new_privilege not in valid_privileges:
return jsonify({'message': 'Invalid privilege level'}), 400
# Prevent users from removing their own godmode privileges
if user_id == current_user.id and new_privilege != 'godmode':
return jsonify({'message': 'Cannot remove your own godmode privileges'}), 400
conn = get_pg_connection()
cur = conn.cursor(cursor_factory=extras.NamedTupleCursor)
# Check if user exists
cur.execute("SELECT id, username, privilege_level FROM users WHERE id = %s", (user_id,))
target_user = cur.fetchone()
if not target_user:
cur.close()
conn.close()
return jsonify({'message': 'User not found'}), 404
old_privilege = target_user.privilege_level
# Update privilege level
cur.execute("""
UPDATE users
SET privilege_level = %s, updated_at = CURRENT_TIMESTAMP
WHERE id = %s
""", (new_privilege, user_id))
conn.commit()
cur.close()
conn.close()
print(f"[*] Admin {current_user.username} updated user {target_user.username} privileges: {old_privilege} -> {new_privilege}")
return jsonify({
'message': 'User privileges updated successfully',
'user_id': user_id,
'username': target_user.username,
'old_privilege': old_privilege,
'new_privilege': new_privilege
}), 200
except Exception as e:
print(f"[!] Error updating user privileges: {e}")
print(f"[!] Traceback: {traceback.format_exc()}")
return jsonify({'message': 'Failed to update user privileges'}), 500
@app.route('/api/admin/users/<int:user_id>/status', methods=['PUT', 'OPTIONS'])
@godmode_required
def update_user_status(current_user, user_id):
"""Update user active status - Godmode only."""
if request.method == 'OPTIONS':
return '', 200
try:
data = request.get_json()
is_active = data.get('is_active')
if is_active is None:
return jsonify({'message': 'is_active field required'}), 400
# Prevent users from deactivating themselves
if user_id == current_user.id and not is_active:
return jsonify({'message': 'Cannot deactivate your own account'}), 400
conn = get_pg_connection()
cur = conn.cursor(cursor_factory=extras.NamedTupleCursor)
# Check if user exists
cur.execute("SELECT id, username, is_active FROM users WHERE id = %s", (user_id,))
target_user = cur.fetchone()
if not target_user:
cur.close()
conn.close()
return jsonify({'message': 'User not found'}), 404
# Update status
cur.execute("""
UPDATE users
SET is_active = %s, updated_at = CURRENT_TIMESTAMP
WHERE id = %s
""", (is_active, user_id))
conn.commit()
cur.close()
conn.close()
status_text = "activated" if is_active else "deactivated"
print(f"[*] Admin {current_user.username} {status_text} user {target_user.username}")
return jsonify({
'message': f'User {status_text} successfully',
'user_id': user_id,
'username': target_user.username,
'is_active': is_active
}), 200
except Exception as e:
print(f"[!] Error updating user status: {e}")
return jsonify({'message': 'Failed to update user status'}), 500
@app.route('/api/admin/users/<int:user_id>', methods=['GET', 'OPTIONS'])
@admin_required
def get_user_details(current_user, user_id):
"""Get detailed information about a specific user - Admin+ only."""
if request.method == 'OPTIONS':
return '', 200
try:
conn = get_pg_connection()
cur = conn.cursor(cursor_factory=extras.NamedTupleCursor)
# Get user details with statistics
cur.execute("""
SELECT
u.id,
u.username,
u.email,
u.privilege_level,
u.created_at,
u.updated_at,
u.last_login,
u.is_active,
COUNT(DISTINCT ur.id) as total_ratings,
AVG(ur.rating) as avg_rating,
COUNT(DISTINCT sa.id) as total_visits,
MAX(sa.visit_time) as last_visit
FROM users u
LEFT JOIN user_ratings ur ON u.id = ur.user_id
LEFT JOIN site_analytics sa ON u.id = sa.user_id
WHERE u.id = %s
GROUP BY u.id, u.username, u.email, u.privilege_level, u.created_at, u.updated_at, u.last_login, u.is_active
""", (user_id,))
user = cur.fetchone()
if not user:
cur.close()
conn.close()
return jsonify({'message': 'User not found'}), 404
# Get recent ratings
cur.execute("""
SELECT url, rating, created_at, updated_at
FROM user_ratings
WHERE user_id = %s
ORDER BY updated_at DESC
LIMIT 10
""", (user_id,))
recent_ratings = cur.fetchall()
# Get recent visits
cur.execute("""
SELECT page_path, visit_time, ip_address, browser, os, country, city
FROM site_analytics
WHERE user_id = %s
ORDER BY visit_time DESC
LIMIT 20
""", (user_id,))
recent_visits = cur.fetchall()
cur.close()
conn.close()
# Format response
user_data = {
'id': user.id,
'username': user.username,
'email': user.email,
'privilege_level': user.privilege_level,
'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,
'last_visit': user.last_visit.isoformat() if user.last_visit else None,
'is_active': user.is_active,
'stats': {
'total_ratings': user.total_ratings,
'avg_rating': float(user.avg_rating) if user.avg_rating else 0,
'total_visits': user.total_visits
},
'recent_ratings': [
{
'url': rating.url,
'rating': rating.rating,
'created_at': rating.created_at.isoformat(),
'updated_at': rating.updated_at.isoformat()
}
for rating in recent_ratings
],
'recent_visits': [
{
'page_path': visit.page_path,
'visit_time': visit.visit_time.isoformat(),
'ip_address': str(visit.ip_address),
'browser': visit.browser,
'os': visit.os,
'location': f"{visit.city}, {visit.country}" if visit.city and visit.country else 'Unknown'
}
for visit in recent_visits
]
}
print(f"[*] Admin {current_user.username} viewed details for user {user.username}")
return jsonify(user_data), 200
except Exception as e:
print(f"[!] Error fetching user details: {e}")
return jsonify({'message': 'Failed to fetch user details'}), 500
@app.route('/api/admin/users/<int:user_id>', methods=['DELETE', 'OPTIONS'])
@godmode_required
def delete_user(current_user, user_id):
"""Delete a user account - Godmode only."""
if request.method == 'OPTIONS':
return '', 200
try:
# Prevent users from deleting themselves
if user_id == current_user.id:
return jsonify({'message': 'Cannot delete your own account'}), 400
conn = get_pg_connection()
cur = conn.cursor(cursor_factory=extras.NamedTupleCursor)
# Check if user exists
cur.execute("SELECT id, username FROM users WHERE id = %s", (user_id,))
target_user = cur.fetchone()
if not target_user:
cur.close()
conn.close()
return jsonify({'message': 'User not found'}), 404
# Delete user (CASCADE will handle related records)
cur.execute("DELETE FROM users WHERE id = %s", (user_id,))
conn.commit()
cur.close()
conn.close()
print(f"[*] Admin {current_user.username} deleted user {target_user.username}")
return jsonify({
'message': 'User deleted successfully',
'deleted_user': target_user.username
}), 200
except Exception as e:
print(f"[!] Error deleting user: {e}")
return jsonify({'message': 'Failed to delete user'}), 500
# ═══════════════════════════════════════════════════════════════════════════════
# ANALYTICS ROUTES
# ═══════════════════════════════════════════════════════════════════════════════
@app.before_request
def handle_preflight():
if request.method == "OPTIONS":
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add('Access-Control-Allow-Headers', "Content-Type,Authorization")
response.headers.add('Access-Control-Allow-Methods', "GET,POST,PUT,DELETE,OPTIONS")
response.headers.add('Access-Control-Allow-Credentials', 'true')
return response
@app.route('/api/analytics/track', methods=['POST', 'OPTIONS'])
@optional_token
def track_analytics(current_user):
"""Track page visit analytics."""
if request.method == 'OPTIONS':
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "https://ap.projectkryptos.xyz")
response.headers.add('Access-Control-Allow-Headers', "Content-Type,Authorization")
response.headers.add('Access-Control-Allow-Methods', "POST,OPTIONS")
response.headers.add('Access-Control-Allow-Credentials', 'true')
return response
try:
data = request.get_json()
page_path = data.get('page', '/')
user_id = current_user.id if current_user else None
track_page_visit(page_path, user_id)
return jsonify({'status': 'tracked'}), 200
except Exception as e:
print(f"[!] Analytics tracking error: {e}")
return jsonify({'message': 'Tracking failed'}), 500
@app.route('/api/analytics/dashboard', methods=['GET', 'OPTIONS'])
@godmode_required
def analytics_dashboard(current_user):
"""Get analytics dashboard data - Godmode only."""
if request.method == 'OPTIONS':
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "https://ap.projectkryptos.xyz")
response.headers.add('Access-Control-Allow-Headers', "Content-Type,Authorization")
response.headers.add('Access-Control-Allow-Methods', "GET,OPTIONS")
response.headers.add('Access-Control-Allow-Credentials', 'true')
return response
try:
conn = get_pg_connection()
cur = conn.cursor(cursor_factory=extras.NamedTupleCursor)
# Get recent visits (last 100)
cur.execute("""
SELECT
sa.id,
sa.ip_address,
sa.page_path,
sa.browser,
sa.browser_version,
sa.os,
sa.device_type,
sa.country,
sa.city,
sa.visit_time,
u.username
FROM site_analytics sa
LEFT JOIN users u ON sa.user_id = u.id
ORDER BY sa.visit_time DESC
LIMIT 100
""")
recent_visits = cur.fetchall()
# Get visit statistics - UNIQUE visits only
cur.execute("""
SELECT
COUNT(DISTINCT CONCAT(COALESCE(user_id::text, ''), ip_address::text, DATE(visit_time)::text)) as total_visits,
COUNT(DISTINCT ip_address) as unique_visitors,
COUNT(DISTINCT user_id) as registered_users
FROM site_analytics
WHERE visit_time >= NOW() - INTERVAL '24 hours'
""")
daily_stats = cur.fetchone()
cur.execute("""
SELECT
COUNT(DISTINCT CONCAT(COALESCE(user_id::text, ''), ip_address::text, DATE(visit_time)::text)) as total_visits,
COUNT(DISTINCT ip_address) as unique_visitors,
COUNT(DISTINCT user_id) as registered_users
FROM site_analytics
WHERE visit_time >= NOW() - INTERVAL '7 days'
""")
weekly_stats = cur.fetchone()
# Get top countries
cur.execute("""
SELECT country, COUNT(DISTINCT CONCAT(COALESCE(user_id::text, ''), ip_address::text)) as visits
FROM site_analytics
WHERE visit_time >= NOW() - INTERVAL '7 days'
GROUP BY country
ORDER BY visits DESC
LIMIT 10
""")
top_countries = cur.fetchall()
# Get top browsers
cur.execute("""
SELECT browser, COUNT(DISTINCT CONCAT(COALESCE(user_id::text, ''), ip_address::text)) as visits
FROM site_analytics
WHERE visit_time >= NOW() - INTERVAL '7 days'
GROUP BY browser
ORDER BY visits DESC
LIMIT 10
""")
top_browsers = cur.fetchall()
# Get top pages