Spaces:
Runtime error
Runtime error
Commit ·
4f26fae
1
Parent(s): 92f19f5
Add JWT and Bcrypt utility classes for authentication
Browse files- src/utils/__init__.py +9 -1
- src/utils/_bcrypt_util.py +17 -0
- src/utils/_jwt_util.py +20 -0
src/utils/__init__.py
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
|
|
|
|
|
| 1 |
from ._openai_client import OpenAIClient
|
| 2 |
from ._pinecone_client import PineconeClient
|
| 3 |
|
| 4 |
-
__all__ = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
__version__ = "0.1.0"
|
| 6 |
__author__ = "Ramanjit Singh"
|
|
|
|
| 1 |
+
from ._jwt_util import JWTUtil
|
| 2 |
+
from ._bcrypt_util import BcryptUtil
|
| 3 |
from ._openai_client import OpenAIClient
|
| 4 |
from ._pinecone_client import PineconeClient
|
| 5 |
|
| 6 |
+
__all__ = [
|
| 7 |
+
"JWTUtil",
|
| 8 |
+
"BcryptUtil",
|
| 9 |
+
"OpenAIClient",
|
| 10 |
+
"PineconeClient",
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
__version__ = "0.1.0"
|
| 14 |
__author__ = "Ramanjit Singh"
|
src/utils/_bcrypt_util.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import bcrypt
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class BcryptUtil:
|
| 5 |
+
@staticmethod
|
| 6 |
+
def hash_password(password: str) -> str:
|
| 7 |
+
|
| 8 |
+
salt = bcrypt.gensalt()
|
| 9 |
+
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
|
| 10 |
+
return hashed_password.decode('utf-8')
|
| 11 |
+
|
| 12 |
+
@staticmethod
|
| 13 |
+
def compare_password(stored_password: str, provided_password: str) -> bool:
|
| 14 |
+
|
| 15 |
+
stored_password = stored_password.encode('utf-8')
|
| 16 |
+
provided_password = provided_password.encode('utf-8')
|
| 17 |
+
return bcrypt.checkpw(provided_password, stored_password)
|
src/utils/_jwt_util.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import jwt
|
| 3 |
+
from datetime import datetime, timedelta
|
| 4 |
+
|
| 5 |
+
class JWTUtil:
|
| 6 |
+
def __init__(self, algorithm='HS256'):
|
| 7 |
+
self.secret_key = os.getenv('JWT_SECRET_KEY')
|
| 8 |
+
self.algorithm = algorithm
|
| 9 |
+
|
| 10 |
+
def generate_jwt(self, payload, expiration_minutes=60):
|
| 11 |
+
payload['exp'] = datetime.now() + timedelta(minutes=expiration_minutes)
|
| 12 |
+
return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)
|
| 13 |
+
|
| 14 |
+
def validate_jwt(self, token):
|
| 15 |
+
try:
|
| 16 |
+
return jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
|
| 17 |
+
except jwt.ExpiredSignatureError:
|
| 18 |
+
return None
|
| 19 |
+
except jwt.InvalidTokenError:
|
| 20 |
+
return None
|