fixes
This commit is contained in:
@@ -1,10 +1,17 @@
|
|||||||
from fastapi import FastAPI
|
|
||||||
from src.web.protected_routes.routes import router as protected_router
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
from fastapi import FastAPI
|
||||||
|
|
||||||
|
from src.web.protected_routes.protected_user_action_routes import (
|
||||||
|
router as protected_user_action_routes,
|
||||||
|
)
|
||||||
|
from src.web.protected_routes.routes import router as protected_router
|
||||||
|
|
||||||
app=FastAPI(root_path="/")
|
app=FastAPI(root_path="/")
|
||||||
app.include_router(router=protected_router)
|
app.include_router(router=protected_router)
|
||||||
|
app.include_router(router=protected_user_action_routes)
|
||||||
|
|
||||||
|
|
||||||
@app.get("")
|
@app.get("")
|
||||||
def root()->dict:
|
def root()->dict:
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from sqlalchemy import and_, not_, select
|
from sqlalchemy import and_, not_, select
|
||||||
from sqlalchemy.exc import NoResultFound
|
|
||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
from src.errors.http_errors.errors import Errors
|
from src.errors.http_errors.errors import Errors
|
||||||
@@ -37,14 +36,16 @@ class JwtCrudActions:
|
|||||||
with self.Session() as session: # noqa: SIM117
|
with self.Session() as session: # noqa: SIM117
|
||||||
with session.begin():
|
with session.begin():
|
||||||
new_token=RefreshTokens(**data)
|
new_token=RefreshTokens(**data)
|
||||||
response=session.add(new_token)
|
session.add(new_token)
|
||||||
return response
|
|
||||||
|
|
||||||
def update_token(self, old_jti:UUID, new_jti:UUID)->bool:
|
def update_token(self, old_jti:UUID, new_jti:UUID)->bool:
|
||||||
with self.Session() as session: # noqa: SIM117
|
with self.Session() as session: # noqa: SIM117
|
||||||
with session.begin():
|
with session.begin():
|
||||||
query=select(RefreshTokens).where(RefreshTokens.id==old_jti)
|
query=select(RefreshTokens).where(RefreshTokens.id==old_jti)
|
||||||
response=session.scalars(query).one()
|
response = session.scalars(query).one_or_none()
|
||||||
|
if response is None:
|
||||||
|
return False
|
||||||
|
else:
|
||||||
response.is_revoked=True
|
response.is_revoked=True
|
||||||
response.replaced_by=new_jti
|
response.replaced_by=new_jti
|
||||||
return True
|
return True
|
||||||
@@ -53,14 +54,12 @@ class JwtCrudActions:
|
|||||||
with self.Session() as session: #noqa:SIM117
|
with self.Session() as session: #noqa:SIM117
|
||||||
with session.begin():
|
with session.begin():
|
||||||
new_token=RefreshTokens(**data)
|
new_token=RefreshTokens(**data)
|
||||||
session.add(new_token)
|
|
||||||
query=select(RefreshTokens).where(RefreshTokens.id==old_jti)
|
query=select(RefreshTokens).where(RefreshTokens.id==old_jti)
|
||||||
|
response = session.scalars(query).one_or_none()
|
||||||
try:
|
if response is None:
|
||||||
response = session.scalars(query).one()
|
return False
|
||||||
except NoResultFound as e:
|
else:
|
||||||
raise self.error.not_found_error(detail="Token not found") from e
|
session.add(new_token)
|
||||||
|
|
||||||
response.is_revoked=True
|
response.is_revoked=True
|
||||||
response.replaced_by=new_jti
|
response.replaced_by=new_jti
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from src.models.pydantic_models.model import UserOutDB
|
|||||||
|
|
||||||
|
|
||||||
class UsersCrudActions:
|
class UsersCrudActions:
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.Session=sessionmaker(bind=engine)
|
self.Session=sessionmaker(bind=engine)
|
||||||
|
|
||||||
|
|||||||
+15
-13
@@ -9,14 +9,14 @@ from src.errors.http_errors.errors import Errors
|
|||||||
from src.models.configs_read.env import env_settings
|
from src.models.configs_read.env import env_settings
|
||||||
from src.models.pydantic_models.model import RefreshTokensCreate, UserOut
|
from src.models.pydantic_models.model import RefreshTokensCreate, UserOut
|
||||||
|
|
||||||
from .jwt import Hashes, Jwt
|
from .jwt import HashService, JwtService
|
||||||
|
|
||||||
|
|
||||||
class CurrentUser:
|
class CurrentUserService:
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.jwt_service=Jwt()
|
self.jwt_service=JwtService()
|
||||||
self.hash=Hashes()
|
self.hash=HashService()
|
||||||
self.crud_db_actions=UsersCrudActions()
|
self.crud_db_actions=UsersCrudActions()
|
||||||
self.jwt_db_actions=JwtCrudActions()
|
self.jwt_db_actions=JwtCrudActions()
|
||||||
self.error=Errors()
|
self.error=Errors()
|
||||||
@@ -147,9 +147,12 @@ class CurrentUser:
|
|||||||
expires_at=datetime.now(UTC)+timedelta(days=env_settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
expires_at=datetime.now(UTC)+timedelta(days=env_settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.jwt_db_actions.create_and_update_token(RefreshTokensCreate.model_dump(new_token_record), old_jti, new_jti)
|
success = self.jwt_db_actions.create_and_update_token(RefreshTokensCreate.model_dump(new_token_record), old_jti, new_jti)
|
||||||
|
|
||||||
return (new_access_token,new_refresh_token)
|
if not success:
|
||||||
|
raise self.error.not_found_error(detail="Token not found")
|
||||||
|
|
||||||
|
return (new_access_token, new_refresh_token)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -163,15 +166,14 @@ class CurrentUser:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
jti=UUID(jti)
|
jti=UUID(jti)
|
||||||
except (ValueError, TypeError) as e:
|
except (ValueError, TypeError, AttributeError) as e:
|
||||||
raise self.error.credentials_error(detail="Jwt token is incorrect") from e
|
raise self.error.credentials_error(detail="Jwt token is incorrect") from e
|
||||||
|
|
||||||
current_token = self.jwt_db_actions.get_token_by_id(jti)
|
|
||||||
if current_token is None:
|
|
||||||
raise self.error.not_found_error(detail="Refresh Token Not Found")
|
|
||||||
|
|
||||||
'''logout by assigning revoked flag'''
|
'''logout by assigning revoked flag'''
|
||||||
return self.jwt_db_actions.logout(jti)
|
if self.jwt_db_actions.logout(jti):
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
raise self.error.not_found_error(detail="Refresh Token Not Found")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -186,4 +188,4 @@ class CurrentUser:
|
|||||||
|
|
||||||
return (access_token, refresh_token)
|
return (access_token, refresh_token)
|
||||||
|
|
||||||
auth=CurrentUser()
|
auth=CurrentUserService()
|
||||||
@@ -9,7 +9,7 @@ from src.errors.http_errors.errors import Errors
|
|||||||
from src.models.configs_read.env import env_settings
|
from src.models.configs_read.env import env_settings
|
||||||
|
|
||||||
'''Hash/Check hash'''
|
'''Hash/Check hash'''
|
||||||
class Hashes:
|
class HashService:
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
pass
|
pass
|
||||||
@@ -25,7 +25,7 @@ class Hashes:
|
|||||||
|
|
||||||
|
|
||||||
'''jwt'''
|
'''jwt'''
|
||||||
class Jwt:
|
class JwtService:
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
from src.database.users.crud import UsersCrudActions
|
||||||
|
from src.errors.http_errors.errors import Errors
|
||||||
|
from src.models.pydantic_models.model import UserOut
|
||||||
|
|
||||||
|
|
||||||
|
class CrudService:
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.errors=Errors()
|
||||||
|
self.crud_db_actions=UsersCrudActions()
|
||||||
|
|
||||||
|
def get_user_by_email(self, email:str)->UserOut:
|
||||||
|
user_entity=self.crud_db_actions.get_user_by_email(email)
|
||||||
|
if not user_entity:
|
||||||
|
raise self.errors.not_found_error(detail="User wasn't found")
|
||||||
|
return UserOut.model_validate(user_entity)
|
||||||
|
|
||||||
|
crud_service=CrudService()
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from src.models.pydantic_models.model import UserOut
|
||||||
|
from src.service.users_crud.users_crud import crud_service
|
||||||
|
from src.web.protected_routes.routes import get_current_user
|
||||||
|
|
||||||
|
router=APIRouter(prefix="/user")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/get_by_email")
|
||||||
|
async def get_current_user_by_email(email:str, current_user=Depends(get_current_user))->UserOut: # noqa: B008
|
||||||
|
return crud_service.get_user_by_email(email)
|
||||||
+5
-5
@@ -1,14 +1,14 @@
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from src.service.auth.jwt import Hashes, Jwt
|
from src.service.auth.jwt import HashService, JwtService
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def jwt_service()->Jwt:
|
def jwt_service()->JwtService:
|
||||||
jwt_service=Jwt()
|
jwt_service=JwtService()
|
||||||
return jwt_service
|
return jwt_service
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def hash_service()->Hashes:
|
def hash_service()->HashService:
|
||||||
hash_service=Hashes()
|
hash_service=HashService()
|
||||||
return hash_service
|
return hash_service
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from fastapi import Request
|
from fastapi import Request
|
||||||
|
|
||||||
from src.service.auth.auth import CurrentUser
|
from src.service.auth.auth import CurrentUserService
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def current_user_service()->CurrentUser:
|
def current_user_service()->CurrentUserService:
|
||||||
current_user_service=CurrentUser()
|
current_user_service=CurrentUserService()
|
||||||
return current_user_service
|
return current_user_service
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ from jose import jwt
|
|||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from src.models.configs_read.env import env_settings
|
from src.models.configs_read.env import env_settings
|
||||||
from src.service.auth.auth import CurrentUser
|
from src.service.auth.auth import CurrentUserService
|
||||||
from src.service.auth.jwt import Hashes, Jwt
|
from src.service.auth.jwt import HashService, JwtService
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.integra
|
@pytest.mark.integra
|
||||||
@@ -19,7 +19,7 @@ class TestAuth:
|
|||||||
@pytest.mark.parametrize("user_data",[
|
@pytest.mark.parametrize("user_data",[
|
||||||
pytest.param(SimpleNamespace(first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), id="correct_data")
|
pytest.param(SimpleNamespace(first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), id="correct_data")
|
||||||
])
|
])
|
||||||
def test_get_current_user_positive(self,current_user_service:CurrentUser, jwt_service:Jwt, monkeypatch, user_data:SimpleNamespace)->None:
|
def test_get_current_user_positive(self,current_user_service:CurrentUserService, jwt_service:JwtService, monkeypatch, user_data:SimpleNamespace)->None:
|
||||||
|
|
||||||
with allure.step("create token"):
|
with allure.step("create token"):
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ class TestAuth:
|
|||||||
pytest.param(SimpleNamespace(first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True),1234, HTTPException, id="wrong_id"),
|
pytest.param(SimpleNamespace(first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True),1234, HTTPException, id="wrong_id"),
|
||||||
pytest.param(SimpleNamespace(status=True),uuid4(), ValidationError,id="empty_model_data")
|
pytest.param(SimpleNamespace(status=True),uuid4(), ValidationError,id="empty_model_data")
|
||||||
])
|
])
|
||||||
def test_get_current_user_negative(self,current_user_service:CurrentUser, jwt_service:Jwt, monkeypatch, user_data:SimpleNamespace, expected_exception, uuid)->None:
|
def test_get_current_user_negative(self,current_user_service:CurrentUserService, jwt_service:JwtService, monkeypatch, user_data:SimpleNamespace, expected_exception, uuid)->None:
|
||||||
|
|
||||||
with allure.step("create token"):
|
with allure.step("create token"):
|
||||||
|
|
||||||
@@ -64,7 +64,7 @@ class TestAuth:
|
|||||||
@pytest.mark.parametrize("user_data, form_data_email,form_data_password",[
|
@pytest.mark.parametrize("user_data, form_data_email,form_data_password",[
|
||||||
pytest.param(SimpleNamespace(id=uuid4(),hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), "d@d.d", "1234", id="correct_data"),
|
pytest.param(SimpleNamespace(id=uuid4(),hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), "d@d.d", "1234", id="correct_data"),
|
||||||
])
|
])
|
||||||
def test_login_positive(self, jwt_service:Jwt,current_user_service:CurrentUser, monkeypatch, user_data:SimpleNamespace, hash_service:Hashes, form_data_email:str, form_data_password:str, requests)->None:
|
def test_login_positive(self, jwt_service:JwtService,current_user_service:CurrentUserService, monkeypatch, user_data:SimpleNamespace, hash_service:HashService, form_data_email:str, form_data_password:str, requests)->None:
|
||||||
|
|
||||||
with allure.step("patching db call functions"):
|
with allure.step("patching db call functions"):
|
||||||
|
|
||||||
@@ -90,7 +90,7 @@ class TestAuth:
|
|||||||
pytest.param(SimpleNamespace(id=uuid4(),hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=False), "d@d.d", "1234",HTTPException, id="false_status"),
|
pytest.param(SimpleNamespace(id=uuid4(),hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=False), "d@d.d", "1234",HTTPException, id="false_status"),
|
||||||
pytest.param(SimpleNamespace(id=1234,hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), "d@d.d", "1234",ValidationError, id="wrong_id"),
|
pytest.param(SimpleNamespace(id=1234,hashed_password="1234", first_name="test",last_name="test",middle_name="test",email="d@d.d",direct_permissions=[],group=[],status=True), "d@d.d", "1234",ValidationError, id="wrong_id"),
|
||||||
])
|
])
|
||||||
def test_login_negative(self, current_user_service:CurrentUser, user_data:SimpleNamespace, jwt_service:Jwt, monkeypatch, requests, hash_service:Hashes, form_data_email:str, form_data_password:str, expected_exception):
|
def test_login_negative(self, current_user_service:CurrentUserService, user_data:SimpleNamespace, jwt_service:JwtService, monkeypatch, requests, hash_service:HashService, form_data_email:str, form_data_password:str, expected_exception):
|
||||||
|
|
||||||
with allure.step("patching db call functions"):
|
with allure.step("patching db call functions"):
|
||||||
|
|
||||||
@@ -107,7 +107,7 @@ class TestAuth:
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_logout_positive(self, jwt_service:Jwt, monkeypatch, current_user_service:CurrentUser)->None:
|
def test_logout_positive(self, jwt_service:JwtService, monkeypatch, current_user_service:CurrentUserService)->None:
|
||||||
|
|
||||||
with allure.step("create fake refresh token"):
|
with allure.step("create fake refresh token"):
|
||||||
|
|
||||||
@@ -115,7 +115,6 @@ class TestAuth:
|
|||||||
|
|
||||||
with allure.step("patching db call functions"):
|
with allure.step("patching db call functions"):
|
||||||
|
|
||||||
monkeypatch.setattr(current_user_service.jwt_db_actions, "get_token_by_id", lambda jti: "test")
|
|
||||||
monkeypatch.setattr(current_user_service.jwt_db_actions, "logout", lambda jti: True )
|
monkeypatch.setattr(current_user_service.jwt_db_actions, "logout", lambda jti: True )
|
||||||
|
|
||||||
with allure.step("test logout with fake data"):
|
with allure.step("test logout with fake data"):
|
||||||
@@ -126,14 +125,13 @@ class TestAuth:
|
|||||||
@pytest.mark.parametrize("jti,db_result, expected_exception",[
|
@pytest.mark.parametrize("jti,db_result, expected_exception",[
|
||||||
pytest.param(None, True, HTTPException, id="jti_none"),
|
pytest.param(None, True, HTTPException, id="jti_none"),
|
||||||
pytest.param(1234, True, HTTPException, id="jti_int"),
|
pytest.param(1234, True, HTTPException, id="jti_int"),
|
||||||
pytest.param(str(uuid4()), None, HTTPException, id="db_result_none"),
|
pytest.param(str(uuid4()), False, HTTPException, id="db_result_none"),
|
||||||
])
|
])
|
||||||
def test_logout_negative(self, jwt_service:Jwt, monkeypatch, current_user_service:CurrentUser, expected_exception, jti, db_result)->None:
|
def test_logout_negative(self, jwt_service:JwtService, monkeypatch, current_user_service:CurrentUserService, expected_exception, jti, db_result)->None:
|
||||||
|
|
||||||
with allure.step("patching db call functions"):
|
with allure.step("patching db call functions"):
|
||||||
|
|
||||||
monkeypatch.setattr(current_user_service.jwt_db_actions, "get_token_by_id", lambda jti: db_result)
|
monkeypatch.setattr(current_user_service.jwt_db_actions, "logout", lambda jti: db_result )
|
||||||
monkeypatch.setattr(current_user_service.jwt_db_actions, "logout", lambda jti: True )
|
|
||||||
|
|
||||||
def fake_create_refresh_token(data:dict)->str:
|
def fake_create_refresh_token(data:dict)->str:
|
||||||
return jwt.encode(data, env_settings.SECRET_KEY, env_settings.ALGORITHM)
|
return jwt.encode(data, env_settings.SECRET_KEY, env_settings.ALGORITHM)
|
||||||
@@ -153,7 +151,7 @@ class TestAuth:
|
|||||||
@pytest.mark.parametrize("db_result_token, user_data_result_db", [
|
@pytest.mark.parametrize("db_result_token, user_data_result_db", [
|
||||||
pytest.param(SimpleNamespace(is_revoked=False, expires_at=datetime.now(UTC)+timedelta(days=15)),SimpleNamespace(status=True), id="correct_data")
|
pytest.param(SimpleNamespace(is_revoked=False, expires_at=datetime.now(UTC)+timedelta(days=15)),SimpleNamespace(status=True), id="correct_data")
|
||||||
])
|
])
|
||||||
def test_refresh_token_positive(self, monkeypatch, current_user_service:CurrentUser, db_result_token, requests:Request, jwt_service:Jwt,user_data_result_db )->None:
|
def test_refresh_token_positive(self, monkeypatch, current_user_service:CurrentUserService, db_result_token, requests:Request, jwt_service:JwtService,user_data_result_db )->None:
|
||||||
|
|
||||||
with allure.step("patching db call functions"):
|
with allure.step("patching db call functions"):
|
||||||
|
|
||||||
@@ -194,13 +192,12 @@ class TestAuth:
|
|||||||
pytest.param(SimpleNamespace(is_revoked=False, user_id="123",expires_at=datetime.now(UTC)+timedelta(days=15)),None,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,id="user_missing"),
|
pytest.param(SimpleNamespace(is_revoked=False, user_id="123",expires_at=datetime.now(UTC)+timedelta(days=15)),None,{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,id="user_missing"),
|
||||||
pytest.param(SimpleNamespace(is_revoked=False,user_id="123", expires_at=datetime.now(UTC)-timedelta(days=15)),SimpleNamespace(status=True),{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,id="wrong_exp")
|
pytest.param(SimpleNamespace(is_revoked=False,user_id="123", expires_at=datetime.now(UTC)-timedelta(days=15)),SimpleNamespace(status=True),{"sub":str(uuid4()), "jti":str(uuid4()), "token_type":"refresh", "exp":datetime.now(UTC)+timedelta(days=45)}, HTTPException,id="wrong_exp")
|
||||||
])
|
])
|
||||||
def test_refresh_token_negative(self, monkeypatch, current_user_service:CurrentUser, db_result_token, requests, jwt_service:Jwt,user_data_result_db, expected_exception, fake_token_data)->None:
|
def test_refresh_token_negative(self, monkeypatch, current_user_service:CurrentUserService, db_result_token, requests, jwt_service:JwtService,user_data_result_db, expected_exception, fake_token_data)->None:
|
||||||
with allure.step("patching db call functions"):
|
with allure.step("patching db call functions"):
|
||||||
monkeypatch.setattr(current_user_service.jwt_db_actions,"get_token_by_id", lambda jti: db_result_token)
|
monkeypatch.setattr(current_user_service.jwt_db_actions,"get_token_by_id", lambda jti: db_result_token)
|
||||||
monkeypatch.setattr(current_user_service.jwt_db_actions, "revoke_all", lambda user_id:True)
|
monkeypatch.setattr(current_user_service.jwt_db_actions, "revoke_all", lambda user_id:True)
|
||||||
monkeypatch.setattr(current_user_service.crud_db_actions, "get_user_by_id", lambda user:user_data_result_db)
|
monkeypatch.setattr(current_user_service.crud_db_actions, "get_user_by_id", lambda user:user_data_result_db)
|
||||||
monkeypatch.setattr(current_user_service.jwt_db_actions, "create_token", lambda new_token_record:True)
|
monkeypatch.setattr(current_user_service.jwt_db_actions, "create_and_update_token", lambda old_jti, new_jti, new_token_record:True)
|
||||||
monkeypatch.setattr(current_user_service.jwt_db_actions,"update_token", lambda old_jti, new_jti: True )
|
|
||||||
|
|
||||||
fake_request = requests
|
fake_request = requests
|
||||||
|
|
||||||
|
|||||||
+11
-11
@@ -6,7 +6,7 @@ from fastapi import HTTPException
|
|||||||
from jose import jwt
|
from jose import jwt
|
||||||
|
|
||||||
from src.models.configs_read.env import env_settings
|
from src.models.configs_read.env import env_settings
|
||||||
from src.service.auth.jwt import Hashes, Jwt
|
from src.service.auth.jwt import HashService, JwtService
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.unit
|
@pytest.mark.unit
|
||||||
@@ -15,7 +15,7 @@ class TestJwt:
|
|||||||
@pytest.mark.parametrize("data", [
|
@pytest.mark.parametrize("data", [
|
||||||
pytest.param({"sub": "123"}, id="full_sub")
|
pytest.param({"sub": "123"}, id="full_sub")
|
||||||
])
|
])
|
||||||
def test_access_create_positive(self, jwt_service:Jwt, data:dict)->None:
|
def test_access_create_positive(self, jwt_service:JwtService, data:dict)->None:
|
||||||
|
|
||||||
with allure.step("create correct access token"):
|
with allure.step("create correct access token"):
|
||||||
token = jwt_service.create_access_token(data)
|
token = jwt_service.create_access_token(data)
|
||||||
@@ -30,7 +30,7 @@ class TestJwt:
|
|||||||
pytest.param({"sub":""},HTTPException, id="empty_value"),
|
pytest.param({"sub":""},HTTPException, id="empty_value"),
|
||||||
pytest.param({"":""},HTTPException, id="empty_key_value")
|
pytest.param({"":""},HTTPException, id="empty_key_value")
|
||||||
])
|
])
|
||||||
def test_access_create_negative(self, jwt_service:Jwt, data:dict, expected_exception)->None:
|
def test_access_create_negative(self, jwt_service:JwtService, data:dict, expected_exception)->None:
|
||||||
with allure.step("create invalid access token"),pytest.raises(expected_exception):
|
with allure.step("create invalid access token"),pytest.raises(expected_exception):
|
||||||
jwt_service.create_access_token(data)
|
jwt_service.create_access_token(data)
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ class TestJwt:
|
|||||||
@pytest.mark.parametrize("data", [
|
@pytest.mark.parametrize("data", [
|
||||||
pytest.param({"sub": "123"}, id="full_sub")
|
pytest.param({"sub": "123"}, id="full_sub")
|
||||||
])
|
])
|
||||||
def test_refresh_create_positive(self, jwt_service:Jwt, data:dict)->None:
|
def test_refresh_create_positive(self, jwt_service:JwtService, data:dict)->None:
|
||||||
|
|
||||||
with allure.step("create correct access token"):
|
with allure.step("create correct access token"):
|
||||||
token = jwt_service.create_refresh_token(data)
|
token = jwt_service.create_refresh_token(data)
|
||||||
@@ -54,7 +54,7 @@ class TestJwt:
|
|||||||
pytest.param({"sub":""},HTTPException, id="empty_value"),
|
pytest.param({"sub":""},HTTPException, id="empty_value"),
|
||||||
pytest.param({"":""},HTTPException, id="empty_key_value")
|
pytest.param({"":""},HTTPException, id="empty_key_value")
|
||||||
])
|
])
|
||||||
def test_refresh_create_negative(self, jwt_service:Jwt, data, expected_exception)->None:
|
def test_refresh_create_negative(self, jwt_service:JwtService, data, expected_exception)->None:
|
||||||
with allure.step("create invalid access token"), pytest.raises(expected_exception):
|
with allure.step("create invalid access token"), pytest.raises(expected_exception):
|
||||||
jwt_service.create_refresh_token(data)
|
jwt_service.create_refresh_token(data)
|
||||||
|
|
||||||
@@ -62,7 +62,7 @@ class TestJwt:
|
|||||||
@pytest.mark.parametrize("data", [
|
@pytest.mark.parametrize("data", [
|
||||||
pytest.param({"sub": "123", "exp":datetime.now(UTC)+timedelta(minutes=15), "token_type":"access"}, id="correct_data"),
|
pytest.param({"sub": "123", "exp":datetime.now(UTC)+timedelta(minutes=15), "token_type":"access"}, id="correct_data"),
|
||||||
])
|
])
|
||||||
def test_jwt_decode_positive(self, data:dict, monkeypatch, jwt_service:Jwt)->None:
|
def test_jwt_decode_positive(self, data:dict, monkeypatch, jwt_service:JwtService)->None:
|
||||||
|
|
||||||
with allure.step("patch a create token function"):
|
with allure.step("patch a create token function"):
|
||||||
def fake_create_access_token(data:dict)->str:
|
def fake_create_access_token(data:dict)->str:
|
||||||
@@ -83,7 +83,7 @@ class TestJwt:
|
|||||||
pytest.param({}, HTTPException, id="empty_data"),
|
pytest.param({}, HTTPException, id="empty_data"),
|
||||||
pytest.param("", AttributeError, id="not_dict_data")
|
pytest.param("", AttributeError, id="not_dict_data")
|
||||||
])
|
])
|
||||||
def test_jwt_decode_invalid(self,jwt_service:Jwt, expected_exception, data, monkeypatch)->None:
|
def test_jwt_decode_invalid(self,jwt_service:JwtService, expected_exception, data, monkeypatch)->None:
|
||||||
with allure.step("patch a create token function"):
|
with allure.step("patch a create token function"):
|
||||||
def fake_create_access_token(data:dict)->str:
|
def fake_create_access_token(data:dict)->str:
|
||||||
return jwt.encode(data, env_settings.SECRET_KEY, env_settings.ALGORITHM)
|
return jwt.encode(data, env_settings.SECRET_KEY, env_settings.ALGORITHM)
|
||||||
@@ -115,7 +115,7 @@ class TestJwt:
|
|||||||
@pytest.mark.parametrize("password",[
|
@pytest.mark.parametrize("password",[
|
||||||
pytest.param("plain_password", id="correct_plain_password")
|
pytest.param("plain_password", id="correct_plain_password")
|
||||||
])
|
])
|
||||||
def test_hash_and_veryfy_positive(self, password:str, hash_service:Hashes)->None:
|
def test_hash_and_veryfy_positive(self, password:str, hash_service:HashService)->None:
|
||||||
|
|
||||||
with allure.step("encode password"):
|
with allure.step("encode password"):
|
||||||
encoded_password=hash_service.plain_to_hash(password)
|
encoded_password=hash_service.plain_to_hash(password)
|
||||||
@@ -127,7 +127,7 @@ class TestJwt:
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_verify_wrong_password(self, hash_service:Hashes)->None:
|
def test_verify_wrong_password(self, hash_service:HashService)->None:
|
||||||
|
|
||||||
with allure.step("encode password"):
|
with allure.step("encode password"):
|
||||||
encoded_password=hash_service.plain_to_hash("plain_password")
|
encoded_password=hash_service.plain_to_hash("plain_password")
|
||||||
@@ -136,9 +136,9 @@ class TestJwt:
|
|||||||
assert hash_service.verify_password("wrong_password", encoded_password) is False
|
assert hash_service.verify_password("wrong_password", encoded_password) is False
|
||||||
|
|
||||||
|
|
||||||
def test_token_to_hash_determistic(self, hash_service:Hashes)->None:
|
def test_token_to_hash_determistic(self, hash_service:HashService)->None:
|
||||||
assert hash_service.token_to_hash("abc")==hash_service.token_to_hash("abc")
|
assert hash_service.token_to_hash("abc")==hash_service.token_to_hash("abc")
|
||||||
|
|
||||||
def test_token_to_hash_different_input(self, hash_service:Hashes)->None:
|
def test_token_to_hash_different_input(self, hash_service:HashService)->None:
|
||||||
assert hash_service.token_to_hash("abc")!=hash_service.token_to_hash("xyz")
|
assert hash_service.token_to_hash("abc")!=hash_service.token_to_hash("xyz")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user