Initial commit with authentication and routes for registering/login already set up
This commit is contained in:
54
app/security.py
Normal file
54
app/security.py
Normal file
@ -0,0 +1,54 @@
|
||||
import bcrypt
|
||||
from jose import jwt, JWTError
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi import HTTPException, status
|
||||
import os
|
||||
|
||||
# Secret and algorithm for JWT
|
||||
SECRET_KEY = os.getenv('SECRET_KEY', 'your_jwt_secret_key') # Ensure this is set in your environment
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
||||
|
||||
# Hash password using bcrypt directly
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""Hashes the password using bcrypt."""
|
||||
salt = bcrypt.gensalt() # Generate a salt
|
||||
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt) # Hash the password
|
||||
return hashed_password.decode('utf-8') # Return as a string
|
||||
|
||||
# Verify password using bcrypt directly
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verifies if the plain password matches the hashed password."""
|
||||
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
|
||||
|
||||
# Create JWT token
|
||||
def create_access_token(data: dict, expires_delta: timedelta = None):
|
||||
"""Creates a JWT token with expiration time."""
|
||||
to_encode = data.copy()
|
||||
if expires_delta:
|
||||
expire = datetime.utcnow() + expires_delta
|
||||
else:
|
||||
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
# Verify JWT token
|
||||
def verify_access_token(token: str):
|
||||
"""Verifies the JWT token and returns the user_id if valid."""
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
user_id: str = payload.get("user_id")
|
||||
if user_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid token",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return user_id
|
||||
except JWTError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid token",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
Reference in New Issue
Block a user