diff --git a/codes/services.py b/codes/services.py new file mode 100644 index 0000000..4449084 --- /dev/null +++ b/codes/services.py @@ -0,0 +1,82 @@ +import random +import string +import requests + +from django.db import IntegrityError +from django.conf import settings +from django.utils.timezone import now + +from rest_framework.views import APIView +from rest_framework.response import Response +from rest_framework import status + +from .models import CertificationCode + +from common.models.choiceModels import CertificateCodeUseType +from common.utils.codeManger import set_expire + +from solapi import SolapiMessageService +from solapi.model import RequestMessage + +# from .schemas import send_sms_post_schema # Swagger나 drf-spectacular 등에 사용되는 데코레이터 + +class CertificateService: + @staticmethod + def send(code, identifier): + pass + + # 유효시간 5분 설정해서 저장, 이전 같은 번호 sms 요청 값들 is_used=True로 바꾸기 + @staticmethod + def save_certificate_info(use_type: CertificateCodeUseType, code, identifier): + try: + befores = CertificationCode.objects.filter( + use_type=use_type, + identifier=identifier, + is_used=False + ).update(is_used=True) + instance = CertificationCode.objects.create( + use_type = use_type, + code = code, + expire_at = set_expire(5), + identifier = identifier + ) + return True + except IntegrityError as e: + return False + + # code 체크 후 is_used=True로 설정 + @staticmethod + def check_code(use_type: CertificateCodeUseType, code, identifier): + if check := CertificationCode.objects.filter( + use_type=use_type, + identifier=identifier, + is_used=False, + expire_at__gte=now() + ).order_by('-created_at').first(): + + if check.code == code: + check.is_used=True + check.save() + return True + return False + +class SmsService(CertificateService): + # 같은 전번에 대해 요청 텀 설정은 views 단에서 하자. + @staticmethod + def send(code, identifier): + message_service = SolapiMessageService( + api_key = settings.SOLAPI_API_KEY, api_secret = settings.SOLAPI_API_SECRET + ) + + message = RequestMessage( + from_ = settings.FROM_PHONE_NUMBER, + to = identifier, + text = "colio 서비스 회원가입 인증번호는 " + code +" 입니다." + ) + + try: + res = message_service.send(message) + return True + except Exception as e: + print(f"메시지 발송 실패: {str(e)}") + return False \ No newline at end of file