Skip to content

Commit

Permalink
Merge branch 'main' into dependabot/pip/pydantic-1.10.1
Browse files Browse the repository at this point in the history
  • Loading branch information
Segelzwerg authored Sep 1, 2022
2 parents 3f3a823 + 73f717d commit 8ce86c6
Show file tree
Hide file tree
Showing 14 changed files with 52 additions and 75 deletions.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from whist_core.error.table_error import TableNotReadyError, PlayerNotJoinedError

from tests.whist_server.api.game.base_created_case import BaseCreateGameTestCase
from tests.whist_server.api.room.base_created_case import BaseCreateGameTestCase
from whist_server.database.error import PlayerNotCreatorError
from whist_server.services.error import RoomNotFoundError
from whist_server.services.error import UserNotReadyError
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from unittest.mock import MagicMock

from tests.whist_server.api.game.base_created_case import BaseCreateGameTestCase
from tests.whist_server.api.room.base_created_case import BaseCreateGameTestCase
from whist_server.database.room import RoomInfo
from whist_server.services.error import RoomNotFoundError

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import pytest
from starlette.testclient import TestClient

from tests.whist_server.api.game.base_created_case import BaseCreateGameTestCase
from tests.whist_server.api.room.base_created_case import BaseCreateGameTestCase
from whist_server import app
from whist_server.database import db
from whist_server.database.warning import PlayerAlreadyJoinedWarning
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from whist_core.game.errors import NotPlayersTurnError
from whist_core.game.warnings import TrickNotDoneWarning

from tests.whist_server.api.game.base_created_case import BaseCreateGameTestCase
from tests.whist_server.api.room.base_created_case import BaseCreateGameTestCase


class TrickTestCase(BaseCreateGameTestCase):
Expand Down
39 changes: 8 additions & 31 deletions whist_server/api/room/action.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"""Route to interaction with a table."""
from typing import Optional

from fastapi import APIRouter, BackgroundTasks, Depends, Security, HTTPException, status
from fastapi import APIRouter, BackgroundTasks, Depends, Security, status
from pydantic import BaseModel
from whist_core.error.table_error import PlayerNotJoinedError, TableNotReadyError
from whist_core.session.matcher import RandomMatcher, RoundRobinMatcher, Matcher
from whist_core.user.player import Player

from whist_server.api.util import create_http_error
from whist_server.database.error import PlayerNotCreatorError
from whist_server.database.room import RoomInDb
from whist_server.services.authentication import get_current_user
Expand Down Expand Up @@ -61,18 +62,10 @@ def start_room(room_id: str, model: StartModel, background_tasks: BackgroundTask
background_tasks.add_task(channel_service.notify, room_id, RoomStartedEvent())
except PlayerNotCreatorError as start_exception:
message = 'Player has not administrator rights at this table.'
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=message,
headers={"WWW-Authenticate": "Bearer"},
) from start_exception
raise create_http_error(message, status.HTTP_403_FORBIDDEN) from start_exception
except TableNotReadyError as ready_error:
message = 'At least one player is not ready and therefore the table cannot be started'
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=message,
headers={"WWW-Authenticate": "Bearer"},
) from ready_error
raise create_http_error(message, status.HTTP_400_BAD_REQUEST) from ready_error
else:
return {'status': 'started'}

Expand All @@ -97,11 +90,7 @@ def ready_player(room_id: str, user: Player = Security(get_current_user),
room_service.save(room)
except PlayerNotJoinedError as ready_error:
message = 'Player has not joined the table yet.'
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=message,
headers={"WWW-Authenticate": "Bearer"},
) from ready_error
raise create_http_error(message, status.HTTP_403_FORBIDDEN) from ready_error
return {'status': f'{user.username} is ready'}


Expand All @@ -127,23 +116,11 @@ def unready_player(room_id: str, user: Player = Security(get_current_user),
room_service.save(room)
except PlayerNotJoinedError as join_error:
message = 'Player not joined yet.'
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=message,
headers={"WWW-Authenticate": "Bearer"},
) from join_error
raise create_http_error(message, status.HTTP_403_FORBIDDEN) from join_error
except RoomNotFoundError as room_error:
message = 'Room id not found'
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=message,
headers={"WWW-Authenticate": "Bearer"},
) from room_error
raise create_http_error(message, status.HTTP_404_NOT_FOUND) from room_error
except UserNotReadyError as ready_error:
message = 'Player not ready'
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=message,
headers={"WWW-Authenticate": "Bearer"},
) from ready_error
raise create_http_error(message, status.HTTP_400_BAD_REQUEST) from ready_error
return {'status': f'{user.username} is unready'}
19 changes: 8 additions & 11 deletions whist_server/api/room/info.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Collection of general room information getter."""
from fastapi import APIRouter, Depends, HTTPException, Security, status
from fastapi import APIRouter, Depends, Security, status
from whist_core.user.player import Player

from whist_server.api.util import create_http_error
from whist_server.database.room import RoomInDb, RoomInfo
from whist_server.services.authentication import get_current_user
from whist_server.services.error import RoomNotFoundError
Expand Down Expand Up @@ -34,9 +35,8 @@ def room_info(room_id: str, room_service=Depends(RoomDatabaseService)) -> RoomIn
try:
room = room_service.get(room_id)
except RoomNotFoundError as not_found:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Room not found with id: {room_id}',
headers={"WWW-Authenticate": "Bearer"}, ) from not_found
message = f'Room not found with id: {room_id}'
raise create_http_error(message, status.HTTP_400_BAD_REQUEST) from not_found
return room.get_info()


Expand All @@ -55,12 +55,9 @@ def room_id_from_name(room_name: str, room_service=Depends(RoomDatabaseService),
try:
room: RoomInDb = room_service.get_by_name(room_name)
if not room.has_joined(user):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
detail='User has not access.',
headers={"WWW-Authenticate": "Bearer"},
)
message = 'User has not access.'
raise create_http_error(message, status.HTTP_403_FORBIDDEN)
except RoomNotFoundError as not_found:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Room not found with name: {room_name}',
headers={"WWW-Authenticate": "Bearer"}, ) from not_found
message = f'Room not found with name: {room_name}'
raise create_http_error(message, status.HTTP_400_BAD_REQUEST) from not_found
return {'id': str(room.id)}
10 changes: 4 additions & 6 deletions whist_server/api/room/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
"""
from typing import Optional

from fastapi import APIRouter, BackgroundTasks, HTTPException, Security, status, Depends
from fastapi import APIRouter, BackgroundTasks, Security, status, Depends
from pydantic import BaseModel
from whist_core.user.player import Player

from whist_server.api.util import create_http_error
from whist_server.database.warning import PlayerAlreadyJoinedWarning
from whist_server.services.authentication import get_current_user
from whist_server.services.channel_service import ChannelService
Expand Down Expand Up @@ -47,11 +48,8 @@ def join_game(room_id: str, request: JoinRoomArgs, background_tasks: BackgroundT
if room.hashed_password is not None and (
request.password is None or not pwd_service.verify(request.password,
room.hashed_password)):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Wrong room password.",
headers={"WWW-Authenticate": "Bearer"},
)
message = "Wrong room password."
raise create_http_error(message, status.HTTP_401_UNAUTHORIZED)
try:
room.join(user)
room_service.save(room)
Expand Down
13 changes: 6 additions & 7 deletions whist_server/api/room/trick.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import Union

from fastapi import APIRouter, BackgroundTasks, Security, Depends
from fastapi import HTTPException, status
from fastapi import status
from whist_core.cards.card import Card
from whist_core.cards.card_container import OrderedCardContainer
from whist_core.cards.card_container import UnorderedCardContainer
Expand All @@ -11,6 +11,7 @@
from whist_core.game.warnings import TrickNotDoneWarning
from whist_core.user.player import Player

from whist_server.api.util import create_http_error
from whist_server.services.authentication import get_current_user
from whist_server.services.channel_service import ChannelService
from whist_server.services.room_db_service import RoomDatabaseService
Expand Down Expand Up @@ -67,9 +68,8 @@ def play_card(room_id: str, card: Card, background_tasks: BackgroundTasks,
background_tasks.add_task(channel_service.notify, room_id,
TrickDoneEvent(winner=trick.winner))
except NotPlayersTurnError as turn_error:
raise HTTPException(detail=f'It is not {user.username}\'s turn',
status_code=status.HTTP_400_BAD_REQUEST,
headers={"WWW-Authenticate": "Bearer"}) from turn_error
message = f'It is not {user.username}\'s turn'
raise create_http_error(message, status.HTTP_400_BAD_REQUEST) from turn_error
return trick.stack


Expand All @@ -88,9 +88,8 @@ def get_winner(room_id: str, user: Player = Security(get_current_user),
"""
room = room_service.get(room_id)
if user not in room.players:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
headers={'WWW-Authenticate': 'Bearer'},
detail='You have not joined the table.')
message = 'You have not joined the table.'
raise create_http_error(message, status.HTTP_403_FORBIDDEN)

trick = room.current_trick()
try:
Expand Down
14 changes: 4 additions & 10 deletions whist_server/api/user/auth.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""User authentication."""

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, status
from fastapi.security import OAuth2PasswordRequestForm

from whist_server.api.util import create_http_error
from whist_server.database.access_token import AccessToken
from whist_server.services import authentication
from whist_server.services.authentication import create_access_token
Expand All @@ -24,16 +25,9 @@ async def auth(request: OAuth2PasswordRequestForm = Depends()):

try:
if not await authentication.check_credentials(username, password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Incorrect password.',
headers={'WWW-Authenticate': 'Bearer'})
raise create_http_error('Incorrect password', status.HTTP_401_UNAUTHORIZED)
except UserNotFoundError as error:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Incorrect username',
headers={'WWW-Authenticate': 'Bearer'}
) from error
raise create_http_error('Incorrect username', status.HTTP_403_FORBIDDEN) from error
token_request = {'sub': username}
token = create_access_token(token_request)
return AccessToken(access_token=token, token_type='Bearer') # nosec B106
9 changes: 3 additions & 6 deletions whist_server/api/user/create.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""'/user/create api"""

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, status
from pydantic import BaseModel

from whist_server.api.util import create_http_error
from whist_server.database.user import UserInDb
from whist_server.services.error import UserExistsError
from whist_server.services.password import PasswordService
Expand Down Expand Up @@ -35,9 +36,5 @@ def create_user(request: CreateUserArgs, pwd_service=Depends(PasswordService),
user_id = user_db_service.add(user)
except UserExistsError as user_error:
message = 'User already exists.'
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=message,
headers={"WWW-Authenticate": "Bearer"},
) from user_error
raise create_http_error(message, status.HTTP_400_BAD_REQUEST) from user_error
return {'user_id': user_id}
15 changes: 15 additions & 0 deletions whist_server/api/util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""Utility functions for the API"""
from fastapi import HTTPException


def create_http_error(message: str, status_code: int) -> HTTPException:
"""
Creates a HTTP Exception from a message and the status code.
:param message: Custom message to be displayed.
:param status_code: HTTP Status Code of the error
:return: final error to be raised
"""
return HTTPException(
status_code=status_code,
detail=message,
headers={'WWW-Authenticate': 'Bearer'})

0 comments on commit 8ce86c6

Please sign in to comment.