import logging from rest_framework.response import Response from rest_framework.permissions import AllowAny from django.utils.translation import gettext as _ from django.conf import settings from pingcap_sso.api.base import Endpoint from pingcap_sso.signals import pingcap_lark_staff_resigned logger = logging.getLogger(__name__) class PingCAPLarkWebhookEndpoint(Endpoint): # Configure: https://open.feishu.cn/app/cli_a5f2b513de3f900c/event # Doc: https://open.feishu.cn/document/server-docs/event-subscription-guide/overview permission_classes = (AllowAny, ) def post(self, request, *args, **kwargs): data = request.data if data.get('type') == 'url_verification': return Response({ 'challenge': data.get('challenge'), }) try: schema = data['schema'] header = data['header'] token = header['token'] event_type = header['event_type'] event_body = data['event']['object'] except Exception: return Response({ 'detail': _('wrong params') }, 400) if schema != '2.0': return Response({ 'detail': _('wrong schema') }, 400) if token != settings.PINGCAP_LARK_APP_WEBHOOK_TOKEN: return Response({ 'detail': _('invalid token') }, 400) logger.info(f'PingCAP Lark webhook received event: {data}') if event_type == 'contact.user.deleted_v3': pingcap_lark_staff_resigned.send( sender=self.__class__, org='global', event=event_body ) return Response({ 'challenge': data.get('challenge'), }) class PingCAPCNLarkWebhookEndpoint(Endpoint): permission_classes = (AllowAny, ) def post(self, request, *args, **kwargs): data = request.data if data.get('type') == 'url_verification': return Response({ 'challenge': data.get('challenge'), }) try: schema = data['schema'] header = data['header'] token = header['token'] event_type = header['event_type'] event_body = data['event']['object'] except Exception: return Response({ 'detail': _('wrong params') }, 400) if schema != '2.0': return Response({ 'detail': _('wrong schema') }, 400) if token != settings.PINGCAP_CN_LARK_APP_WEBHOOK_TOKEN: return Response({ 'detail': _('invalid token') }, 400) logger.info(f'PingCAP CN Lark webhook received event: {data}') if event_type == 'contact.user.deleted_v3': pingcap_lark_staff_resigned.send( sender=self.__class__, org='cn', event=event_body ) return Response({ 'challenge': data.get('challenge'), })