Skip to content

Commit

Permalink
Merge pull request #52 from hyp3rd/fix/API
Browse files Browse the repository at this point in the history
auth endpoints improvements
  • Loading branch information
hyp3rd committed Dec 15, 2023
2 parents 30fb5f1 + d5e26c3 commit 148e448
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 12 deletions.
47 changes: 47 additions & 0 deletions api/routers/auth.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Bridge Auth Router."""
import json
import os

from fastapi import APIRouter

Expand Down Expand Up @@ -62,3 +63,49 @@ async def telegram_auth(auth: TelegramAuthSchema):
error="",
)
)


@router.delete(
"/telegram",
name="Sign out from Telegram",
summary="Clears the Telegram authentication.",
description="Clears the Telegram authentication and session files.",
response_model=TelegramAuthResponseSchema,
)
async def telegram_deauth():
"""Clears the Telegram authentication"""
config = Config.get_instance()

try:
# Remove the Telegram auth file.
if os.path.isfile(config.api.telegram_auth_file):
os.remove(config.api.telegram_auth_file)

# Remove the session file.
if os.path.isfile(f"{config.application.name}.session"):
os.remove(f"{config.application.name}.session")

return TelegramAuthResponseSchema(
auth=TelegramAuthResponse(
status="success",
message="signed out from the Telegram API successfully.",
error="",
)
)

except OSError as ex:
return TelegramAuthResponseSchema(
auth=TelegramAuthResponse(
status="failed",
message="failed to sign out from the Telegram API.",
error=ex.strerror,
)
)
except Exception as ex: # pylint: disable=broad-except
return TelegramAuthResponseSchema(
auth=TelegramAuthResponse(
status="failed",
message="failed to sign out from the Telegram API.",
error=str(ex),
)
)
4 changes: 2 additions & 2 deletions api/routers/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ async def post_config(self, config_schema: ConfigSchema) -> BaseResponse:

# validate the config with pydantic
try:
_ = ConfigYAMLSchema(**config_schema.config.dict())
_ = ConfigYAMLSchema(**config_schema.config.model_dump())
except ValidationError as exc:
for error in exc.errors():
logger.error(error)
Expand All @@ -262,7 +262,7 @@ async def post_config(self, config_schema: ConfigSchema) -> BaseResponse:

with open(config_file_name, "w", encoding="utf-8") as new_config_file:
yaml.dump(
config_schema.config.dict(),
config_schema.config.model_dump(),
new_config_file,
allow_unicode=False,
encoding="utf-8",
Expand Down
10 changes: 5 additions & 5 deletions bridge/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import yaml

# from pydantic import RootModel # pylint: disable=import-error
from pydantic import SecretStr # pylint: disable=import-error
# from pydantic import SecretStr # pylint: disable=import-error
from pydantic import BaseModel, StrictInt, model_validator, validator

_instances: Dict[str, "Config"] = {}
Expand Down Expand Up @@ -226,7 +226,7 @@ class TelegramConfig(BaseModel): # pylint: disable=too-few-public-methods
"""Telegram config."""

phone: str
password: SecretStr
password: str
api_id: StrictInt
api_hash: str
log_unhandled_dialogs: bool = False
Expand All @@ -237,9 +237,9 @@ class TelegramConfig(BaseModel): # pylint: disable=too-few-public-methods
class Config:
"""Telegram config."""

json_encoders = {
SecretStr: lambda val: val.get_secret_value(),
}
# json_encoders = {
# SecretStr: lambda val: val.get_secret_value(),
# }

@validator("api_hash")
def api_hash_alphanumeric(cls, val):
Expand Down
13 changes: 8 additions & 5 deletions bridge/telegram/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
from asyncio.events import AbstractEventLoop

from telethon import TelegramClient
from telethon.errors.rpcerrorlist import (FloodWaitError,
PhoneCodeInvalidError,
SessionPasswordNeededError,
SessionRevokedError)
from telethon.errors.rpcerrorlist import (
FloodWaitError,
PhoneCodeInvalidError,
SessionPasswordNeededError,
SessionRevokedError,
)

from bridge.config import Config
from bridge.events import EventDispatcher
Expand Down Expand Up @@ -207,7 +209,8 @@ def password_callback():
json.dump(auth_data, auth_file)
raise

# os.remove(config.telegram.auth_file)
if os.path.isfile(config.api.telegram_auth_file):
os.remove(config.api.telegram_auth_file)

bot_identity = await telegram_client.get_me(input_peer=False)
logger.info(
Expand Down
3 changes: 3 additions & 0 deletions tools/kill-server.bash
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env bash

kill -9 "$(ps aux | grep python | awk '{print $2}')"

0 comments on commit 148e448

Please sign in to comment.