Demo
This commit is contained in:
0
app/utils/__init__.py
Normal file
0
app/utils/__init__.py
Normal file
17
app/utils/bcrypt_utils.py
Normal file
17
app/utils/bcrypt_utils.py
Normal file
@@ -0,0 +1,17 @@
|
||||
import bcrypt
|
||||
|
||||
def hash_password(
|
||||
password: str
|
||||
) -> bytes:
|
||||
salt = bcrypt.gensalt()
|
||||
pwd_bytes: bytes = password.encode()
|
||||
return bcrypt.hashpw(pwd_bytes, salt)
|
||||
|
||||
def validate_password(
|
||||
password: str,
|
||||
hashed_password: bytes
|
||||
) -> bool:
|
||||
return bcrypt.checkpw(
|
||||
password=password.encode(),
|
||||
hashed_password=hashed_password
|
||||
)
|
||||
30
app/utils/jwt_utlis.py
Normal file
30
app/utils/jwt_utlis.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from datetime import timedelta, datetime
|
||||
|
||||
import jwt
|
||||
from app.core.config import settings
|
||||
|
||||
def encode_jwt(payload: dict,
|
||||
private_key: str = settings.auth_jwt.private_key_path.read_text(),
|
||||
algorithm=settings.auth_jwt.algorithm,
|
||||
expire_timedelta: timedelta | None = None,
|
||||
expire_minutes: int = settings.auth_jwt.access_token_expire_minutes):
|
||||
to_encode = payload.copy()
|
||||
now = datetime.utcnow()
|
||||
if expire_timedelta:
|
||||
expire = now + timedelta
|
||||
else:
|
||||
expire = now + timedelta(minutes=expire_minutes)
|
||||
to_encode.update(
|
||||
exp=expire,
|
||||
iat=now
|
||||
)
|
||||
encoded = jwt.encode(to_encode,
|
||||
private_key,
|
||||
algorithm=algorithm)
|
||||
return encoded
|
||||
|
||||
def decode_jwt(token: str | bytes,
|
||||
public_key: str = settings.auth_jwt.public_key_path.read_text(),
|
||||
algorithm: str = settings.auth_jwt.algorithm):
|
||||
decoded = jwt.decode(token, public_key, algorithms=[algorithm])
|
||||
return decoded
|
||||
Reference in New Issue
Block a user