Skip to content

Commit

Permalink
Merge pull request #75 from w1tnessbtwwwww/backend
Browse files Browse the repository at this point in the history
Backend
  • Loading branch information
w1tnessbtwwwww authored Jan 6, 2025
2 parents 9343e57 + a20e370 commit 3e5407b
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,27 @@ class OrganizationRepository(AbstractRepository):
model = Organization


async def delete_organization(self, **kwargs) -> Result[int]:
query = (
delete(self.model)
.where(and_(
self.model.organizationId == kwargs["organizationId"],
self.model.leaderId == kwargs["leaderId"]
))
)

try:
result = await self._session.execute(query)
await self._session.commit()

if result.rowcount < 1:
return err("Организация не найдена")

return success(result.rowcount)
except Exception as e:
logger.error(f"Не удалось удалить организацию OrganizationRepository.", str(e))
return err("Произошла ошибка при удалении организации. Информация направлена разработчику.")

async def create_organization(self, **kwargs) -> Result[Organization]:
query = (
select(self.model)
Expand All @@ -35,20 +56,40 @@ async def create_organization(self, **kwargs) -> Result[Organization]:

return success(value = await self.create(**kwargs))

async def update_organization(self, **kwargs) -> Result[Organization]:
async def update_organization(self,
organizationId: str,
new_title: Optional[str] = None,
new_description: Optional[str] = None) -> Result[Organization]:

query = (
update(self.model)
select(self.model)
.where(and_(
self.model.organizationId == kwargs["organizationId"],
self.model.organizationId == organizationId,
self.model.leaderId == self.model.leaderId
))
.values(**kwargs).returning(self.model)
)

result = await self._session.execute(query)
await self._session.commit()
organization = result.scalars().first()

if not organization:
return err("Организация не найдена")

update_query = (
update(self.model)
.where(self.model.organizationId == organizationId)
.values(
title = new_title if new_title else organization.title,
description = new_description if new_description else organization.description
)
.returning(self.model)
)

try:
updating = await self._session.execute(update_query)
await self._session.commit()
organization = updating.scalars().first()
except Exception as e:
logger.error(f"Не удалось обновить организацию OrganizationRepository.", str(e))
return err("Произошла ошибка при обновлении организации. Информация направлена разработчику.")
return success(organization)
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
class UserRepository(AbstractRepository):
model = User

async def create(self, **kwargs):
query = insert(self.model).values(**kwargs).returning(self.model)
result = await self._session.execute(query)
return result.scalars().first()

async def update_by_id(self, userId: str, **kwargs):
query = update(self.model).where(self.model.userId == userId).values(**kwargs).returning(self.model)
result = await self._session.execute(query)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ async def register(registerRequest: RegisterRequest, session: AsyncSession = Dep
async def authorize(username: str = Form(), password: str = Form(), session: AsyncSession = Depends(get_session)):
user = await UserRepository(session).get_by_filter_one(email=username)
if not user:
raise HTTPException(status_code=400, detail="Пользователь не найден")
raise HTTPException(status_code=401, detail="Пользователь не найден")
authorized = await UserService(session).authorize(username, password)
if not authorized.success:
raise HTTPException(status_code=400, detail=authorized.error)
raise HTTPException(status_code=401, detail=authorized.error)

jwt_manager = JWTManager()
access_token = jwt_manager.encode_token({ "userId": str(user.userId) }, token_type=JWTType.ACCESS)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,9 @@ async def update_organization(updateRequest: UpdateOrganization, user: User = De


@organization_router.delete("/delete")
async def delete_organization(user: User = Depends(get_current_user), session: AsyncSession = Depends(get_session)):
raise HTTPException(status_code=400, detail="Not implemented")
async def delete_organization(organizationId: str, user: User = Depends(get_current_user), session: AsyncSession = Depends(get_session)):
deleting = await OrganizationService(session).delete_organization(organizationId, user.userId)
if not deleting.success:
raise HTTPException(status_code=400, detail=deleting.error)

return deleting.value
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@

class UpdateOrganization(BaseModel):
organizationId: str
title: Optional[str] = None
description: Optional[str] = None
new_title: Optional[str] = None
new_description: Optional[str] = None
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@

from typing import Optional
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.models.models import Organization, User
Expand All @@ -8,6 +9,7 @@

from app.schema.request.organization.create_organization import CreateOrganization
from app.schema.request.organization.update_organization import UpdateOrganization
from app.utils.logger.telegram_bot.telegram_logger import logger
from app.utils.result import Result, err, success


Expand All @@ -17,6 +19,17 @@ def __init__(self, session: AsyncSession):
self._session = session
self._repo = OrganizationRepository(session)

async def delete_organization(self, organizationId: str, leaderId: str) -> Result[int]:
try:
deleting = await self._repo.delete_organization(organizationId=organizationId, leaderId=leaderId)
if not deleting.success:
return err(deleting.error)
return success(deleting.value)
except Exception as e:
logger.error(f"Произошла ошибка в OrganizationService. при удалении организации.", str(e))
return err("Произошла ошибка при удалении организации. Информация направлена разработчику.")


async def create_organization(self, createRequest: CreateOrganization, userId: str) -> Result[Organization]:
return await self._repo.create_organization(title=createRequest.name, description=createRequest.description, leaderId=userId)

Expand All @@ -26,7 +39,7 @@ async def update_organization(self, updateRequest: UpdateOrganization, userId: s
if not organization:
return err("Организация не найдена.")

organization_upd = await self._repo.update_organization(organizationId=updateRequest.organizationId, title=updateRequest.title, description=updateRequest.description, leaderId=userId)
organization_upd = await self._repo.update_organization(organizationId=updateRequest.organizationId, new_title=updateRequest.new_title, new_description=updateRequest.new_description)
if not organization_upd.success:
return err(organization_upd.error)

Expand Down
14 changes: 9 additions & 5 deletions SpeedSolverBackend/SpeedSolverAPI/app/services/user_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,19 @@ async def confirm_email(self, userId: str):
return await self._repo.update_by_id(userId, is_mail_verified=True)

async def update_profile(self, token: str, update_request: UpdateProfile):
user: User = await JWTManager().get_current_user(token, self._session)
await self._repo.update_profile()
raise NotImplementedError

async def register(self, register_request: register.RegisterRequest) -> Result[None]:
try:
inserted = await self._repo.create(email=register_request.email, password=hash_password(register_request.password))
await VerificationService(self._session).process_verification(inserted.userId, inserted.email)
inserted = await self._repo.create(email=register_request.email, password=hash_password(register_request.password))
is_verification_inserted = await VerificationService(self._session).process_verification(inserted.userId, inserted.email)
if not is_verification_inserted.success:
self._repo.rollback()
return err(is_verification_inserted.error)

await self._repo.commit()
except IntegrityError as e:
return err("Пользователь с такой почтой уже зарегистрирован.")
return err("Пользователь с такой почтой уже зарегистрирован.")
return success("Пользователь успешно зарегистрирован. Проверьте почту.")

async def authorize(self, email: str, password: str):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ def __init__(self, session: AsyncSession):
async def process_verification(self, userId: str, email: str):
code = await EmailService().send_verify_code("Подтверждение письма", email)
if not code.success:
logger.fatal(code.error)
return
return err("Не удалось отправить код. Возможно, неверная почта.")

verification = await self._repo.process_verification(userId, code.value)
return verification
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ async def send_verify_code(subject: str, send_to: str) -> Result[str]:
result = success(code)
logger.info(f"sended code {code} to {send_to}")
except Exception as e:
print(f'Ошибка при отправке сообщения: {e}')
result = err(str(e))
logger.error(f'Ошибка при отправке сообщения: {e}')
logger.error(f'Ошибка при отправке кода на почту.', str(e))
finally:
server.quit()
return result

0 comments on commit 3e5407b

Please sign in to comment.