Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 61a26f8

Browse files
committed
generated file: utils/auth_utils.py
1 parent d58a300 commit 61a26f8

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎utils/auth_utils.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from datetime import datetime, timedelta
2+
import jwt
3+
from fastapi import HTTPException, status, Depends
4+
from fastapi.security import OAuth2PasswordBearer
5+
from sqlalchemy.orm import Session
6+
7+
from database import get_db
8+
from . import models, schemas
9+
from dotenv import load_dotenv
10+
11+
load_dotenv()
12+
SECRET_KEY = os.getenv("JWT_SECRET_KEY")
13+
14+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
15+
16+
def create_access_token(data: dict, expires_delta: timedelta = timedelta(minutes=15)) -> str:
17+
"""Generates a JWT access token for a user.
18+
19+
Args:
20+
data (dict): A dictionary containing user information to be encoded in the token.
21+
expires_delta (timedelta, optional): The expiration time for the token. Defaults to timedelta(minutes=15).
22+
23+
Returns:
24+
str: The encoded JWT access token.
25+
"""
26+
to_encode = data.copy()
27+
expire = datetime.utcnow() + expires_delta
28+
to_encode.update({"exp": expire})
29+
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm="HS256")
30+
return encoded_jwt
31+
32+
async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> models.User:
33+
"""Verifies the JWT token and retrieves the associated user from the database.
34+
35+
Args:
36+
token (str): The JWT token provided in the Authorization header.
37+
db (Session): The SQLAlchemy database session.
38+
39+
Returns:
40+
models.User: The user object associated with the token.
41+
42+
Raises:
43+
HTTPException: If the token is invalid, expired, or the user is not found.
44+
"""
45+
try:
46+
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
47+
user = db.query(models.User).filter(models.User.email == payload["sub"]).first()
48+
if not user:
49+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
50+
return user
51+
except jwt.ExpiredSignatureError:
52+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired")
53+
except jwt.InvalidTokenError:
54+
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /