From 4b64e994c93f9f7c441e1e1bd00cbb56a4481576 Mon Sep 17 00:00:00 2001 From: Vlad Date: Mon, 1 Apr 2024 15:33:40 +0600 Subject: [PATCH] end --- UserStatus/models.py | 55 ++++++++++++++++++++++++++ main.py | 91 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 UserStatus/models.py diff --git a/UserStatus/models.py b/UserStatus/models.py new file mode 100644 index 0000000..9f36064 --- /dev/null +++ b/UserStatus/models.py @@ -0,0 +1,55 @@ +from django.db import models +from oauth2_provider import settings as oauth2_settings +class MyUser(models.Model): + + def photo_upload(instance, filename): + return f'passport/{instance.first_name}-{instance.last_name}/{filename}' + + GENDER_CHOICES = ( + ('Мужской', 'Мужской'), + ('Женский', 'Женский'), + ) + email = models.EmailField(unique=True) + gender = models.CharField(max_length=10, choices=GENDER_CHOICES, blank=True, null=True, verbose_name='Пол') + date = models.DateField(null=True, blank=True, verbose_name='Дата рождения') + phone_number = models.CharField(max_length=15, blank=True, null=True, unique=True, verbose_name='Номер телефона') + image = models.ImageField(upload_to='images', blank=True, verbose_name='Изображение профиля') + face_image = models.ImageField(upload_to=photo_upload, blank=True, verbose_name='Переднее изображение паспорта') + back_image = models.ImageField(upload_to=photo_upload, blank=True, verbose_name='Заднее изображение паспорта') + STATUS_CHOICES = ( + ('Верифицирован', 'Верифицирован'), + ('Не верифицирован', 'Не верифицирован'), + ('На верификацию', 'На верификацию'), + ('Верификация отклонена', 'Верификация отклонена'), + ) + status = models.CharField(max_length=30, default='Не верифицирован', choices=STATUS_CHOICES, blank=True, null=True, verbose_name='Статус') + + class Meta: + db_table = 'backend_myuser' + + + def __str__(self): + return self.email + + + + + + +class Token000000(models.Model): + token = models.CharField(max_length=255, unique=True, verbose_name='key') + user_id = models.IntegerField(unique=True, verbose_name='user_id') + + + class Meta: + db_table = 'authtoken_token' + + def __str__(self): + return self.token + + + + + + + diff --git a/main.py b/main.py index 99139d3..9044474 100644 --- a/main.py +++ b/main.py @@ -12,6 +12,45 @@ from queue import Queue, Empty from threading import Lock import pytesseract import face_recognition +from django.conf import settings + +from django.db import transaction +from django.db.models import F +from asgiref.sync import sync_to_async + + + +settings.configure( + DATABASES={ + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': 'Test', + 'USER': 'postgres', + 'PASSWORD': 'admin', + 'HOST': 'localhost', + 'PORT': '5432', + } + }, + INSTALLED_APPS=[ + 'UserStatus', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'rest_framework.authtoken', + ], +AUTH_USER_MODEL = 'UserStatus.MyUser', + +) + +import django +django.setup() +from UserStatus.models import MyUser +from rest_framework.authtoken.models import Token + + @@ -30,6 +69,40 @@ if not os.path.exists(directoryToSave): + +@sync_to_async +def update_user_status(email): + try: + with transaction.atomic(): + user = MyUser.objects.get(email=email) + user.status = 'Верифицирован' + user.save() + except MyUser.DoesNotExist: + print(f"User with email {email} does not exist.") + except Exception as e: + print(f"An error occurred: {e}") + + + +@sync_to_async +def check_if_ok(email, token_value): + try: + with transaction.atomic(): + user = MyUser.objects.get(email=email) + # Получаем ID пользователя + user_id = user.id + # Ищем токен пользователя по user_id + token = Token.objects.get(key=token_value) + if token and token.user.id == user_id: + return True + except MyUser.DoesNotExist: + print(f"User with email {email} does not exist.") + except Exception as e: + print(f"An error occurred: {e}") + + return False + + def detect_rectangle(frame, template): result = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED) _, max_val, _, max_loc = cv2.minMaxLoc(result) @@ -73,6 +146,8 @@ def handle_output(out, frame_lock, frame_container): async def save_webm_stream(websocket): + email = None + token = None json_data_received = False @@ -106,6 +181,7 @@ async def save_webm_stream(websocket): async for message in websocket: if not json_data_received: + json_data, _, binary_data = message.partition('\0') if json_data: @@ -113,6 +189,15 @@ async def save_webm_stream(websocket): try: json_object = json.loads(json_data) print("JSON data received:", json_object) + to_get9 = json_object.get("message") + email = to_get9.get("email") + token = to_get9.get("token") + if email: + result = await check_if_ok(email, token) + print(f"result: {result}") + else: + print("No email provided.") + except json.JSONDecodeError: print("Invalid JSON") @@ -120,7 +205,7 @@ async def save_webm_stream(websocket): if binary_data: process.stdin.write(message) - count += len(message) + count += len(message) else: process.stdin.write(message) @@ -191,6 +276,10 @@ async def save_webm_stream(websocket): cv2.imwrite(f'face_{i + 1}.png', local_frame[top:bottom, left:right]) await websocket.send(json.dumps({"stage": 3})) + if email: + await update_user_status(email) + else: + print("No email provided.") break await websocket.send(json.dumps({"stage": 2, "faceCount": face_count, "faceWidth1" : face_width1, "faceWidth2" : face_width2}))