Update auth.py
Browse files
auth.py
CHANGED
@@ -1,9 +1,5 @@
|
|
1 |
-
|
2 |
-
from fastapi import Depends, HTTPException, Form, Response, status
|
3 |
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
4 |
-
from fastapi.templating import Jinja2Templates
|
5 |
-
#from fastapi.responses import HTMLResponse
|
6 |
-
#from fastapi.requests import Request
|
7 |
from pydantic import BaseModel
|
8 |
from sqlalchemy.orm import Session
|
9 |
from models import User
|
@@ -11,19 +7,20 @@ from database import get_db
|
|
11 |
import jwt
|
12 |
from passlib.context import CryptContext
|
13 |
from datetime import datetime, timedelta
|
|
|
14 |
|
15 |
-
|
16 |
-
templates = Jinja2Templates(directory="templates")
|
17 |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
|
|
18 |
class AuthViews:
|
19 |
def __init__(self):
|
20 |
self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
21 |
self.SECRET_KEY = "your-secret-key" # Replace with your actual secret key
|
22 |
self.ALGORITHM = "HS256"
|
23 |
self.ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
|
|
24 |
def verify_token(token: str = Depends(oauth2_scheme)):
|
25 |
try:
|
26 |
-
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
27 |
return payload.get("sub")
|
28 |
except JWTError:
|
29 |
raise HTTPException(
|
@@ -31,7 +28,7 @@ def verify_token(token: str = Depends(oauth2_scheme)):
|
|
31 |
detail="Could not validate credentials",
|
32 |
headers={"WWW-Authenticate": "Bearer"},
|
33 |
)
|
34 |
-
|
35 |
class UserCreate(BaseModel):
|
36 |
username: str
|
37 |
password: str
|
@@ -39,79 +36,56 @@ class UserCreate(BaseModel):
|
|
39 |
|
40 |
def register(self, user: UserCreate, db: Session = Depends(get_db)):
|
41 |
# Validate email format and check for existing users
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
|
46 |
# Hash the password
|
47 |
-
|
48 |
|
49 |
-
# Generate a verification token
|
50 |
-
|
51 |
|
52 |
# Send a verification email (implement email.send_verification_email)
|
53 |
|
54 |
# Create the user in the database
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
|
61 |
def verify_email(self, verification_token: str, db: Session = Depends(get_db)):
|
62 |
# Verify the email using the token (implement email.verify_token)
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
|
67 |
# Get the user by email
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
|
72 |
-
|
73 |
-
|
74 |
|
75 |
# Mark the email as verified
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
|
80 |
-
# Dependency for verifying the user's token
|
81 |
def get_current_user(token: str = Depends(verify_token)):
|
82 |
if not token:
|
83 |
raise HTTPException(status_code=401, detail="Token not valid")
|
84 |
return token
|
85 |
|
86 |
-
# Function to generate JWT tokens
|
87 |
def create_access_token(self, data: dict, expires_delta: timedelta):
|
88 |
to_encode = data.copy()
|
89 |
expire = datetime.utcnow() + expires_delta
|
90 |
to_encode.update({"exp": expire})
|
91 |
-
encoded_jwt = jwt.encode(to_encode,
|
92 |
return encoded_jwt
|
93 |
|
94 |
-
# Your login route
|
95 |
-
#@app.post("/auth/login", response_model=dict)
|
96 |
-
def login(self, form_data: OAuth2PasswordRequestForm = Depends()):
|
97 |
-
# Check email verification
|
98 |
-
db_user = database.get_user_by_email(db, form_data.username)
|
99 |
-
if not db_user or not self.pwd_context.verify(form_data.password, db_user.hashed_password):
|
100 |
-
raise HTTPException(status_code=400, detail="Incorrect email or password")
|
101 |
-
|
102 |
-
if not db_user.is_verified:
|
103 |
-
raise HTTPException(status_code=400, detail="Email not verified")
|
104 |
-
|
105 |
-
# Generate an access token
|
106 |
-
access_token_expires = timedelta(minutes=self.ACCESS_TOKEN_EXPIRE_MINUTES)
|
107 |
-
access_token = create_access_token({"sub": db_user.email}, access_token_expires)
|
108 |
-
return {"access_token": access_token, "token_type": "bearer"}
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
auth_views = AuthViews()
|
115 |
|
116 |
|
117 |
|
|
|
1 |
+
from fastapi import Depends, HTTPException, Form, status
|
|
|
2 |
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
|
|
|
|
|
|
3 |
from pydantic import BaseModel
|
4 |
from sqlalchemy.orm import Session
|
5 |
from models import User
|
|
|
7 |
import jwt
|
8 |
from passlib.context import CryptContext
|
9 |
from datetime import datetime, timedelta
|
10 |
+
from jwt import JWTError
|
11 |
|
|
|
|
|
12 |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
13 |
+
auth_views = AuthViews()
|
14 |
class AuthViews:
|
15 |
def __init__(self):
|
16 |
self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
17 |
self.SECRET_KEY = "your-secret-key" # Replace with your actual secret key
|
18 |
self.ALGORITHM = "HS256"
|
19 |
self.ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
20 |
+
|
21 |
def verify_token(token: str = Depends(oauth2_scheme)):
|
22 |
try:
|
23 |
+
payload = jwt.decode(token, AuthViews().SECRET_KEY, algorithms=[AuthViews().ALGORITHM])
|
24 |
return payload.get("sub")
|
25 |
except JWTError:
|
26 |
raise HTTPException(
|
|
|
28 |
detail="Could not validate credentials",
|
29 |
headers={"WWW-Authenticate": "Bearer"},
|
30 |
)
|
31 |
+
|
32 |
class UserCreate(BaseModel):
|
33 |
username: str
|
34 |
password: str
|
|
|
36 |
|
37 |
def register(self, user: UserCreate, db: Session = Depends(get_db)):
|
38 |
# Validate email format and check for existing users
|
39 |
+
db_user = database.get_user_by_email(db, user.email)
|
40 |
+
if db_user:
|
41 |
+
raise HTTPException(status_code=400, detail="Email already registered")
|
42 |
|
43 |
# Hash the password
|
44 |
+
hashed_password = AuthViews().pwd_context.hash(user.password)
|
45 |
|
46 |
+
# Generate a verification token (you need to implement this function)
|
47 |
+
verification_token = generate_verification_token(user.email)
|
48 |
|
49 |
# Send a verification email (implement email.send_verification_email)
|
50 |
|
51 |
# Create the user in the database
|
52 |
+
user_in_db = User(email=user.email, hashed_password=hashed_password)
|
53 |
+
db.add(user_in_db)
|
54 |
+
db.commit()
|
55 |
+
db.refresh(user_in_db)
|
56 |
+
return user_in_db
|
57 |
|
58 |
def verify_email(self, verification_token: str, db: Session = Depends(get_db)):
|
59 |
# Verify the email using the token (implement email.verify_token)
|
60 |
+
email = email.verify_token(verification_token)
|
61 |
+
if not email:
|
62 |
+
raise HTTPException(status_code=400, detail="Invalid verification token")
|
63 |
|
64 |
# Get the user by email
|
65 |
+
user = database.get_user_by_email(db, email)
|
66 |
+
if not user:
|
67 |
+
raise HTTPException(status_code=400, detail="User not found")
|
68 |
|
69 |
+
if user.is_verified:
|
70 |
+
raise HTTPException(status_code=400, detail="Email already verified")
|
71 |
|
72 |
# Mark the email as verified
|
73 |
+
user.is_verified = True
|
74 |
+
db.commit()
|
75 |
+
return {"message": "Email verification successful"}
|
76 |
|
|
|
77 |
def get_current_user(token: str = Depends(verify_token)):
|
78 |
if not token:
|
79 |
raise HTTPException(status_code=401, detail="Token not valid")
|
80 |
return token
|
81 |
|
|
|
82 |
def create_access_token(self, data: dict, expires_delta: timedelta):
|
83 |
to_encode = data.copy()
|
84 |
expire = datetime.utcnow() + expires_delta
|
85 |
to_encode.update({"exp": expire})
|
86 |
+
encoded_jwt = jwt.encode(to_encode, AuthViews().SECRET_KEY, algorithm=AuthViews().ALGORITHM)
|
87 |
return encoded_jwt
|
88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
|
91 |
|