-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
951 lines (786 loc) · 37.5 KB
/
main.py
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
# main.py
import os
import sys
import json
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi import FastAPI, Request, Form, Depends, HTTPException, status, Header, Security, APIRouter
from fastapi.responses import RedirectResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.sessions import SessionMiddleware
from passlib.context import CryptContext
from datetime import datetime, timedelta, timezone
from typing import Optional, List
import jwt
import uuid
import logging
import hashlib
import base64
import urllib.parse
from db_helper import DBHelper
from models import OAuth2AuthorizationCode, UserCreate, User, UserUpdate, OAuth2Client, OAuth2ClientUpdate, \
OAuth2ClientCreate, Role, RoleCreate, Permission, PermissionCreate
from credential_manager import CredentialManager
# Configure logging to write to stdout only
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
])
class OriginLoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
origin = request.headers.get('origin')
logging.info(f"Incoming request from origin: {origin}")
response = await call_next(request)
return response
app = FastAPI()
# Add this middleware before CORSMiddleware
app.add_middleware(OriginLoggingMiddleware)
# Determine environment
environment = os.getenv('ENVIRONMENT', 'development')
# CORS configuration
# Define allowed origins based on environment
if environment == 'production':
origins = [
"https://pass.cerealsoft.com",
"https://oauthconsole.cerealsoft.com",
"https://auth.cerealsoft.com",
"https://passbackend.cerealsoft.com",
"https://aiportals.cerealsoft.com",
"https://dungeongpt.cerealsoft.com",
"https://dungeongptbackend.cerealsoft.com",
# Add other production origins if needed
]
else:
origins = [
"https://localhost:8300", # ai portals back end
"http://localhost:8300", # ai portals back end
"https://localhost:3500", # ai portals front end
"http://localhost:3500", # ai portals front end
"https://localhost:3400", # oauth console front end
"https://localhost:3300", # Frontend origin
"https://localhost:3200",
"http://localhost:3000", # If applicable, e.g., React default port
# Add other specific origins as needed
]
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # Specify allowed origins
allow_credentials=True, # Allow credentials (cookies, authorization headers)
allow_methods=["*"], # Allow all HTTP methods
allow_headers=["*"], # Allow all headers
expose_headers=["*"],
)
# Session middleware
app.add_middleware(SessionMiddleware, secret_key=CredentialManager.get_secret_key())
# Add middleware
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["*"])
# Password hashing
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# JWT configuration
SECRET_KEY = CredentialManager.get_secret_key()
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Initialize DBHelper
db_helper = DBHelper()
@app.on_event("startup")
async def startup():
await db_helper.init_db()
try:
# Existing client setup code remains unchanged
client_id_signup = 'a1b2c3d4-5678-90ab-cdef-1234567890ab'
client_secret_signup = 'b2c3d4e5-6789-01ab-cdef-2345678901bc'
redirect_uri_signup = 'http://localhost:3000/callback'
existing_client = await db_helper.get_client_by_id(client_id_signup)
if not existing_client:
await db_helper.add_client(client_id_signup, client_secret_signup, [redirect_uri_signup])
client_id_password_vault = 'a1b2c3d4-5678-90ab-cdef-1234567890ac'
client_secret_password_vault = 'b2c3d4e5-6789-01ab-cdef-2345678901bc'
redirect_uri_password_vault = None
client_id_oauth_console = 'a1b2c3d4-5678-90ab-cdef-1234567890ad'
client_secret_oauth_console = 'b2c3d4e5-6789-01ab-cdef-2345678901bc'
redirect_uri_oauth_console = None
if environment == 'production':
redirect_uri_password_vault = 'https://pass.cerealsoft.com/callback'
redirect_uri_oauth_console = 'https://oauthconsole.cerealsoft.com/callback'
redirect_uri_ai_portals = 'https://aiportals.cerealsoft.com/callback'
else:
redirect_uri_password_vault = 'https://localhost:3300/callback'
redirect_uri_oauth_console = 'https://localhost:3400/callback'
redirect_uri_ai_portals = 'https://localhost:3500/callback'
existing_client2 = await db_helper.get_client_by_id(client_id_password_vault)
logging.info(f"client 2: {existing_client2}")
existing_client3 = await db_helper.get_client_by_id(client_id_oauth_console)
logging.info(f"client 3: {existing_client3}")
# Register AI Portals frontend as a client
client_id_ai_portals = 'your_client_id'
client_secret_ai_portals = 'your_client_secret' # If applicable
existing_client4 = await db_helper.get_client_by_id(client_id_ai_portals)
if not existing_client4:
await db_helper.add_client(client_id_ai_portals, client_secret_ai_portals, [redirect_uri_ai_portals])
if not existing_client2:
await db_helper.add_client(client_id_password_vault, client_secret_password_vault, [redirect_uri_password_vault])
if not existing_client3:
await db_helper.add_client(client_id_oauth_console, client_secret_oauth_console, [redirect_uri_oauth_console])
# New code to create default admin user
# 1. Create 'admin' role if it doesn't exist
admin_role = await db_helper.get_role_by_name('admin')
if not admin_role:
await db_helper.create_role('admin')
logging.info("Created 'admin' role")
# 2. Create default admin user if it doesn't exist
admin_email = '[email protected]'
admin_password = 'adminpassword' # In production, do not hardcode passwords
existing_admin_user = await db_helper.get_user_by_email(admin_email)
if not existing_admin_user:
# Hash the password
hashed_password = get_password_hash(admin_password)
# Create UserCreate object
admin_user_create = UserCreate(email=admin_email, password=hashed_password)
# Add user to the database
await db_helper.add_user(admin_user_create)
logging.info(f"Created default admin user with email: {admin_email}")
# Retrieve the admin user (whether newly created or existing)
admin_user = await db_helper.get_user_by_email(admin_email)
# 3. Assign 'admin' role to the admin user
# Get the role and user IDs
admin_role = await db_helper.get_role_by_name('admin')
if admin_role and admin_user:
# Check if the user already has the 'admin' role
user_roles = await db_helper.get_user_roles(admin_user.id)
if 'admin' not in user_roles:
await db_helper.assign_role_to_user(admin_user.id, admin_role['id'])
logging.info(f"Assigned 'admin' role to user '{admin_email}'")
else:
logging.info(f"User '{admin_email}' already has 'admin' role")
else:
logging.error("Failed to assign 'admin' role to the default admin user")
except Exception as e:
logging.error(f"Error during startup: {e}")
# Utility 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_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta if expires_delta else timedelta(minutes=15))
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
# Dependency function to get the current user
async def get_current_user(request: Request):
user_id = request.session.get('user_id')
if user_id:
user = await db_helper.get_user_by_id(user_id)
if user:
return user
raise HTTPException(status_code=401, detail="Not authenticated")
# Routes
@app.get("/authorize")
async def authorize(request: Request,
response_type: str,
client_id: str,
redirect_uri: str,
scope: Optional[str] = None,
state: Optional[str] = None,
code_challenge: Optional[str] = None,
code_challenge_method: Optional[str] = None):
# Validate client
client = await db_helper.get_client_by_id(client_id)
if not client:
logging.error(f"Invalid client_id: {client_id}")
raise HTTPException(status_code=400, detail="Invalid client_id")
# Validate redirect_uri
if redirect_uri not in client.redirect_uris:
logging.error(f"Invalid redirect_uri: {redirect_uri}")
logging.error(f"Allowed redirect_uris: {client.redirect_uris}")
raise HTTPException(status_code=400, detail="Invalid redirect_uri")
# Check response_type
if response_type != 'code':
logging.error(f"Unsupported response_type: {response_type}")
raise HTTPException(status_code=400, detail="Unsupported response_type")
# PKCE parameters
if not code_challenge or not code_challenge_method:
logging.error("Missing PKCE parameters")
raise HTTPException(status_code=400, detail="Missing PKCE parameters")
# Parse state to extract original state and next_url
try:
state_data = json.loads(state)
original_state = state_data.get('state')
next_url = state_data.get('nextUrl')
except Exception as e:
logging.error(f"Invalid state parameter: {state}")
raise HTTPException(status_code=400, detail="Invalid state parameter")
# Check if user is authenticated
user_id = request.session.get('user_id')
if not user_id:
# Store parameters in session to use after login
request.session['auth_request'] = {
'response_type': response_type,
'client_id': client_id,
'redirect_uri': redirect_uri,
'scope': scope,
'state': original_state, # Store only the original state
'state_json': state, # Store the full state JSON string
'code_challenge': code_challenge,
'code_challenge_method': code_challenge_method,
'next_url': next_url # Store next_url separately
}
return RedirectResponse(url="/login")
else:
# User is authenticated
user = await db_helper.get_user_by_id(user_id)
if not user:
# User not found, clear session
request.session.clear()
request.session['auth_request'] = {
'response_type': response_type,
'client_id': client_id,
'redirect_uri': redirect_uri,
'scope': scope,
'state': original_state, # Store only the original state
'state_json': state, # Store the full state JSON string
'code_challenge': code_challenge,
'code_challenge_method': code_challenge_method,
'next_url': next_url # Store next_url separately
}
return RedirectResponse(url="/login")
# Generate authorization code
code = str(uuid.uuid4())
expires_at = datetime.utcnow() + timedelta(minutes=10) # Authorization code expires in 10 minutes
await db_helper.save_authorization_code(OAuth2AuthorizationCode(
code=code,
client_id=client_id,
redirect_uri=redirect_uri,
scope=scope,
user_id=user.id,
code_challenge=code_challenge,
code_challenge_method=code_challenge_method,
expires_at=expires_at
))
# Redirect back to client with authorization code
params = {'code': code}
if original_state:
params['state'] = original_state
redirect_with_params = f"{redirect_uri}?{urllib.parse.urlencode(params)}"
return RedirectResponse(url=redirect_with_params)
@app.get("/login")
async def login_get(request: Request):
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Login / Sign Up</title>
<style>
/* Include your CSS styles here */
.signup-container {
background: linear-gradient(135deg, #6e8efb, #a777e3);
max-width: 400px;
margin: 50px auto;
padding: 40px 30px;
border-radius: 10px;
box-shadow: 0 15px 25px rgba(0, 0, 0, 0.2);
color: #fff;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
animation: fadeIn 1s ease-in-out;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(-10%);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.signup-container h2 {
text-align: center;
margin-bottom: 30px;
font-size: 32px;
}
.signup-container form {
display: flex;
flex-direction: column;
}
.signup-container label {
font-size: 18px;
margin-bottom: 5px;
}
.signup-container input {
width: 100%;
padding: 12px 15px;
font-size: 16px;
border: none;
border-radius: 25px;
margin-bottom: 20px;
background: rgba(255, 255, 255, 0.1);
color: #fff;
outline: none;
}
.signup-container input::placeholder {
color: rgba(255, 255, 255, 0.7);
}
.signup-container input:focus {
background: rgba(255, 255, 255, 0.2);
}
.input-error {
border: 2px solid #ff4d4d !important;
}
.signup-container .password-toggle {
position: absolute;
right: 15px;
top: 55%;
transform: translateY(-50%);
cursor: pointer;
color: #fff;
font-size: 14px;
}
.signup-container button {
padding: 12px 15px;
font-size: 18px;
cursor: pointer;
border: none;
border-radius: 25px;
background: #fff;
color: #6e8efb;
font-weight: bold;
transition: background 0.3s, color 0.3s;
}
.signup-container button:hover {
background: #6e8efb;
color: #fff;
}
.signup-container p {
text-align: center;
font-size: 16px;
margin-top: 20px;
background: rgba(255, 255, 255, 0.1);
padding: 10px;
border-radius: 5px;
}
/* Responsive Design */
@media (max-width: 500px) {
.signup-container {
padding: 30px 20px;
margin: 20px;
}
}
</style>
</head>
<body>
<div class="signup-container">
<h2>Login / Sign Up</h2>
<form method="post" action="/login">
<label for="email">Email:</label>
<input type="email" name="email" id="email" required placeholder="Enter your email" />
<label for="password">Password:</label>
<input type="password" name="password" id="password" required placeholder="Enter your password" />
<button type="submit">Login / Sign Up</button>
</form>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content, status_code=200)
@app.post("/login")
async def login_post(request: Request, email: str = Form(...), password: str = Form(...)):
user = await db_helper.get_user_by_email(email)
if user:
if not verify_password(password, user.hashed_password):
logging.error(f"Invalid credentials for {email}")
raise HTTPException(status_code=400, detail="Invalid credentials")
else:
# Register new user
hashed_password = get_password_hash(password)
new_user = UserCreate(email=email, password=hashed_password)
await db_helper.add_user(user_in=new_user)
user = await db_helper.get_user_by_email(email)
logging.info(f"New user registered: {email}")
# Authenticate user
request.session['user_id'] = user.id
logging.info(f"User '{user.email}' authenticated successfully with user_id '{user.id}'.")
# Retrieve auth_request from session
auth_request = request.session.pop('auth_request', None)
if auth_request:
# Redirect back to /authorize with stored parameters to continue the OAuth2 flow
redirect_url = f"/authorize?response_type={urllib.parse.quote(auth_request['response_type'])}" \
f"&client_id={urllib.parse.quote(auth_request['client_id'])}" \
f"&redirect_uri={urllib.parse.quote(auth_request['redirect_uri'])}" \
f"&scope={urllib.parse.quote(auth_request['scope'] or '')}" \
f"&state={urllib.parse.quote(auth_request['state_json'] or '')}" \
f"&code_challenge={urllib.parse.quote(auth_request['code_challenge'])}" \
f"&code_challenge_method={urllib.parse.quote(auth_request['code_challenge_method'])}"
logging.info(f"Redirecting user '{user.email}' to authorization endpoint with URL: {redirect_url}")
return RedirectResponse(url=redirect_url, status_code=303)
else:
# No auth_request found, redirect to 'next_url' if present
next_url = request.session.pop('next_url', '/')
logging.info(f"Redirecting user '{user.email}' to next URL: {next_url}")
return RedirectResponse(url=next_url, status_code=303)
@app.post("/token")
async def token(request: Request,
grant_type: str = Form(...),
code: str = Form(None),
redirect_uri: str = Form(None),
client_id: str = Form(None),
code_verifier: str = Form(None)):
logging.info("Received /token request")
logging.info(f"Parameters - grant_type: {grant_type}, code: {code}, redirect_uri: {redirect_uri}, client_id: {client_id}, code_verifier: {code_verifier}")
if grant_type != 'authorization_code':
logging.error(f"Unsupported grant_type: {grant_type}")
raise HTTPException(status_code=400, detail="Unsupported grant_type")
if not code or not redirect_uri or not client_id or not code_verifier:
logging.error("Missing parameters in token request")
raise HTTPException(status_code=400, detail="Missing parameters")
# Validate client
client = await db_helper.get_client_by_id(client_id)
if not client:
logging.error(f"Invalid client_id: {client_id}")
raise HTTPException(status_code=400, detail="Invalid client_id")
# Retrieve authorization code
auth_code = await db_helper.get_authorization_code(code)
if not auth_code:
logging.error(f"Invalid or expired authorization code: {code}")
raise HTTPException(status_code=400, detail="Invalid or expired authorization code")
if auth_code['client_id'] != client_id or auth_code['redirect_uri'] != redirect_uri:
logging.error("Authorization code does not match client or redirect_uri")
raise HTTPException(status_code=400, detail="Invalid authorization code")
if auth_code['expires_at'] < datetime.now(timezone.utc):
logging.error("Authorization code has expired")
await db_helper.delete_authorization_code(code)
raise HTTPException(status_code=400, detail="Authorization code expired")
# Verify PKCE code_challenge
code_challenge_method = auth_code['code_challenge_method']
code_challenge = auth_code['code_challenge']
if code_challenge_method == 'S256':
new_code_challenge = base64.urlsafe_b64encode(
hashlib.sha256(code_verifier.encode()).digest()
).decode().rstrip("=")
elif code_challenge_method == 'plain':
new_code_challenge = code_verifier
else:
logging.error(f"Unsupported code_challenge_method: {code_challenge_method}")
raise HTTPException(status_code=400, detail="Invalid code_challenge_method")
if new_code_challenge != code_challenge:
logging.error("Invalid code_verifier")
raise HTTPException(status_code=400, detail="Invalid code_verifier")
# Generate access token
user = await db_helper.get_user_by_id(auth_code['user_id'])
access_token = create_token(
data={"sub": str(user.id), "email": user.email}, # Changed from user['id'], user['email']
expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
)
# Optionally, generate a refresh token
refresh_token = str(uuid.uuid4())
refresh_expires_at = datetime.utcnow() + timedelta(days=7)
await db_helper.save_refresh_token(user.id, refresh_token, refresh_expires_at)
# Delete authorization code
await db_helper.delete_authorization_code(code)
logging.info(f"Issued access_token and refresh_token for user_id: {user.id}")
return {
"access_token": access_token,
"token_type": "bearer",
"expires_in": ACCESS_TOKEN_EXPIRE_MINUTES * 60,
"refresh_token": refresh_token
}
@app.post("/token/refresh")
async def token_refresh(refresh_token: str = Form(...)):
# Retrieve refresh token
token_data = await db_helper.get_refresh_token(refresh_token)
if not token_data:
logging.error(f"Invalid refresh token: {refresh_token}")
raise HTTPException(status_code=400, detail="Invalid refresh token")
if token_data['expires_at'] < datetime.utcnow():
logging.error("Refresh token has expired")
await db_helper.delete_refresh_token(refresh_token)
raise HTTPException(status_code=400, detail="Refresh token expired")
# Generate new access token
user = await db_helper.get_user_by_id(token_data['user_id'])
access_token = create_token(
data={"sub": str(user.id), "email": user.email}, # Changed from user['id'], user['email']
expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
)
# Optionally, rotate refresh token
new_refresh_token = str(uuid.uuid4())
refresh_expires_at = datetime.utcnow() + timedelta(days=7)
await db_helper.save_refresh_token(user.id, new_refresh_token, refresh_expires_at)
await db_helper.delete_refresh_token(refresh_token)
return {
"access_token": access_token,
"token_type": "bearer",
"expires_in": ACCESS_TOKEN_EXPIRE_MINUTES * 60,
"refresh_token": new_refresh_token
}
async def get_token_from_header(authorization: str = Header(...)):
if authorization.startswith("Bearer "):
return authorization[len("Bearer "):]
raise HTTPException(status_code=401, detail="Invalid authorization header")
@app.get("/protected-resource")
async def protected_resource(token: str = Depends(get_token_from_header)):
# Decode and verify token
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id = payload.get("sub")
if not user_id:
raise HTTPException(status_code=401, detail="Invalid token")
user = await db_helper.get_user_by_id(int(user_id))
if not user:
raise HTTPException(status_code=401, detail="User not found")
return {"email": user.email} # Changed from user['email']
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid token")
# Additional endpoints for client registration, etc., can be added as needed
@app.post("/login_or_signup")
async def login_or_signup(request: Request, email: str = Form(...), password: str = Form(...), next: Optional[str] = None):
logging.info(f"Login/Signup attempt for {email}")
user = await db_helper.get_user_by_email(email)
if user:
# User exists, attempt to authenticate
if not verify_password(password, user.hashed_password):
logging.warning(f"Invalid password for {email}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
)
else:
logging.info(f"User {email} logged in successfully")
else:
# User does not exist, create account
hashed_password = get_password_hash(password)
try:
new_user = UserCreate(email=email, hashed_password=hashed_password)
await db_helper.add_user(user_in=new_user)
user = await db_helper.get_user_by_email(email)
logging.info(f"User {email} registered and logged in successfully")
except Exception as e:
logging.error(f"Registration error for {email}: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
# Set user in session
request.session['user_id'] = user.id
# Redirect back to the original authorization request
next_url = request.query_params.get('next') or '/'
return RedirectResponse(url=next_url)
@app.post("/logout")
async def logout(request: Request):
request.session.clear()
logging.info("User logged out successfully")
return {"msg": "Logged out successfully"}
# Example protected resource using the dependency
@app.get("/users/me")
async def read_users_me(user: User = Depends(get_current_user)): # Type hint updated
logging.info(f"User data requested for {user.email}") # Changed from user['email']
return {
"email": user.email, # Changed from user['email']
"id": user.id, # Changed from user['id']
}
# Additional endpoints for roles and permissions can be added as needed
@app.post("/roles")
async def create_role(role_name: str):
try:
await db_helper.create_role(role_name)
logging.info(f"Role '{role_name}' created successfully")
return {"msg": f"Role '{role_name}' created successfully"}
except Exception as e:
logging.error(f"Role creation error: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
@app.post("/permissions")
async def create_permission(permission_name: str):
try:
await db_helper.create_permission(permission_name)
logging.info(f"Permission '{permission_name}' created successfully")
return {"msg": f"Permission '{permission_name}' created successfully"}
except Exception as e:
logging.error(f"Permission creation error: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
@app.post("/roles/{role_name}/permissions")
async def assign_permission_to_role(role_name: str, permission_name: str):
try:
role = await db_helper.get_role_by_name(role_name)
if not role:
raise HTTPException(status_code=404, detail="Role not found")
permission = await db_helper.get_permission_by_name(permission_name)
if not permission:
raise HTTPException(status_code=404, detail="Permission not found")
await db_helper.assign_permission_to_role(role['id'], permission['id'])
logging.info(f"Assigned permission '{permission_name}' to role '{role_name}'")
return {"msg": f"Permission '{permission_name}' assigned to role '{role_name}'"}
except Exception as e:
logging.error(f"Error assigning permission to role: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
@app.post("/users/{email}/roles")
async def assign_role_to_user(email: str, role_name: str):
try:
user = await db_helper.get_user_by_email(email)
if not user:
raise HTTPException(status_code=404, detail="User not found")
role = await db_helper.get_role_by_name(role_name)
if not role:
raise HTTPException(status_code=404, detail="Role not found")
await db_helper.assign_role_to_user(user.id, role['id'])
logging.info(f"Assigned role '{role_name}' to user '{email}'")
return {"msg": f"Role '{role_name}' assigned to user '{email}'"}
except Exception as e:
logging.error(f"Error assigning role to user: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
@app.get("/users/{email}/permissions")
async def get_user_permissions(email: str):
try:
user = await db_helper.get_user_by_email(email)
if not user:
raise HTTPException(status_code=404, detail="User not found")
permission_names = await db_helper.get_user_permissions(user.id)
logging.info(f"Retrieved permissions for user '{email}'")
return {"email": email, "permissions": permission_names}
except Exception as e:
logging.error(f"Error retrieving user permissions: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
# Define security scheme
bearer_scheme = HTTPBearer()
async def get_current_active_user(token: HTTPAuthorizationCredentials = Security(bearer_scheme)):
try:
payload = jwt.decode(token.credentials, SECRET_KEY, algorithms=[ALGORITHM])
user_id = payload.get("sub")
if not user_id:
raise HTTPException(status_code=401, detail="Invalid token")
user = await db_helper.get_user_by_id(int(user_id))
if not user:
raise HTTPException(status_code=401, detail="User not found")
return user
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid token")
async def get_current_admin_user(user: User = Depends(get_current_active_user)):
# Check if the user has the 'admin' role
roles = await db_helper.get_user_roles(user.id)
if 'admin' not in roles:
raise HTTPException(status_code=403, detail="Not authorized")
return user
admin_router = APIRouter(prefix="/admin", tags=["admin"])
@admin_router.get("/users", response_model=List[User])
async def get_users(admin_user: User = Depends(get_current_admin_user)):
users = await db_helper.get_all_users()
return users
@admin_router.post("/users", response_model=User)
async def create_user(user_in: UserCreate, admin_user: User = Depends(get_current_admin_user)):
existing_user = await db_helper.get_user_by_email(user_in.email)
if existing_user:
raise HTTPException(status_code=400, detail="Email already registered")
# Hash the password
hashed_password = get_password_hash(user_in.password)
user_in.password = hashed_password
await db_helper.add_user(user_in)
user = await db_helper.get_user_by_email(user_in.email)
return user
@admin_router.put("/users/{user_id}", response_model=User)
async def update_user(user_id: int, user_in: UserUpdate, admin_user: User = Depends(get_current_admin_user)):
user = await db_helper.get_user_by_id(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
if user_in.password:
user_in.password = get_password_hash(user_in.password)
await db_helper.update_user(user_id, user_in)
updated_user = await db_helper.get_user_by_id(user_id)
return updated_user
@admin_router.delete("/users/{user_id}", response_model=dict)
async def delete_user(user_id: int, admin_user: User = Depends(get_current_admin_user)):
user = await db_helper.get_user_by_id(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
await db_helper.delete_user(user_id)
return {"detail": "User deleted successfully"}
@admin_router.get("/clients", response_model=List[OAuth2Client])
async def get_clients(admin_user: User = Depends(get_current_admin_user)):
clients = await db_helper.get_all_clients()
return clients
@admin_router.post("/clients", response_model=OAuth2Client)
async def create_client(client_data: OAuth2ClientCreate, admin_user: User = Depends(get_current_admin_user)):
existing_client = await db_helper.get_client_by_id(client_data.client_id)
if existing_client:
raise HTTPException(status_code=400, detail="Client ID already exists")
await db_helper.add_client(client_data.client_id, client_data.client_secret, client_data.redirect_uris)
new_client = await db_helper.get_client_by_id(client_data.client_id)
if not new_client:
raise HTTPException(status_code=500, detail="Failed to create new client")
return new_client
@admin_router.put("/clients/{client_id}", response_model=OAuth2Client)
async def update_client(client_id: str, client_data: OAuth2ClientUpdate, admin_user: User = Depends(get_current_admin_user)):
existing_client = await db_helper.get_client_by_id(client_id)
if not existing_client:
raise HTTPException(status_code=404, detail="Client not found")
await db_helper.update_client(client_id, client_data)
updated_client = await db_helper.get_client_by_id(client_id)
if not updated_client:
raise HTTPException(status_code=500, detail="Failed to update the client")
return updated_client
@admin_router.delete("/clients/{client_id}", response_model=dict)
async def delete_client(client_id: str, admin_user: User = Depends(get_current_admin_user)):
existing_client = await db_helper.get_client_by_id(client_id)
if not existing_client:
raise HTTPException(status_code=404, detail="Client not found")
await db_helper.delete_client(client_id)
return {"detail": "Client deleted successfully"}
@admin_router.get("/roles", response_model=List[Role])
async def get_roles(admin_user: User = Depends(get_current_admin_user)):
roles = await db_helper.get_all_roles()
return roles
@admin_router.post("/roles", response_model=Role)
async def create_role(role_in: RoleCreate, admin_user: User = Depends(get_current_admin_user)):
existing_role = await db_helper.get_role_by_name(role_in.role_name)
if existing_role:
raise HTTPException(status_code=400, detail="Role already exists")
await db_helper.create_role(role_in.role_name)
new_role = await db_helper.get_role_by_name(role_in.role_name)
return Role(**new_role)
@admin_router.delete("/roles/{role_id}", response_model=dict)
async def delete_role(role_id: int, admin_user: User = Depends(get_current_admin_user)):
await db_helper.delete_role(role_id)
return {"detail": "Role deleted successfully"}
@admin_router.get("/permissions", response_model=List[Permission])
async def get_permissions(admin_user: User = Depends(get_current_admin_user)):
permissions = await db_helper.get_all_permissions()
return permissions
@admin_router.post("/permissions", response_model=Permission)
async def create_permission(permission_in: PermissionCreate, admin_user: User = Depends(get_current_admin_user)):
existing_permission = await db_helper.get_permission_by_name(permission_in.permission_name)
if existing_permission:
raise HTTPException(status_code=400, detail="Permission already exists")
await db_helper.create_permission(permission_in.permission_name)
new_permission = await db_helper.get_permission_by_name(permission_in.permission_name)
return Permission(**new_permission)
@admin_router.delete("/permissions/{permission_id}", response_model=dict)
async def delete_permission(permission_id: int, admin_user: User = Depends(get_current_admin_user)):
await db_helper.delete_permission(permission_id)
return {"detail": "Permission deleted successfully"}
class RoleAssign(BaseModel):
role_id: int
@admin_router.post("/users/{user_id}/roles", response_model=dict)
async def assign_role_to_user(user_id: int, role_assign: RoleAssign, admin_user: User = Depends(get_current_admin_user)):
await db_helper.assign_role_to_user(user_id, role_assign.role_id)
return {"detail": "Role assigned to user successfully"}
@admin_router.delete("/users/{user_id}/roles/{role_id}", response_model=dict)
async def remove_role_from_user(user_id: int, role_id: int, admin_user: User = Depends(get_current_admin_user)):
await db_helper.remove_role_from_user(user_id, role_id)
return {"detail": "Role removed from user successfully"}
@admin_router.get("/users/{user_id}/roles", response_model=List[Role])
async def get_user_roles(user_id: int, admin_user: User = Depends(get_current_admin_user)):
roles = await db_helper.get_roles_for_user(user_id)
return [Role(**role) for role in roles]
class PermissionAssign(BaseModel):
permission_id: int
@admin_router.post("/roles/{role_id}/permissions", response_model=dict)
async def assign_permission_to_role(role_id: int, perm_assign: PermissionAssign, admin_user: User = Depends(get_current_admin_user)):
await db_helper.assign_permission_to_role(role_id, perm_assign.permission_id)
return {"detail": "Permission assigned to role successfully"}
@admin_router.delete("/roles/{role_id}/permissions/{permission_id}", response_model=dict)
async def remove_permission_from_role(role_id: int, permission_id: int, admin_user: User = Depends(get_current_admin_user)):
await db_helper.remove_permission_from_role(role_id, permission_id)
return {"detail": "Permission removed from role successfully"}
app.include_router(admin_router)