Update auth.py
Browse files
auth.py
CHANGED
@@ -5,7 +5,7 @@ from pydantic import BaseModel
|
|
5 |
from sqlalchemy.orm import Session
|
6 |
from models import User
|
7 |
from database import get_db
|
8 |
-
|
9 |
from passlib.context import CryptContext
|
10 |
from datetime import datetime, timedelta
|
11 |
|
@@ -59,31 +59,37 @@ class AuthViews:
|
|
59 |
db.commit()
|
60 |
return {"message": "Email verification successful"}
|
61 |
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
# Check email verification
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
|
69 |
-
|
70 |
-
|
71 |
|
72 |
# Generate an access token
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
self.SECRET_KEY,
|
77 |
-
algorithm=self.ALGORITHM,
|
78 |
-
)
|
79 |
-
return {"access_token": access_token, "token_type": "bearer"}
|
80 |
-
|
81 |
-
|
82 |
-
# Import User model and database functions
|
83 |
-
#from app.models import User
|
84 |
-
#from app.database import get_user_by_email
|
85 |
|
86 |
-
|
87 |
|
88 |
|
89 |
|
|
|
5 |
from sqlalchemy.orm import Session
|
6 |
from models import User
|
7 |
from database import get_db
|
8 |
+
import jwt
|
9 |
from passlib.context import CryptContext
|
10 |
from datetime import datetime, timedelta
|
11 |
|
|
|
59 |
db.commit()
|
60 |
return {"message": "Email verification successful"}
|
61 |
|
62 |
+
# Dependency for verifying the user's token
|
63 |
+
def get_current_user(token: str = Depends(verify_token)):
|
64 |
+
if not token:
|
65 |
+
raise HTTPException(status_code=401, detail="Token not valid")
|
66 |
+
return token
|
67 |
+
|
68 |
+
# Function to generate JWT tokens
|
69 |
+
def create_access_token(self, data: dict, expires_delta: timedelta):
|
70 |
+
to_encode = data.copy()
|
71 |
+
expire = datetime.utcnow() + expires_delta
|
72 |
+
to_encode.update({"exp": expire})
|
73 |
+
encoded_jwt = jwt.encode(to_encode, self.SECRET_KEY, algorithm=self.ALGORITHM)
|
74 |
+
return encoded_jwt
|
75 |
+
|
76 |
+
# Your login route
|
77 |
+
@app.post("/auth/login", response_model=dict)
|
78 |
+
def login(self, form_data: OAuth2PasswordRequestForm = Depends()):
|
79 |
# Check email verification
|
80 |
+
db_user = database.get_user_by_email(db, form_data.username)
|
81 |
+
if not db_user or not self.pwd_context.verify(form_data.password, db_user.hashed_password):
|
82 |
+
raise HTTPException(status_code=400, detail="Incorrect email or password")
|
83 |
|
84 |
+
if not db_user.is_verified:
|
85 |
+
raise HTTPException(status_code=400, detail="Email not verified")
|
86 |
|
87 |
# Generate an access token
|
88 |
+
access_token_expires = timedelta(minutes=self.ACCESS_TOKEN_EXPIRE_MINUTES)
|
89 |
+
access_token = create_access_token({"sub": db_user.email}, access_token_expires)
|
90 |
+
return {"access_token": access_token, "token_type": "bearer"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
|
92 |
+
|
93 |
|
94 |
|
95 |
|