2023-06-12 18:50:33 +02:00
|
|
|
import datetime
|
2022-06-03 08:09:47 -06:00
|
|
|
from typing import Optional, Tuple
|
|
|
|
|
from uuid import uuid4
|
|
|
|
|
|
|
|
|
|
from django.core.exceptions import ValidationError
|
2022-08-23 13:25:22 -03:00
|
|
|
from django.db import IntegrityError, models
|
2022-06-03 08:09:47 -06:00
|
|
|
from django.utils import timezone
|
|
|
|
|
|
|
|
|
|
from apps.telegram.models import TelegramToUserConnector
|
2023-04-17 15:16:18 +08:00
|
|
|
from common.insight_log import ChatOpsEvent, ChatOpsTypePlug, write_chatops_insight_log
|
2022-06-03 08:09:47 -06:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class TelegramVerificationCode(models.Model):
|
|
|
|
|
uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False)
|
|
|
|
|
datetime = models.DateTimeField(auto_now_add=True)
|
|
|
|
|
|
|
|
|
|
user = models.OneToOneField(
|
|
|
|
|
"user_management.User", on_delete=models.CASCADE, related_name="telegram_verification_code"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def is_active(self) -> bool:
|
2023-06-12 18:50:33 +02:00
|
|
|
return self.datetime + datetime.timedelta(days=1) < timezone.now()
|
2022-06-03 08:09:47 -06:00
|
|
|
|
2022-10-25 14:53:07 +08:00
|
|
|
@property
|
2022-12-06 22:42:58 +08:00
|
|
|
def uuid_with_org_uuid(self) -> str:
|
|
|
|
|
return f"{self.user.organization.uuid}_{self.uuid}"
|
2022-10-25 14:53:07 +08:00
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def uuid_without_org_id(cls, verification_code: str) -> str:
|
|
|
|
|
try:
|
|
|
|
|
return verification_code.split("_")[1]
|
|
|
|
|
except IndexError:
|
|
|
|
|
raise ValidationError("Invalid verification code format")
|
|
|
|
|
|
2022-06-03 08:09:47 -06:00
|
|
|
@classmethod
|
|
|
|
|
def verify_user(
|
2022-10-25 14:53:07 +08:00
|
|
|
cls, verification_code: str, telegram_chat_id: int, telegram_nick_name: str
|
2022-06-03 08:09:47 -06:00
|
|
|
) -> Tuple[Optional[TelegramToUserConnector], bool]:
|
|
|
|
|
try:
|
2022-10-25 14:53:07 +08:00
|
|
|
uuid_code = cls.uuid_without_org_id(verification_code)
|
|
|
|
|
code_instance = cls.objects.get(uuid=uuid_code)
|
|
|
|
|
|
|
|
|
|
user = code_instance.user
|
2022-06-03 08:09:47 -06:00
|
|
|
|
|
|
|
|
connector, created = TelegramToUserConnector.objects.get_or_create(
|
2022-08-23 13:25:22 -03:00
|
|
|
user=user, defaults={"telegram_nick_name": telegram_nick_name, "telegram_chat_id": telegram_chat_id}
|
2022-06-03 08:09:47 -06:00
|
|
|
)
|
2022-08-24 12:04:44 +05:00
|
|
|
write_chatops_insight_log(
|
|
|
|
|
author=user,
|
|
|
|
|
event_name=ChatOpsEvent.USER_LINKED,
|
2023-04-17 15:16:18 +08:00
|
|
|
chatops_type=ChatOpsTypePlug.TELEGRAM.value,
|
2022-08-25 13:34:19 +05:00
|
|
|
linked_user=user.username,
|
|
|
|
|
linked_user_id=user.public_primary_key,
|
2022-06-03 08:09:47 -06:00
|
|
|
)
|
|
|
|
|
return connector, created
|
|
|
|
|
|
2022-08-23 13:25:22 -03:00
|
|
|
except (ValidationError, cls.DoesNotExist, IntegrityError):
|
2022-06-03 08:09:47 -06:00
|
|
|
return None, False
|