Skip to content

Commit

Permalink
Dump version
Browse files Browse the repository at this point in the history
  • Loading branch information
Qwizi committed Jan 29, 2024
1 parent de2a398 commit 163319b
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 190 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

[tool.poetry]
name = "sharkservers-api"
version = "1.2.1"
version = "1.2.2"
description = "sharkservers-api"
authors = ["Qwizi <ciolek.adrian@protonmail.com>"]
license = "GPL-3.0"
Expand Down
5 changes: 4 additions & 1 deletion sharkservers/auth/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ class PasswordSchema(BaseModel):

@validator("password2")
def passwords_match(
self, value: str, values: dict[str], **kwargs: dict[str], # noqa: ARG002
self,
value: str,
values: dict[str],
**kwargs: dict[str], # noqa: ARG002
) -> None:
"""
Check if the 'password2' field matches the 'password' field.
Expand Down
2 changes: 1 addition & 1 deletion sharkservers/dependencies.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Dependencies for the application."""
import resend
from fastapi import Depends
from fastapi_mail import ConnectionConfig
from fastapi_mail.email_utils import DefaultChecker
import resend

from sharkservers.services import EmailService, UploadService
from sharkservers.settings import Settings, get_settings
Expand Down
24 changes: 19 additions & 5 deletions sharkservers/exception_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
from sharkservers.logger import logger


async def request_validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
async def request_validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
"""
Middleware will log all RequestValidationErrors.
Expand All @@ -32,12 +34,18 @@ async def request_validation_exception_handler(request: Request, exc: RequestVal
logger.debug("Our custom request_validation_exception_handler was called")
body = await request.body()
query_params = request.query_params._dict # pylint: disable=protected-access
detail = {"errors": exc.errors(), "body": body.decode(), "query_params": query_params}
detail = {
"errors": exc.errors(),
"body": body.decode(),
"query_params": query_params,
}
logger.info(detail)
return await _request_validation_exception_handler(request, exc)


async def http_exception_handler(request: Request, exc: HTTPException) -> Union[JSONResponse, Response]:
async def http_exception_handler(
request: Request, exc: HTTPException
) -> Union[JSONResponse, Response]:
"""
HTTPException handler.
Expand All @@ -54,7 +62,9 @@ async def http_exception_handler(request: Request, exc: HTTPException) -> Union[
return await _http_exception_handler(request, exc)


async def unhandled_exception_handler(request: Request, exc: Exception) -> PlainTextResponse:
async def unhandled_exception_handler(
request: Request, exc: Exception
) -> PlainTextResponse:
"""
Unhandled exception handler.
Expand All @@ -70,7 +80,11 @@ async def unhandled_exception_handler(request: Request, exc: Exception) -> Plain
logger.debug("Our custom unhandled_exception_handler was called")
host = getattr(getattr(request, "client", None), "host", None)
port = getattr(getattr(request, "client", None), "port", None)
url = f"{request.url.path}?{request.query_params}" if request.query_params else request.url.path
url = (
f"{request.url.path}?{request.query_params}"
if request.query_params
else request.url.path
)
exception_type, exception_value, exception_traceback = sys.exc_info()
exception_name = getattr(exception_type, "__name__", None)
logger.error(
Expand Down
4 changes: 3 additions & 1 deletion sharkservers/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,9 @@ def create_app() -> FastAPI:
_app.mount("/static", StaticFiles(directory=st_abs_file_path), name="static")
init_routes(_app)
add_pagination(_app)
_app.add_exception_handler(RequestValidationError, request_validation_exception_handler)
_app.add_exception_handler(
RequestValidationError, request_validation_exception_handler
)
_app.add_exception_handler(HTTPException, http_exception_handler)
_app.add_exception_handler(Exception, unhandled_exception_handler)

Expand Down
12 changes: 9 additions & 3 deletions sharkservers/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ async def log_request_middleware(request: Request, call_next):
0.0.0.0:1234 - GET /ping 200 OK 1.00ms
"""
logger.debug("middleware: log_request_middleware")
url = f"{request.url.path}?{request.query_params}" if request.query_params else request.url.path
url = (
f"{request.url.path}?{request.query_params}"
if request.query_params
else request.url.path
)
start_time = time.time()
response = await call_next(request)
process_time = (time.time() - start_time) * 1000
Expand All @@ -23,6 +27,8 @@ async def log_request_middleware(request: Request, call_next):
try:
status_phrase = http.HTTPStatus(response.status_code).phrase
except ValueError:
status_phrase=""
logger.info(f'{host}:{port} - "{request.method} {url}" {response.status_code} {status_phrase} {formatted_process_time}ms')
status_phrase = ""
logger.info(
f'{host}:{port} - "{request.method} {url}" {response.status_code} {status_phrase} {formatted_process_time}ms'
)
return response
178 changes: 0 additions & 178 deletions sharkservers/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,184 +22,6 @@
from sharkservers.users.models import User


# class EmailService:
# """
# Email service class.

# Attributes
# ----------
# mailer: FastMail instance.
# checker: DefaultChecker instance.

# Methods
# -------
# activation_email_template: Returns an activation email template.
# change_email_template: Returns a change email template.
# password_reset_email_template: Returns a password reset email template.
# _send_message: Sends an email message.
# send_confirmation_email: Sends a confirmation email.
# """

# mailer: FastMail
# checker: DefaultChecker

# def __init__(self, _mailer: FastMail, checker: DefaultChecker) -> None:
# """Initialize EmailService class."""
# self.mailer = _mailer
# self.checker = checker

# @staticmethod
# def activation_email_template(code: str) -> str:
# """
# Return an activation email template.

# Args:
# ----
# code (str): Activation code.

# Returns:
# -------
# str: Activation email template.
# """
# return f"""
# Drogi(a) Użytkowniku, <br>

# Dziękujemy za dołączenie do naszej społeczności! Jesteśmy podekscytowani, że jesteś z nami.<br>

# Aby dokończyć proces rejestracji i aktywować swoje konto, proszę skorzystać z poniższego kodu aktywacyjnego: <br>

# Kod aktywacyjny: {code} <br>

# Pamiętaj, że kod aktywacyjny może wygasnąć po pewnym czasie, więc zalecamy, abyś aktywował/a swoje konto jak najszybciej. <br>

# Pozdrawiamy, <br>
# Administracja SharkServers.pl
# """

# @staticmethod
# def change_email_template(code: str) -> str:
# """
# Return a change email template.

# Args:
# ----
# code (str): Verification code.

# Returns:
# -------
# str: Change email template.
# """
# return f"""
# Drogi(a) Użytkowniku,<br>

# Otrzymujesz tę wiadomość, ponieważ zażądałeś/aś zmiany adresu e-mail powiązanego z Twoim kontem na SharkServers.pl.<br>

# Proszę skorzystać z poniższego kodu weryfikacyjnego, aby potwierdzić tę zmianę:<br>

# Kod weryfikacyjny: {code}<br>

# Prosimy o wprowadzenie powyższego kodu w odpowiednie pole na naszej stronie w celu potwierdzenia zmiany adresu e-mail. Jeśli nie żądałeś/aś tej zmiany, prosimy o natychmiastowy kontakt z naszym zespołem wsparcia pod adresem [Adres e-mail zespołu wsparcia] lub za pośrednictwem formularza kontaktowego na naszej stronie.<br>

# Pamiętaj, że ten kod weryfikacyjny wygaśnie po pewnym czasie w celu zabezpieczenia Twojego konta. Prosimy o jego użycie jak najszybciej.<br>

# Jeśli potrzebujesz pomocy lub masz pytania, zawsze możesz skontaktować się z naszym zespołem obsługi klienta.<br>

# Z poważaniem,<br>
# Administracja SharkServers.pl

# """

# @staticmethod
# def password_reset_email_template(code: str) -> str:
# """
# Password reset email template.

# Args:
# ----
# code (str): Verification code.

# Returns:
# -------
# str: Password reset email template.
# """
# return f"""
# Drogi(a) Użytkowniku,<br><br>

# Otrzymujesz tę wiadomość, ponieważ zażądałeś/aś zresetowania hasła powiązanego z Twoim kontem na SharkServers.pl.<br><br>

# Proszę skorzystać z poniższego kodu weryfikacyjnego, aby zresetować hasło:<br><br>

# Kod weryfikacyjny: {code}<br><br>

# Proszę wprowadzić powyższy kod w odpowiednie pole na naszej stronie w celu zresetowania hasła. Jeśli to nie Ty zażądałeś/aś resetowania hasła, zignoruj tę wiadomość.<br><br>

# Kod weryfikacyjny wygasa po ograniczonym czasie w celu zabezpieczenia Twojego konta. Proszę o użycie go jak najszybciej.<br><br>

# Jeśli potrzebujesz pomocy lub masz pytania, zawsze możesz skontaktować się z naszym zespołem obsługi klienta.<br><br>

# Z poważaniem,<br>
# Administracja SharkServers.pl
# """

# async def _send_message(self, subject: str, recipients: list, body: str) -> None:
# """
# Sends an email message to the specified recipients.

# Args:
# ----
# subject (str): The subject of the email.
# recipients (list): A list of email addresses of the recipients.
# body (str): The body of the email.

# Returns:
# -------
# None
# """ # noqa: D401
# if not await self.checker.check_mx_record(recipients[0].split("@")[1]):
# logger.info(f"Email {recipients[0]} is invalid")
# return
# await self.mailer.send_message(
# message=MessageSchema(
# subject=subject,
# recipients=recipients,
# body=body,
# subtype=MessageType.html,
# ),
# )

# async def send_confirmation_email(
# self,
# activation_type: ActivationEmailTypeEnum,
# email: EmailStr,
# code: str,
# ) -> None:
# """
# Send a confirmation email.

# Args:
# ----
# activation_type (ActivationEmailTypeEnum): The type of the activation email.
# email (EmailStr): The email address of the recipient.
# code (str): The activation code.

# Returns:
# -------
# None
# """
# subject = None
# body = None
# if activation_type == ActivationEmailTypeEnum.ACCOUNT:
# subject = "Twój kod aktywacyjny - Witamy na naszej stronie!"
# body = self.activation_email_template(code)
# elif activation_type == ActivationEmailTypeEnum.EMAIL:
# subject = "Twój kod weryfikacyjny - Zmiana adresu e-mail"
# body = self.change_email_template(code)
# elif activation_type == ActivationEmailTypeEnum.PASSWORD:
# subject = "Twój kod weryfikacyjny - Reset hasła"
# body = self.password_reset_email_template(code)
# await self._send_message(subject, [email], body)
# logger.info(f"Activation email sent to {email} with code {code}")


class EmailService:
"""Email service class."""
Expand Down

0 comments on commit 163319b

Please # to comment.