Skip to content
Open
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
7 changes: 4 additions & 3 deletions alembic.ini
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,9 @@ version_path_separator = os # Use os.pathsep. Default configuration used for ne
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = postgresql://hw14:1234@localhost/hw14

;sqlalchemy.url = postgresql://hw14:1234@localhost/hw14
[alembic:env]
sqlalchemy.url = postgresql+asyncpg://user:password@localhost:5438/dbname

[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
Expand Down Expand Up @@ -103,7 +104,7 @@ qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
handlers = console
qualname = alembic

[handler_console]
Expand Down
2 changes: 2 additions & 0 deletions app/src/conf/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ class Settings(BaseSettings):
env_file=pathlib.Path(__file__).resolve().parent.parent.parent.parent / ".env",
env_file_encoding="utf-8",
extra="ignore",


)

api_name: str
Expand Down
2 changes: 1 addition & 1 deletion app/src/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from app.src.schemas.tokens import TokenModel, TokenPasswordSetModel
from app.src.repository import users as repository_users
from app.src.services.auth import auth_service
from app.src.services.email import (
from app.src.services.email_service import (
send_email_for_verification,
send_email_for_password_reset,
)
Expand Down
33 changes: 22 additions & 11 deletions app/src/services/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
Module of authentication class and methods
"""


from datetime import datetime, timedelta, timezone
from os import urandom
from typing import Optional
Expand All @@ -18,6 +17,7 @@
from app.src.conf.config import settings
from app.src.database.connect_db import get_session, get_redis_db1
from app.src.repository import users as repository_users
# from .auth_service import get_current_user # Функція для отримання поточного користувача


class Auth:
Expand Down Expand Up @@ -51,7 +51,7 @@ def get_password_hash(self, password: str):
return self.pwd_context.hash(password)

async def create_access_token(
self, data: dict, expires_delta: Optional[float] = None
self, data: dict, expires_delta: Optional[float] = None
):
"""
Creates the access token.
Expand All @@ -76,8 +76,19 @@ async def create_access_token(
)
return encoded_access_token

async def role_required(role: str):
def decorator(current_user: User = Depends(get_current_user)):
if current_user.role != role:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions",
)
return current_user

return decorator

async def create_refresh_token(
self, data: dict, expires_delta: Optional[float] = None
self, data: dict, expires_delta: Optional[float] = None
):
"""
Creates the refresh token.
Expand Down Expand Up @@ -107,7 +118,7 @@ async def create_refresh_token(
return encoded_refresh_token

async def create_email_verification_token(
self, data: dict, expires_delta: Optional[float] = None
self, data: dict, expires_delta: Optional[float] = None
):
"""
Creates the email verification token.
Expand Down Expand Up @@ -137,7 +148,7 @@ async def create_email_verification_token(
return encoded_email_verification_token

async def create_password_reset_token(
self, data: dict, expires_delta: Optional[float] = None
self, data: dict, expires_delta: Optional[float] = None
):
"""
Creates the password reset token.
Expand Down Expand Up @@ -167,7 +178,7 @@ async def create_password_reset_token(
return encoded_password_reset_token

async def create_password_set_token(
self, data: dict, expires_delta: Optional[float] = None
self, data: dict, expires_delta: Optional[float] = None
):
"""
Creates the password set token.
Expand Down Expand Up @@ -313,10 +324,10 @@ async def decode_password_set_token(self, password_set_token: str):
raise credentials_exception

async def get_current_user(
self,
access_token: str = Depends(oauth2_scheme),
session: AsyncSession = Depends(get_session),
cache: Redis = Depends(get_redis_db1),
self,
access_token: str = Depends(oauth2_scheme),
session: AsyncSession = Depends(get_session),
cache: Redis = Depends(get_redis_db1),
):
"""
Gets the current user.
Expand Down Expand Up @@ -357,4 +368,4 @@ async def get_current_user(
return user


auth_service = Auth()
auth_service = Auth()
16 changes: 12 additions & 4 deletions app/src/services/email.py → app/src/services/email_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
Module of email sending functions
"""


from pathlib import Path

from fastapi_mail import FastMail, MessageSchema, ConnectionConfig, MessageType
Expand All @@ -11,6 +10,15 @@

from app.src.conf.config import settings

# # Імпортуємо стандартний модуль через importlib
# import importlib
#
# email_message = importlib.import_module('email.message')

# Використовуємо власний модуль
# from . import email_service # це ваш локальний файл
from app.src.services import email_service


conf = ConnectionConfig(
MAIL_SERVER=settings.mail_server,
Expand All @@ -28,7 +36,7 @@


async def send_email_for_verification(
email: EmailStr, username: str, email_verification_token: str, host: HttpUrl
email: EmailStr, username: str, email_verification_token: str, host: HttpUrl
):
"""
Sends an email for verification of the user's email.
Expand Down Expand Up @@ -63,7 +71,7 @@ async def send_email_for_verification(


async def send_email_for_password_reset(
email: EmailStr, username: str, password_reset_token: str, host: HttpUrl
email: EmailStr, username: str, password_reset_token: str, host: HttpUrl
):
"""
Sends an email for the user's password reset.
Expand Down Expand Up @@ -94,4 +102,4 @@ async def send_email_for_password_reset(
fm = FastMail(conf)
await fm.send_message(message, template_name="password_reset_email.html")
except ConnectionErrors as error_message:
print(f"Connection error: {str(error_message)}")
print(f"Connection error: {str(error_message)}")
6 changes: 6 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@
from app.src.database.connect_db import engine, get_session, redis_db0, pool_redis_db
from app.src.routes import contacts, auth, users

import asyncio
import sys

if sys.platform.startswith("win"):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


@asynccontextmanager
async def lifespan(app: FastAPI):
Expand Down