-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
1904 lines (1604 loc) · 69.7 KB
/
main.py
File metadata and controls
1904 lines (1604 loc) · 69.7 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
from fastapi import FastAPI, Request, Depends, HTTPException, status, Form, File, UploadFile
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.staticfiles import StaticFiles
import uuid
import hashlib
import secrets
from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext
import json
from typing import Optional, List, Dict, Any
import os
from decouple import config
import time
import logging
import subprocess
import tempfile
import shutil
from collections import defaultdict
import httpx
from urllib.parse import urlencode
import base64
from fastapi import WebSocket, WebSocketDisconnect
from typing import Dict, Set
import asyncio
import json as json_lib
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="CodeShare - Code Sharing Platform")
# Security
SECRET_KEY = config("SECRET_KEY", default="your-secret-key-here")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
GOOGLE_CLIENT_ID = "-"
GOOGLE_CLIENT_SECRET = "-"
GOOGLE_REDIRECT_URI = "https://codeshare.nauval.site/auth/google/callback"
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
security = HTTPBearer()
templates = Jinja2Templates(directory="templates")
os.makedirs("data/users", exist_ok=True)
os.makedirs("data/codes", exist_ok=True)
os.makedirs("data/threads", exist_ok=True)
os.makedirs("data/notifications", exist_ok=True)
os.makedirs("data/profile_pictures", exist_ok=True)
app.mount("/profile_pictures", StaticFiles(directory="data/profile_pictures"), name="profile_pictures")
def load_json_file(filepath: str) -> Dict[str, Any]:
"""Load JSON file, return empty dict if file doesn't exist"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def save_json_file(filepath: str, data: Dict[str, Any]) -> None:
"""Save data to JSON file"""
directory = os.path.dirname(filepath)
if directory:
os.makedirs(directory, exist_ok=True)
logger.info(f"[File Debug] Directory created/verified: {directory}")
try:
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
logger.info(f"[File Debug] Successfully saved file: {filepath}")
if os.path.exists(filepath):
file_size = os.path.getsize(filepath)
logger.info(f"[File Debug] File verified - size: {file_size} bytes")
else:
logger.error(f"[File Debug] File not found after save: {filepath}")
except Exception as e:
logger.error(f"[File Debug] Error saving file {filepath}: {str(e)}")
raise
def get_user_by_username(username: str) -> Optional[Dict[str, Any]]:
"""Get user data by username"""
filepath = f"data/users/{username}.json"
user_data = load_json_file(filepath)
return user_data if user_data else None
def save_user(username: str, user_data: Dict[str, Any]) -> None:
"""Save user data"""
filepath = f"data/users/{username}.json"
save_json_file(filepath, user_data)
def get_code_by_id(code_id: str) -> Optional[Dict[str, Any]]:
"""Get code data by ID"""
filepath = f"data/codes/{code_id}.json"
code_data = load_json_file(filepath)
return code_data if code_data else None
def save_code(code_id: str, code_data: Dict[str, Any]) -> None:
"""Save code data"""
filepath = f"data/codes/{code_id}.json"
save_json_file(filepath, code_data)
def get_user_codes(username: str) -> List[Dict[str, Any]]:
"""Get all codes by user"""
codes = []
if os.path.exists("data/codes"):
for filename in os.listdir("data/codes"):
if filename.endswith(".json"):
code_data = load_json_file(f"data/codes/{filename}")
if code_data.get("author_username") == username:
codes.append(code_data)
return sorted(codes, key=lambda x: x.get("created_at", ""), reverse=True)
def get_threads_by_code_id(code_id: str) -> List[Dict[str, Any]]:
"""Get all threads for a code"""
filepath = f"data/threads/{code_id}.json"
threads_data = load_json_file(filepath)
return threads_data.get("threads", [])
def save_thread(code_id: str, thread_data: Dict[str, Any]) -> None:
"""Save thread to code"""
filepath = f"data/threads/{code_id}.json"
threads_data = load_json_file(filepath)
if "threads" not in threads_data:
threads_data["threads"] = []
threads_data["threads"].append(thread_data)
save_json_file(filepath, threads_data)
def save_uploaded_file(file: UploadFile) -> str:
"""Save uploaded file and return content"""
try:
content = file.file.read().decode('utf-8')
return content
except UnicodeDecodeError:
raise HTTPException(status_code=400, detail="File must be text-based")
def get_public_codes(limit: int = 10) -> List[Dict[str, Any]]:
"""Get recent public codes from all users"""
codes = []
if os.path.exists("data/codes"):
for filename in os.listdir("data/codes"):
if filename.endswith(".json"):
code_data = load_json_file(f"data/codes/{filename}")
# Only include public codes (not private and no password)
if not code_data.get("is_private", False) and not code_data.get("password_hash"):
codes.append(code_data)
# Sort by created_at and limit results
sorted_codes = sorted(codes, key=lambda x: x.get("created_at", ""), reverse=True)
return sorted_codes[:limit]
# Code execution functions
def execute_code(code: str, language: str) -> Dict[str, Any]:
"""Execute code and return result"""
try:
# Create temporary directory
with tempfile.TemporaryDirectory() as temp_dir:
if language.lower() == "python":
file_path = os.path.join(temp_dir, "code.py")
with open(file_path, 'w', encoding='utf-8') as f:
f.write(code)
# Execute Python code
result = subprocess.run(
["python", file_path],
capture_output=True,
text=True,
timeout=10, # 10 second timeout
cwd=temp_dir
)
return {
"success": result.returncode == 0,
"output": result.stdout,
"error": result.stderr,
"return_code": result.returncode
}
elif language.lower() == "javascript":
file_path = os.path.join(temp_dir, "code.js")
with open(file_path, 'w', encoding='utf-8') as f:
f.write(code)
# Execute JavaScript code with Node.js
result = subprocess.run(
["node", file_path],
capture_output=True,
text=True,
timeout=10,
cwd=temp_dir
)
return {
"success": result.returncode == 0,
"output": result.stdout,
"error": result.stderr,
"return_code": result.returncode
}
elif language.lower() in ["bash", "shell"]:
file_path = os.path.join(temp_dir, "code.sh")
with open(file_path, 'w', encoding='utf-8') as f:
f.write(code)
# Make executable and run
os.chmod(file_path, 0o755)
result = subprocess.run(
["bash", file_path],
capture_output=True,
text=True,
timeout=10,
cwd=temp_dir
)
return {
"success": result.returncode == 0,
"output": result.stdout,
"error": result.stderr,
"return_code": result.returncode
}
else:
return {
"success": False,
"output": "",
"error": f"Language '{language}' is not supported for execution",
"return_code": -1
}
except subprocess.TimeoutExpired:
return {
"success": False,
"output": "",
"error": "Code execution timed out (10 seconds limit)",
"return_code": -1
}
except Exception as e:
return {
"success": False,
"output": "",
"error": f"Execution error: {str(e)}",
"return_code": -1
}
# Auth functions
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
try:
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise HTTPException(status_code=401, detail="Invalid token")
return username
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
# Badge tier system functions
def calculate_user_badges(username: str) -> List[str]:
"""Calculate badges based on user activity"""
user = get_user_by_username(username)
if not user:
return ["newcomer"]
admin_badges = []
if user.get("is_admin", False):
admin_badges.append("admin")
if user.get("verified_by_admin", False):
admin_badges.append("verified")
user_codes = get_user_codes(username)
total_pastes = len(user_codes)
total_views = sum(paste.get("views", 0) for paste in user_codes)
badges = admin_badges.copy()
# Badge tiers based on activity (don't override admin badges)
if total_pastes >= 50 and total_views >= 10000:
if "legend" not in badges:
badges.append("legend")
elif total_pastes >= 25 and total_views >= 5000:
if "expert" not in badges:
badges.append("expert")
elif total_pastes >= 15 and total_views >= 2000:
if "pro" not in badges:
badges.append("pro")
elif total_pastes >= 8 and total_views >= 500:
if "verified" not in badges:
badges.append("verified")
elif total_pastes >= 3 and total_views >= 100:
if "member" not in badges:
badges.append("member")
else:
if not admin_badges: # Only add newcomer if no admin badges
badges.append("newcomer")
# Special badges
if total_views >= 1000 and "popular" not in badges:
badges.append("popular")
if total_pastes >= 10 and "prolific" not in badges:
badges.append("prolific")
return badges
def update_user_badges(username: str) -> None:
"""Update user badges based on current activity"""
user = get_user_by_username(username)
if user:
new_badges = calculate_user_badges(username)
user["badges"] = new_badges
save_user(username, user)
def get_badge_info(badge: str) -> Dict[str, str]:
"""Get badge display information"""
badge_info = {
"newcomer": {"name": "Newcomer", "color": "bg-gray-500", "icon": "🌱", "verified": False},
"member": {"name": "Member", "color": "bg-green-500", "icon": "👤", "verified": False},
"verified": {"name": "Verified", "color": "bg-blue-500", "icon": "✅", "verified": True},
"pro": {"name": "Pro", "color": "bg-purple-500", "icon": "⭐", "verified": False},
"expert": {"name": "Expert", "color": "bg-orange-500", "icon": "🏆", "verified": False},
"legend": {"name": "Legend", "color": "bg-red-500", "icon": "👑", "verified": False},
"popular": {"name": "Popular", "color": "bg-pink-500", "icon": "🔥", "verified": False},
"prolific": {"name": "Prolific", "color": "bg-indigo-500", "icon": "📝", "verified": False},
"admin": {"name": "Admin", "color": "bg-red-600", "icon": "👨💼", "verified": True}
}
return badge_info.get(badge, {"name": badge.title(), "color": "bg-gray-500", "icon": "🏅", "verified": False})
# Admin user management functions
def create_admin_user():
"""Create default admin user if not exists"""
admin_username = "admin"
admin_user = get_user_by_username(admin_username)
if not admin_user:
admin_data = {
"id": str(uuid.uuid4()),
"username": admin_username,
"email": "admin@codeshare.com",
"password_hash": get_password_hash("admin123"), # Default password
"created_at": datetime.now().isoformat(),
"badges": ["admin", "verified", "legend"],
"is_admin": True,
"verified_by_admin": True
}
save_user(admin_username, admin_data)
logger.info("Default admin user created")
def is_admin_user(username: str) -> bool:
"""Check if user is admin"""
user = get_user_by_username(username)
return user and user.get("is_admin", False)
def get_all_users() -> List[Dict[str, Any]]:
"""Get all users (admin only)"""
users = []
if os.path.exists("data/users"):
for filename in os.listdir("data/users"):
if filename.endswith(".json"):
user_data = load_json_file(f"data/users/{filename}")
if user_data:
# Remove sensitive data
safe_user = {
"username": user_data.get("username"),
"email": user_data.get("email"),
"created_at": user_data.get("created_at"),
"badges": user_data.get("badges", []),
"is_admin": user_data.get("is_admin", False),
"verified_by_admin": user_data.get("verified_by_admin", False),
"profile_picture": user_data.get("profile_picture")
}
users.append(safe_user)
return sorted(users, key=lambda x: x.get("created_at", ""), reverse=True)
def verify_user_by_admin(username: str, admin_username: str) -> bool:
"""Admin verifies a user"""
if not is_admin_user(admin_username):
return False
user = get_user_by_username(username)
if not user:
return False
user["verified_by_admin"] = True
if "verified" not in user.get("badges", []):
user["badges"].append("verified")
save_user(username, user)
return True
@app.post("/api/admin/promote-user")
async def promote_user_to_admin(
username: str = Form(...),
current_user: str = Depends(get_current_user)
):
"""Promote a user to admin (admin only)"""
if not is_admin_user(current_user):
raise HTTPException(status_code=403, detail="Admin access required")
user = get_user_by_username(username)
if not user:
raise HTTPException(status_code=404, detail="User not found")
# Promote to admin
user["is_admin"] = True
user["verified_by_admin"] = True
# Update badges
if "admin" not in user.get("badges", []):
user["badges"].append("admin")
if "verified" not in user.get("badges", []):
user["badges"].append("verified")
save_user(username, user)
return {"message": f"User {username} has been promoted to admin"}
create_admin_user()
@app.get("/health")
async def health_check():
return {"status": "healthy", "database": "json_files"}
class ConnectionManager:
def __init__(self):
self.active_connections: Dict[str, Set[WebSocket]] = {}
self.user_connections: Dict[str, WebSocket] = {}
async def connect(self, websocket: WebSocket, user_id: str):
await websocket.accept()
if user_id not in self.active_connections:
self.active_connections[user_id] = set()
self.active_connections[user_id].add(websocket)
self.user_connections[websocket] = user_id
def disconnect(self, websocket: WebSocket):
user_id = self.user_connections.get(websocket)
if user_id and user_id in self.active_connections:
self.active_connections[user_id].discard(websocket)
if not self.active_connections[user_id]:
del self.active_connections[user_id]
if websocket in self.user_connections:
del self.user_connections[websocket]
async def send_personal_message(self, message: str, user_id: str):
if user_id in self.active_connections:
for connection in self.active_connections[user_id].copy():
try:
await connection.send_text(message)
except:
self.active_connections[user_id].discard(connection)
async def broadcast_to_followers(self, message: str, user_id: str):
user = get_user_by_username(user_id)
if user and "followers" in user:
for follower in user["followers"]:
await self.send_personal_message(message, follower)
async def broadcast_global(self, message: str):
for user_connections in self.active_connections.values():
for connection in user_connections.copy():
try:
await connection.send_text(message)
except:
user_connections.discard(connection)
manager = ConnectionManager()
def create_notification(user_id: str, notification_type: str, title: str, message: str, data: Dict = None):
"""Create a notification for a user"""
notification = {
"id": str(uuid.uuid4()),
"user_id": user_id,
"type": notification_type,
"title": title,
"message": message,
"data": data or {},
"read": False,
"created_at": datetime.now().isoformat()
}
# Save notification to user's notification file
notifications_file = f"data/notifications/{user_id}.json"
os.makedirs("data/notifications", exist_ok=True)
notifications_data = load_json_file(notifications_file)
if "notifications" not in notifications_data:
notifications_data["notifications"] = []
notifications_data["notifications"].insert(0, notification)
# Keep only last 50 notifications
notifications_data["notifications"] = notifications_data["notifications"][:50]
save_json_file(notifications_file, notifications_data)
return notification
async def send_real_time_notification(user_id: str, notification: Dict):
"""Send real-time notification via WebSocket"""
message = json_lib.dumps({
"type": "notification",
"data": notification
})
await manager.send_personal_message(message, user_id)
def get_feed_for_user(username: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
"""Get feed of recent pastes from followed users"""
user = get_user_by_username(username)
if not user:
return {"pastes": [], "total": 0, "page": page, "pages": 0}
following = user.get("following", [])
if not following:
return {"pastes": [], "total": 0, "page": page, "pages": 0}
feed_pastes = []
if os.path.exists("data/codes"):
for filename in os.listdir("data/codes"):
if filename.endswith(".json"):
paste_data = load_json_file(f"data/codes/{filename}")
if paste_data and not paste_data.get("is_private", False):
author = paste_data.get("author_username", "")
if author in following:
# Add author badge details
author_user = get_user_by_username(author)
if author_user:
paste_data["author_badge_details"] = get_badge_info(author_user.get("badges", []))
paste_data["author_is_verified"] = author_user.get("verified_by_admin", False)
paste_data["author_is_admin"] = author_user.get("is_admin", False)
feed_pastes.append(paste_data)
# Sort by creation date (newest first)
feed_pastes.sort(key=lambda x: x.get("created_at", ""), reverse=True)
# Pagination
total = len(feed_pastes)
pages = (total + limit - 1) // limit
start = (page - 1) * limit
end = start + limit
return {
"pastes": feed_pastes[start:end],
"total": total,
"page": page,
"pages": pages
}
# Routes
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
return templates.TemplateResponse("login.html", {"request": request})
@app.get("/signup", response_class=HTMLResponse)
async def signup_page(request: Request):
return templates.TemplateResponse("signup.html", {"request": request})
async def get_google_user_info(access_token: str) -> Dict[str, Any]:
"""Get user info from Google using access token"""
async with httpx.AsyncClient() as client:
response = await client.get(
"https://www.googleapis.com/oauth2/v2/userinfo",
headers={"Authorization": f"Bearer {access_token}"}
)
if response.status_code == 200:
return response.json()
else:
raise HTTPException(status_code=400, detail="Failed to get user info from Google")
async def exchange_code_for_token(code: str) -> str:
"""Exchange authorization code for access token"""
async with httpx.AsyncClient() as client:
data = {
"client_id": GOOGLE_CLIENT_ID,
"client_secret": GOOGLE_CLIENT_SECRET,
"code": code,
"grant_type": "authorization_code",
"redirect_uri": GOOGLE_REDIRECT_URI,
}
response = await client.post("https://oauth2.googleapis.com/token", data=data)
if response.status_code == 200:
token_data = response.json()
return token_data["access_token"]
else:
raise HTTPException(status_code=400, detail="Failed to exchange code for token")
def create_user_from_google(google_user: Dict[str, Any]) -> Dict[str, Any]:
"""Create a new user from Google OAuth data"""
base_username = google_user["email"].split("@")[0]
username = base_username
# Ensure username is unique
counter = 1
while get_user_by_username(username):
username = f"{base_username}{counter}"
counter += 1
logger.info(f"[User Debug] Creating user with username: {username}")
user_id = str(uuid.uuid4())
user_data = {
"id": user_id,
"username": username,
"email": google_user["email"],
"google_id": google_user["id"],
"name": google_user.get("name", ""),
"picture": google_user.get("picture", ""),
"created_at": datetime.now().isoformat(),
"badges": ["newcomer", "google_user"],
"is_admin": False,
"verified_by_admin": True, # Auto-verify Google users
"auth_provider": "google"
}
logger.info(f"[User Debug] User data prepared: {json.dumps(user_data, indent=2)}")
try:
save_user(username, user_data)
logger.info(f"[User Debug] User {username} saved successfully")
saved_user = get_user_by_username(username)
if saved_user:
logger.info(f"[User Debug] Verification: User {username} found in database")
else:
logger.error(f"[User Debug] Verification failed: User {username} not found after save!")
except Exception as e:
logger.error(f"[User Debug] Error saving user {username}: {str(e)}")
raise
return user_data
@app.get("/auth/google")
async def google_login():
"""Redirect to Google OAuth"""
params = {
"client_id": GOOGLE_CLIENT_ID,
"redirect_uri": GOOGLE_REDIRECT_URI,
"scope": "openid email profile",
"response_type": "code",
"access_type": "offline",
"prompt": "consent"
}
google_auth_url = f"https://accounts.google.com/o/oauth2/auth?{urlencode(params)}"
return RedirectResponse(url=google_auth_url)
@app.get("/auth/google/callback")
async def google_callback(request: Request, code: str = None, error: str = None):
"""Handle Google OAuth callback"""
logger.info(f"[OAuth Debug] Callback received - code: {'present' if code else 'missing'}, error: {error}")
if error:
logger.error(f"[OAuth Debug] OAuth error received: {error}")
return RedirectResponse(url="/login?error=access_denied")
if not code:
logger.error("[OAuth Debug] No authorization code received")
return RedirectResponse(url="/login?error=no_code")
try:
logger.info("[OAuth Debug] Exchanging code for access token...")
access_token = await exchange_code_for_token(code)
logger.info("[OAuth Debug] Access token obtained successfully")
logger.info("[OAuth Debug] Getting user info from Google...")
google_user = await get_google_user_info(access_token)
logger.info(f"[OAuth Debug] Google user info: email={google_user.get('email')}, id={google_user.get('id')}")
existing_user = None
logger.info("[OAuth Debug] Checking for existing user...")
for filename in os.listdir("data/users"):
if filename.endswith(".json"):
user_data = load_json_file(f"data/users/{filename}")
if user_data and (
user_data.get("google_id") == google_user["id"] or
user_data.get("email") == google_user["email"]
):
existing_user = user_data
logger.info(f"[OAuth Debug] Found existing user: {user_data.get('username')}")
break
if existing_user:
if not existing_user.get("google_id"):
logger.info("[OAuth Debug] Updating existing user with Google info...")
existing_user["google_id"] = google_user["id"]
existing_user["picture"] = google_user.get("picture", "")
existing_user["auth_provider"] = "google"
save_user(existing_user["username"], existing_user)
logger.info(f"[OAuth Debug] Updated user {existing_user['username']} saved successfully")
username = existing_user["username"]
else:
# Create new user
logger.info("[OAuth Debug] Creating new user from Google data...")
user_data = create_user_from_google(google_user)
username = user_data["username"]
logger.info(f"[OAuth Debug] New user created: {username}")
saved_user = get_user_by_username(username)
if saved_user:
logger.info(f"[OAuth Debug] User {username} successfully saved to data/users/{username}.json")
else:
logger.error(f"[OAuth Debug] Failed to save user {username} to database!")
# Create JWT token
logger.info(f"[OAuth Debug] Creating JWT token for user: {username}")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
jwt_token = create_access_token(
data={"sub": username}, expires_delta=access_token_expires
)
logger.info("[OAuth Debug] JWT token created successfully")
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<title>Login Successful</title>
<style>
body {{
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f5f5f5;
}}
.container {{
text-align: center;
background: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}}
.spinner {{
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 0 auto 1rem;
}}
@keyframes spin {{
0% {{ transform: rotate(0deg); }}
100% {{ transform: rotate(360deg); }}
}}
</style>
</head>
<body>
<div class="container">
<div class="spinner"></div>
<h2>Login Berhasil!</h2>
<p>Mengarahkan ke dashboard...</p>
</div>
<script>
// Store token in localStorage
localStorage.setItem('token', '{jwt_token}');
// Redirect to dashboard after short delay
setTimeout(function() {{
window.location.href = '/dashboard';
}}, 1500);
</script>
</body>
</html>
"""
logger.info("[OAuth Debug] Returning inline HTML response with token")
return HTMLResponse(content=html_content)
except Exception as e:
logger.error(f"[OAuth Debug] Google OAuth error: {str(e)}")
logger.error(f"[OAuth Debug] Exception type: {type(e).__name__}")
import traceback
logger.error(f"[OAuth Debug] Traceback: {traceback.format_exc()}")
return RedirectResponse(url="/login?error=oauth_failed")
# @app.get("/auth/success")
# async def auth_success(request: Request):
# """OAuth success page that handles token storage"""
# return templates.TemplateResponse("auth_success.html", {"request": request})
@app.post("/api/signup")
async def signup(
username: str = Form(...),
email: str = Form(...),
password: str = Form(...)
):
# Check if user exists
existing_user = get_user_by_username(username)
if existing_user:
raise HTTPException(status_code=400, detail="Username already exists")
# Create user
user_id = str(uuid.uuid4())
password_hash = get_password_hash(password)
user_data = {
"id": user_id,
"username": username,
"email": email,
"password_hash": password_hash,
"created_at": datetime.now().isoformat(),
"badges": ["newcomer"],
"is_admin": False,
"verified_by_admin": False,
"auth_provider": "local",
"profile_picture": None
}
save_user(username, user_data)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.post("/api/login")
async def login(
username: str = Form(...),
password: str = Form(...)
):
user = get_user_by_username(username)
if not user or not verify_password(password, user["password_hash"]):
raise HTTPException(status_code=401, detail="Invalid credentials")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/create", response_class=HTMLResponse)
async def create_paste_page(request: Request):
return templates.TemplateResponse("create.html", {"request": request})
@app.get("/edit/{paste_id}", response_class=HTMLResponse)
async def edit_paste_page(request: Request, paste_id: str):
"""Serve the edit page for a specific paste"""
return templates.TemplateResponse("edit.html", {
"request": request,
"paste_id": paste_id
})
@app.post("/api/paste")
async def create_paste(
title: str = Form(...),
content: str = Form(default=""),
language: str = Form(default="text"),
is_private: bool = Form(default=False),
password: Optional[str] = Form(default=None),
file: Optional[UploadFile] = File(default=None),
current_user: str = Depends(get_current_user)
):
paste_id = str(uuid.uuid4())
password_hash = get_password_hash(password) if password else None
# Handle file upload
final_content = content
if file and file.filename:
try:
file_content = save_uploaded_file(file)
final_content = file_content if not content else content + "\n\n" + file_content
if language == "text" and file.filename:
ext = file.filename.split('.')[-1].lower()
language_map = {
# Bahasa pemrograman populer
'py': 'python',
'js': 'javascript',
'ts': 'typescript',
'html': 'html',
'htm': 'html',
'css': 'css',
'java': 'java',
'cpp': 'cpp',
'c': 'c',
'cs': 'csharp',
'rb': 'ruby',
'php': 'php',
'go': 'go',
'rs': 'rust',
'kt': 'kotlin',
'swift': 'swift',
'scala': 'scala',
'dart': 'dart',
# Data & config
'sql': 'sql',
'json': 'json',
'xml': 'xml',
'yml': 'yaml',
'yaml': 'yaml',
'toml': 'toml',
'ini': 'ini',
'cfg': 'ini',
'env': 'dotenv',
# Shell & scripting
'sh': 'bash',
'bash': 'bash',
'ps1': 'powershell',
'bat': 'batch',
'cmd': 'batch',
# Markup & docs
'md': 'markdown',
'markdown': 'markdown',
'rst': 'rst',
'tex': 'latex',
'latex': 'latex',
# Web & template
'vue': 'vue',
'svelte': 'svelte',
'jsx': 'jsx',
'tsx': 'tsx',
'ejs': 'ejs',
'twig': 'twig',
'jinja': 'jinja',
# Tambahan lain
'pl': 'perl',
'lua': 'lua',
'r': 'r',
'erl': 'erlang',
'ex': 'elixir',
'clj': 'clojure',
'hs': 'haskell',
'ml': 'ocaml'
}
language = language_map.get(ext, 'text')
except Exception as e:
raise HTTPException(status_code=400, detail=f"Error processing file: {str(e)}")
# Get user info
user = get_user_by_username(current_user)
if not user:
raise HTTPException(status_code=404, detail="User not found")
paste_data = {
"id": paste_id,
"title": title,
"content": final_content,
"language": language,
"author_id": user["id"],
"author_username": current_user,
"is_private": is_private,
"password_hash": password_hash,
"views": 0,
"created_at": datetime.now().isoformat(),
"expires_at": None
}
save_code(paste_id, paste_data)
update_user_badges(current_user)
if not is_private: