Update app.py
Browse files
app.py
CHANGED
@@ -1,20 +1,36 @@
|
|
1 |
-
from fastapi import Depends, HTTPException, Form, status
|
2 |
from fastapi.security import OAuth2PasswordBearer
|
3 |
from pydantic import BaseModel
|
4 |
from sqlalchemy.orm import Session
|
5 |
-
from database import get_user_by_email, get_user_by_verification_token
|
6 |
from models import User
|
7 |
from passlib.context import CryptContext
|
8 |
from datetime import datetime, timedelta
|
9 |
import jwt
|
10 |
-
import os
|
11 |
from emailx import send_verification_email, generate_verification_token
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
|
|
|
|
|
|
|
|
|
14 |
SECRET_KEY = os.environ['my_secret_key']
|
15 |
ALGORITHM = "HS256"
|
16 |
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
17 |
|
|
|
|
|
|
|
|
|
18 |
# Password context
|
19 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
20 |
|
@@ -29,6 +45,45 @@ class UserCreate(BaseModel):
|
|
29 |
email: str
|
30 |
password: str
|
31 |
confirm_password: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
def create_access_token(data: dict, expires_delta: timedelta = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)):
|
34 |
to_encode = data.copy()
|
@@ -58,7 +113,7 @@ def register_user(user_data: UserCreate, db: Session):
|
|
58 |
|
59 |
hashed_password = pwd_context.hash(user_data.password)
|
60 |
verification_token = generate_verification_token(user_data.email)
|
61 |
-
reset_link = f"
|
62 |
send_verification_email(user_data.email, reset_link)
|
63 |
|
64 |
new_user = User(
|
@@ -74,7 +129,7 @@ def register_user(user_data: UserCreate, db: Session):
|
|
74 |
|
75 |
def reset_password(user: User, db: Session):
|
76 |
verification_token = generate_verification_token(user.email)
|
77 |
-
reset_link = f"
|
78 |
send_verification_email(user.email, reset_link)
|
79 |
|
80 |
user.email_verification_token = verification_token
|
|
|
|
|
1 |
from fastapi.security import OAuth2PasswordBearer
|
2 |
from pydantic import BaseModel
|
3 |
from sqlalchemy.orm import Session
|
4 |
+
from database import get_db, get_user_by_email, get_user_by_verification_token
|
5 |
from models import User
|
6 |
from passlib.context import CryptContext
|
7 |
from datetime import datetime, timedelta
|
8 |
import jwt
|
|
|
9 |
from emailx import send_verification_email, generate_verification_token
|
10 |
+
from fastapi import FastAPI, Depends, HTTPException, Request, Form, status
|
11 |
+
from fastapi.responses import RedirectResponse, HTMLResponse
|
12 |
+
from fastapi.templating import Jinja2Templates
|
13 |
+
from starlette.middleware.sessions import SessionMiddleware
|
14 |
+
from fastapi.staticfiles import StaticFiles
|
15 |
+
from authlib.integrations.starlette_client import OAuth
|
16 |
+
from typing import Optional
|
17 |
+
import httpx
|
18 |
+
import os
|
19 |
+
|
20 |
|
21 |
+
|
22 |
+
# Environment variables
|
23 |
+
SECRET_KEY1 = os.getenv('SECRET_KEY', 'default_secret')
|
24 |
+
GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')
|
25 |
+
GOOGLE_CLIENT_SECRET = os.getenv('GOOGLE_CLIENT_SECRET')
|
26 |
SECRET_KEY = os.environ['my_secret_key']
|
27 |
ALGORITHM = "HS256"
|
28 |
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
29 |
|
30 |
+
# FastAPI and OAuth setup
|
31 |
+
app = FastAPI()
|
32 |
+
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY1)
|
33 |
+
oauth = OAuth(app)
|
34 |
# Password context
|
35 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
36 |
|
|
|
45 |
email: str
|
46 |
password: str
|
47 |
confirm_password: str
|
48 |
+
# OAuth Configuration
|
49 |
+
oauth.register(
|
50 |
+
name='google',
|
51 |
+
client_id=GOOGLE_CLIENT_ID,
|
52 |
+
client_secret=GOOGLE_CLIENT_SECRET,
|
53 |
+
access_token_url='https://accounts.google.com/o/oauth2/token',
|
54 |
+
authorize_url='https://accounts.google.com/o/oauth2/auth',
|
55 |
+
api_base_url='https://www.googleapis.com/oauth2/v1/',
|
56 |
+
client_kwargs={'scope': 'openid email profile'}
|
57 |
+
)
|
58 |
+
|
59 |
+
# Static and template configurations
|
60 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
61 |
+
templates = Jinja2Templates(directory="templates")
|
62 |
+
|
63 |
+
# OAuth routes
|
64 |
+
@app.get("/login/oauth")
|
65 |
+
async def login_oauth(request: Request):
|
66 |
+
redirect_uri = request.url_for('auth_callback')
|
67 |
+
return await oauth.google.authorize_redirect(request, redirect_uri)
|
68 |
+
|
69 |
+
@app.get("/auth/callback")
|
70 |
+
async def auth_callback(request: Request, db: Session = Depends(get_db)):
|
71 |
+
token = await oauth.google.authorize_access_token(request)
|
72 |
+
user_info = await oauth.google.parse_id_token(request, token)
|
73 |
+
request.session["user_info"] = user_info
|
74 |
+
|
75 |
+
db_user = db.query(User).filter(User.email == user_info['email']).first()
|
76 |
+
if not db_user:
|
77 |
+
db_user = User(email=user_info['email'], username=user_info['name'], is_verified=True)
|
78 |
+
db.add(db_user)
|
79 |
+
db.commit()
|
80 |
+
db.refresh(db_user)
|
81 |
+
|
82 |
+
access_token = create_access_token(data={"sub": db_user.email}, expires_delta=timedelta(minutes=30))
|
83 |
+
response = RedirectResponse(url="/protected")
|
84 |
+
response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True)
|
85 |
+
return response
|
86 |
+
|
87 |
|
88 |
def create_access_token(data: dict, expires_delta: timedelta = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)):
|
89 |
to_encode = data.copy()
|
|
|
113 |
|
114 |
hashed_password = pwd_context.hash(user_data.password)
|
115 |
verification_token = generate_verification_token(user_data.email)
|
116 |
+
reset_link = f"http://gregniuki-loginauth.hf.space/verify?token={verification_token}"
|
117 |
send_verification_email(user_data.email, reset_link)
|
118 |
|
119 |
new_user = User(
|
|
|
129 |
|
130 |
def reset_password(user: User, db: Session):
|
131 |
verification_token = generate_verification_token(user.email)
|
132 |
+
reset_link = f"http://gregniuki-loginauth.hf.space/reset-password?token={verification_token}"
|
133 |
send_verification_email(user.email, reset_link)
|
134 |
|
135 |
user.email_verification_token = verification_token
|