Skip to content

Commit

Permalink
unban / unverify
Browse files Browse the repository at this point in the history
  • Loading branch information
Zoom-Developer committed Nov 3, 2024
1 parent 2fc186a commit 04f08bf
Show file tree
Hide file tree
Showing 13 changed files with 83 additions and 21 deletions.
23 changes: 20 additions & 3 deletions backend/src/application/user/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from infrastructure.db import User
from infrastructure.exc.auth import UsernameRequired
from infrastructure.exc.likes import FocusNotSelected
from infrastructure.exc.user import AlreadyRegisteredException, FileSizeException, BannedException, SubscriptionRequiredException, VerifyRestrictionsException
from infrastructure.exc.user import AlreadyRegisteredException, AlreadyVerifiedException, FileSizeException, BannedException, SubscriptionRequiredException, VerifyRestrictionsException


class UserService:
Expand Down Expand Up @@ -34,7 +34,7 @@ async def register(self, userdata: dict, data: BaseUser, avatar: bytes) -> User:
await AttachmentService().upload(avatar, user)
await self.select_focus(user)
await TelegramService().send_media_to_chat(
"<b>Новый пользователь</b>"
"<b>👤 Новый пользователь</b>"
f"\n<b>Имя:</b> {user.mention} <b>(<code>{user.id}</code>)</b>"
f"\n<b>Класс:</b> {user.literal}"
f"\n<b>Пол:</b> {'Мужской' if user.male else 'Женский'}"
Expand All @@ -47,6 +47,7 @@ async def select_focus(self, user: User) -> User | None:
if not user.is_active:
return

user.is_active = True
user.focus_user = None
user.focus_is_liked = False
focus = await self.repo.get_noviewed(user)
Expand All @@ -58,6 +59,18 @@ async def select_focus(self, user: User) -> User | None:
await ViewRepository().insert(user, focus)
user.focus_user = focus
return focus

async def send_verify_request(self, user: User) -> None:
if user.verify:
raise AlreadyVerifiedException()
await TelegramService().send_media_to_chat(
"<b>🔰 Новый запрос на верификацию</b>"
f"\n<b>Имя:</b> {user.mention} <b>(<code>{user.id}</code>)</b>"
f"\n<b>Класс:</b> {user.literal}"
f"\n<b>Пол:</b> {'Мужской' if user.male else 'Женский'}"
f"\n<b>Описание:</b> <i>{user.desc}</i>",
[attachment.url for attachment in user.attachments]
)

async def update_avatar(self, user: User, avatar: bytes) -> None:
if len(avatar) > MAX_AVATAR_SIZE:
Expand Down Expand Up @@ -117,4 +130,8 @@ async def check_user_subcription(self, user: User) -> None:
async def ban(self, user: User, reason: str) -> None:
user.is_banned = True
user.ban_reason = reason
user.is_active = False
user.is_active = False

async def unban(self, user: User) -> None:
user.is_banned = False
user.ban_reason = None
6 changes: 5 additions & 1 deletion backend/src/domain/user/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ class PatchUser(BaseUser):
class ReportUser(BaseModel):
reason: str = Field(min_length=3, max_length=64)

class BanUser(BaseModel):
class UnbanUser(BaseModel):
msg_id: int
user_id: int

class BanUser(UnbanUser):
msg_id: int
user_id: int
reason: str
Expand Down
1 change: 1 addition & 0 deletions backend/src/infrastructure/exc/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class ErrorCode(Enum):
E3003_FOCUS_NOTSELECTED = 3003 # 403
E3004_SUBSCRIPTION_REQ = 3004 # 403
E3005_BANNED = 3005 # 403
E3006_ALREADY_VERIFY = 3006 # 403

class HTTPError(Exception):

Expand Down
6 changes: 5 additions & 1 deletion backend/src/infrastructure/exc/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,8 @@ def __init__(self) -> None:

class BannedException(HTTPError):
def __init__(self, reason: str) -> None:
super().__init__(403, ErrorCode.E3005_BANNED, "Your account has been banned", headers={"X-Reason": quote(reason)})
super().__init__(403, ErrorCode.E3005_BANNED, "Your account has been banned", headers={"X-Reason": quote(reason)})

class AlreadyVerifiedException(HTTPError):
def __init__(self) -> None:
super().__init__(403, ErrorCode.E3006_ALREADY_VERIFY, "You already verified")
11 changes: 10 additions & 1 deletion backend/src/interface/api/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async def get_user_info(user: User = Depends(get_user)) -> FullUserDTO:
"description": "Exceeded max file size (limit %s KB) (2002) / Invalid image file (2003)"
% (MAX_AVATAR_SIZE / 1024)
},
401: {"description": "undefined in endpoint"},
401: {"description": "Username required (2001)"},
403: {"description": "Already registered (3001) / Subscription to channel required (3004) / Your account has been banned (3005)"}
}
)
Expand Down Expand Up @@ -81,6 +81,15 @@ async def update_avatar(avatar: bytes = File(), user: User = Depends(get_user))
await CTX_SESSION.get().commit()
return user

@router.post(
"/verify",
responses={
403: {"description": "You already verified (3006)"}
}
)
async def send_verify(user: User = Depends(get_user)) -> FullUserDTO:
await UserService().send_verify_request(user)
return user

######################
# TEST ONLY
Expand Down
13 changes: 12 additions & 1 deletion backend/src/interface/rabbit/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from faststream.rabbit import RabbitRouter

from application.user import UserService
from domain.user import BanUser, BannedUser, VerifyUser, VerifiedUser, UserRepository
from domain.user import BanUser, BannedUser, VerifyUser, VerifiedUser, UnbanUser, UserRepository
from infrastructure.db import CTX_SESSION


Expand All @@ -17,6 +17,17 @@ async def ban_user(data: BanUser) -> BannedUser:
await CTX_SESSION.get().commit()
return BannedUser(msg_id = data.msg_id, success = True)

@router.subscriber("unban")
@router.publisher("unbanned")
async def ban_user(data: UnbanUser) -> BannedUser:
user = await UserRepository().get(data.user_id)
if not user:
return BannedUser(msg_id = data.msg_id, success = False)
await UserService().unban(user)
await CTX_SESSION.get().commit()
return BannedUser(msg_id = data.msg_id, success = True)


@router.subscriber("verify")
@router.publisher("verified")
async def ban_user(data: VerifyUser) -> VerifiedUser:
Expand Down
4 changes: 3 additions & 1 deletion bot/src/models/admin.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from pydantic import BaseModel


class BanUser(BaseModel):
class UnbanUser(BaseModel):
msg_id: int
user_id: int

class BanUser(UnbanUser):
reason: str

class BannedUser(BaseModel):
Expand Down
2 changes: 0 additions & 2 deletions bot/src/rabbit/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from faststream import FastStream

from .broker import broker
from .routers import TelegramRouter, AdminRouter


app = FastStream(broker)
broker.include_routers(TelegramRouter, AdminRouter)
8 changes: 8 additions & 0 deletions bot/src/rabbit/routers/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ async def msg(ban: BannedUser) -> None:
text = "🚫 Пользователь заблокирован" if ban.success else "❕ Неверный пользователь"
)

@router.subscriber("unbanned")
async def msg(ban: BannedUser) -> None:
await bot.send_message(
chat_id = TG_ADMIN_CHAT,
reply_to_message_id = ban.msg_id,
text = "⛓️‍💥 Пользователь разблокирован" if ban.success else "❕ Неверный пользователь"
)

@router.subscriber("verified")
async def msg(ban: VerifiedUser) -> None:
await bot.send_message(
Expand Down
4 changes: 2 additions & 2 deletions bot/src/telegram/dispatcher.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from aiogram import Dispatcher

from .handlers import AdminRouter
from .handlers import AdminHandler


dp = Dispatcher()
dp.include_router(AdminRouter)
dp.include_router(AdminHandler)
2 changes: 1 addition & 1 deletion bot/src/telegram/handlers/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .admin import router as AdminRouter
from .admin import handler as AdminHandler
20 changes: 15 additions & 5 deletions bot/src/telegram/handlers/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
from aiogram.types import Message

from config import TG_ADMIN_CHAT
from models.admin import BanUser, VerifyUser
from models.admin import BanUser, UnbanUser, VerifyUser
from rabbit.broker import broker

router = Router()
handler = Router()

@router.message(Command("ban"), F.chat.id == TG_ADMIN_CHAT)
@handler.message(Command("ban"), F.chat.id == TG_ADMIN_CHAT)
async def ban(msg: Message):
args = msg.text.split()[1:]
if len(args) < 2 or not args[0].isdigit():
Expand All @@ -19,7 +19,17 @@ async def ban(msg: Message):
"adm_ban"
)

@router.message(Command("verify"), F.chat.id == TG_ADMIN_CHAT)
@handler.message(Command("unban"), F.chat.id == TG_ADMIN_CHAT)
async def ban(msg: Message):
args = msg.text.split()[1:]
if len(args) < 1 or not args[0].isdigit():
return msg.reply("❕ Use: /unban [USER_ID]")
await broker.publish(
UnbanUser(msg_id = msg.message_id, user_id = args[0]),
"adm_unban"
)

@handler.message(Command("verify"), F.chat.id == TG_ADMIN_CHAT)
async def ban(msg: Message):
args = msg.text.split()[1:]
if len(args) < 1 or not args[0].isdigit():
Expand All @@ -29,7 +39,7 @@ async def ban(msg: Message):
"adm_verify"
)

@router.message(Command("unverify"), F.chat.id == TG_ADMIN_CHAT)
@handler.message(Command("unverify"), F.chat.id == TG_ADMIN_CHAT)
async def ban(msg: Message):
args = msg.text.split()[1:]
if len(args) < 1 or not args[0].isdigit():
Expand Down
4 changes: 1 addition & 3 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,13 @@ services:
env_file:
- .env
depends_on:
backend:
condition: service_healthy
rabbitmq:
condition: service_healthy
restart: true
deploy:
resources:
limits:
cpus: '0.1'
cpus: '0.3'
memory: 256M

db:
Expand Down

0 comments on commit 04f08bf

Please sign in to comment.