Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
API_CONTAINER_NAME=pynews-server
.PHONY: help build up down logs test lint format clean dev prod restart health

# Colors for terminal output
Expand Down Expand Up @@ -73,3 +74,7 @@ shell: ## Entra no shell do container
setup: install build up ## Setup completo do projeto
@echo "$(GREEN)Setup completo realizado!$(NC)"
@echo "$(GREEN)Acesse: http://localhost:8000/docs$(NC)"


docker/test:
docker exec -e PYTHONPATH=/app $(API_CONTAINER_NAME) pytest -s --cov-report=term-missing --cov-report html --cov-report=xml --cov=app tests/
75 changes: 38 additions & 37 deletions app/routers/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,44 @@
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/authentication/token")


async def get_current_community(
request: Request,
token: Annotated[str, Depends(oauth2_scheme)],
) -> DBCommunity:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)

try:
payload = jwt.decode(
token, auth.SECRET_KEY, algorithms=[auth.ALGORITHM]
)
username = payload.get("sub")
if username is None:
raise credentials_exception
token_data = TokenPayload(username=username)
except InvalidTokenError:
raise credentials_exception
session: AsyncSession = request.app.db_session_factory
community = await get_community_by_username(
session=session, username=token_data.username
)
if community is None:
raise credentials_exception

return community


async def get_current_active_community(
current_user: Annotated[DBCommunity, Depends(get_current_community)],
) -> DBCommunity:
# A função simplesmente retorna o usuário.
# Pode ser estendido futuramente para verificar um status "ativo".
return current_user


def setup():
router = APIRouter(prefix="/authentication", tags=["authentication"])

Expand All @@ -31,43 +69,6 @@ async def authenticate_community(
return None
return found_community

# Teste
async def get_current_community(
request: Request,
token: Annotated[str, Depends(oauth2_scheme)],
) -> DBCommunity:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)

try:
payload = jwt.decode(
token, auth.SECRET_KEY, algorithms=[auth.ALGORITHM]
)
username = payload.get("sub")
if username is None:
raise credentials_exception
token_data = TokenPayload(username=username)
except InvalidTokenError:
raise credentials_exception
session: AsyncSession = request.app.db_session_factory
community = await get_community_by_username(
session=session, username=token_data.username
)
if community is None:
raise credentials_exception

return community

async def get_current_active_community(
current_user: Annotated[DBCommunity, Depends(get_current_community)],
) -> DBCommunity:
# A função simplesmente retorna o usuário.
# Pode ser estendido futuramente para verificar um status "ativo".
return current_user

# Teste

@router.post("/create_commumity")
Expand Down
44 changes: 36 additions & 8 deletions app/routers/news/routes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
from fastapi import APIRouter, Request, status
from typing import Annotated

from fastapi import APIRouter, Depends, Request, status
from fastapi.params import Header
from pydantic import BaseModel
from services.database.orm.news import get_news_by_query_params

from app.routers.authentication import get_current_active_community
from app.schemas import News
from app.services.database.models import Community as DBCommunity
from app.services.database.orm.news import create_news, get_news_by_query_params


class NewsPostResponse(BaseModel):
Expand All @@ -22,10 +29,22 @@ def setup():
summary="News endpoint",
description="Creates news and returns a confirmation message",
)
async def post_news():
async def post_news(
request: Request,
current_community: Annotated[
DBCommunity, Depends(get_current_active_community)
],
news: News,
user_email: str = Header(..., alias="user-email"),
):
"""
News endpoint that creates news and returns a confirmation message.
"""
news_dict = news.__dict__
news_dict["user_email"] = user_email
await create_news(
session=request.app.db_session_factory, news=news_dict
)
return NewsPostResponse()

@router.get(
Expand All @@ -35,16 +54,25 @@ async def post_news():
summary="Get News",
description="Retrieves news filtered by user and query params",
)
async def get_news(request: Request):
async def get_news(
request: Request,
current_community: Annotated[
DBCommunity, Depends(get_current_active_community)
],
id: str | None = None,
user_email: str = Header(..., alias="user-email"),
category: str | None = None,
tags: str | None = None,
):
"""
Get News endpoint that retrieves news filtered by user and query params.
"""
news_list = await get_news_by_query_params(
session=request.app.db_session_factory,
id=request.query_params.get("id"),
user_email=request.headers.get("user-email"),
category=request.query_params.get("category"),
tags=request.query_params.get("tags"),
id=id,
email=user_email,
category=category,
tags=tags,
)
return NewsGetResponse(news_list=news_list)

Expand Down
10 changes: 10 additions & 0 deletions app/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ class CommunityInDB(Community):
password: str


class News(BaseModel):
title: str
content: str
category: str
tags: str | None = None
source_url: str
social_media_url: str | None = None
likes: int = 0


class Token(BaseModel):
access_token: str
token_type: str
Expand Down
3 changes: 2 additions & 1 deletion app/services/database/models/subscriptions.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from typing import List, Optional

from schemas import SubscriptionTagEnum
from sqlalchemy import JSON, Column
from sqlmodel import Field, SQLModel

from app.schemas import SubscriptionTagEnum


class Subscription(SQLModel, table=True):
__tablename__ = "subscriptions" # type: ignore
Expand Down
28 changes: 21 additions & 7 deletions app/services/database/orm/news.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,44 @@
from typing import Optional

from services.database.models import News
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession

from app.services.database.models import News


async def create_news(session: AsyncSession, news: dict) -> None:
_news = News(
title=news["title"],
content=news["content"],
category=news["category"],
user_email=news["user_email"],
source_url=news["source_url"],
tags=news["tags"] or "",
social_media_url=news["social_media_url"] or "",
likes=news["likes"],
)
session.add(_news)
await session.commit()
await session.refresh(_news)


async def get_news_by_query_params(
session: AsyncSession,
user_email: Optional[str] = None,
email: Optional[str] = None,
category: Optional[str] = None,
tags: Optional[str] = None,
id: Optional[str] = None,
) -> list[News]:
filters = []
if user_email is not None:
filters.append(News.user_email == user_email)
if email is not None:
filters.append(News.user_email == email)
if category is not None:
filters.append(News.category == category)
if tags is not None:
filters.append(News.tags == tags)
if id is not None:
filters.append(News.id == id)

print("user_email:", user_email)
print("Filters:", filters)

statement = select(News).where(*filters)
results = await session.exec(statement)
return results.all()
46 changes: 43 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

import pytest
import pytest_asyncio
from fastapi import FastAPI
from fastapi import FastAPI, status
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlmodel import SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession

from app.main import app
from app.services.auth import hash_password
from app.services.database.models.communities import Community

# from app.main import get_db_session

Expand Down Expand Up @@ -73,8 +75,46 @@ async def async_client(test_app: FastAPI) -> AsyncGenerator[AsyncClient, None]:
yield client


class CommunityCredentials:
username: str = "community_username"
email: str = "community_name@test.com"
password: str = "community_password"
hashed_password: str = hash_password(password)


@pytest_asyncio.fixture
async def community(session: AsyncSession):
community = Community(
username=CommunityCredentials.username,
email=CommunityCredentials.email,
password=CommunityCredentials.hashed_password,
)
session.add(community)
await session.commit()
await session.refresh(community)
return community


@pytest_asyncio.fixture()
async def token(async_client: AsyncGenerator[AsyncClient, None]) -> str:
form_data = {
"grant_type": "password",
"username": CommunityCredentials.username,
"password": CommunityCredentials.password,
}
token_response = await async_client.post(
"/api/authentication/token",
data=form_data,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
assert token_response.status_code == status.HTTP_200_OK
return token_response.json()["access_token"]


@pytest.fixture
def mock_headers():
def valid_auth_headers(community: Community, token: str) -> dict[str, str]:
return {
"header1": "value1",
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"user-email": CommunityCredentials.email,
}
34 changes: 11 additions & 23 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,9 @@
import pytest
import pytest_asyncio
from fastapi import status
from httpx import AsyncClient
from services.database.models import Community
from sqlmodel.ext.asyncio.session import AsyncSession

from app.services.auth import hash_password

password = "123Asd!@#"


# gerar usuario para autenticação
@pytest_asyncio.fixture
async def community(session: AsyncSession):
hashed_password = hash_password(password)
community = Community(
username="username", email="username@test.com", password=hashed_password
)
session.add(community)
await session.commit()
await session.refresh(community)
return community
from app.services.database.models import Community
from tests.conftest import CommunityCredentials


@pytest.mark.asyncio
Expand All @@ -33,7 +16,10 @@ async def test_authentication_token_endpoint(
"""
# 1. Teste de login com credenciais válidas
# O OAuth2PasswordRequestForm espera 'username' e 'password'
form_data = {"username": community.username, "password": password}
form_data = {
"username": community.username,
"password": CommunityCredentials.password,
}

response = await async_client.post(
"/api/authentication/token",
Expand Down Expand Up @@ -66,16 +52,18 @@ async def test_authentication_token_endpoint(

@pytest.mark.asyncio
async def test_community_me_with_valid_token(
async_client: AsyncClient, community: Community
async_client: AsyncClient,
community: Community,
):
"""
Testa se o endpoint protegido /authenticate/me/ retorna os dados do usuário com um token válido.
Testa se o endpoint protegido /authenticate/me/ retorna os dados do usuário
com um token válido.
"""
# 1. Obter um token de acesso primeiro
form_data = {
"grant_type": "password",
"username": community.username,
"password": password,
"password": CommunityCredentials.password,
}
token_response = await async_client.post(
"/api/authentication/token",
Expand Down
3 changes: 2 additions & 1 deletion tests/test_communities.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import pytest
from services.database.models import Community
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession

from app.services.database.models import Community


@pytest.mark.asyncio
async def test_insert_communities(session: AsyncSession):
Expand Down
Loading