Esempio n. 1
0
    def post(self, request, *args, **kwargs):
        if self.alias_type.upper() not in api_settings.PASSWORDLESS_AUTH_TYPES:
            # Only allow auth types allowed in settings.
            return Response(status=status.HTTP_404_NOT_FOUND)

        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        if serializer.is_valid(raise_exception=True):
            # Validate -
            user = serializer.validated_data['user']
            # Create and send callback token
            success = TokenService.send_token(user, self.alias_type,
                                              self.token_type,
                                              **self.message_payload)

            # Respond With Success Or Failure of Sent
            if success:
                status_code = status.HTTP_200_OK
                response_detail = self.success_response
            else:
                status_code = status.HTTP_400_BAD_REQUEST
                response_detail = self.failure_response
            return Response({'detail': response_detail}, status=status_code)
        else:
            return Response(serializer.error_messages,
                            status=status.HTTP_400_BAD_REQUEST)
Esempio n. 2
0
    def post(self, request, *args, **kwargs):
        if self.alias_type.upper() not in api_settings.PASSWORDLESS_AUTH_TYPES:
            # Only allow auth types allowed in settings.
            return Response(status=status.HTTP_404_NOT_FOUND)

        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        if serializer.is_valid(raise_exception=True):
            # Validate
            user = serializer.validated_data['user']
            if self.alias_type == 'whatsapp' and not user.has_whatsapp_enabled:
                # Prevents sending tokens to contributor unless WhatsApp is enabled
                logger.debug(
                    f"Skipped sending notification to {user} having WhatsApp {user.has_whatsapp_enabled}"
                )
                message = 'WhatsApp communications must be enabled to receive tokens from CARPA via WhatsApp.'
                return Response({'detail': message},
                                status=status.HTTP_409_CONFLICT)

            # Create and send callback token
            success = TokenService.send_token(user, self.alias_type,
                                              **self.message_payload)

            # Respond With Success Or Failure of Sent
            if success:
                status_code = status.HTTP_200_OK
                response_detail = self.success_response
            else:
                status_code = status.HTTP_400_BAD_REQUEST
                response_detail = self.failure_response
            return Response({'detail': response_detail}, status=status_code)
        else:
            return Response(serializer.error_messages,
                            status=status.HTTP_400_BAD_REQUEST)
Esempio n. 3
0
    def post(self, request, *args, **kwargs):
        if self.alias_type.upper() not in api_settings.PASSWORDLESS_AUTH_TYPES:
            # Only allow auth types allowed in settings.
            return Response(status=status.HTTP_404_NOT_FOUND)
        try:
            user = Peoples.objects.get(mobile=self.request.data.get('mobile'))
        except Peoples.DoesNotExist:
            user = None
        # serializer = self.serializer_class(data=request.data, context={'request': request})
        # if serializer.is_valid(raise_exception=True):
        #     # Validate -
        #     if user is None:
        #         Peoples.objects.get(mobile=self.request.data.get('mobile')).delete()
        # Create and send callback token
        if user is not None:
            success = TokenService.send_token(user, self.alias_type,
                                              **self.message_payload)

            # Respond With Success Or Failure of Sent
            if success:
                status_code = status.HTTP_200_OK
                response_detail = self.success_response
            else:
                status_code = status.HTTP_400_BAD_REQUEST
                response_detail = self.failure_response
            return Response({'detail': response_detail}, status=status_code)
        else:
            return Response('شما در سیستم ثبت نشده اید.',
                            status=status.HTTP_400_BAD_REQUEST)
Esempio n. 4
0
    def post(self, request, *args, **kwargs):
        if self.alias_type.upper() not in api_settings.PASSWORDLESS_AUTH_TYPES:
            # Only allow auth types allowed in settings.
            return Response(status=status.HTTP_404_NOT_FOUND)

        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        if serializer.is_valid(raise_exception=True):
            # Validate -
            user = serializer.validated_data['user']
            template_name = None
            if api_settings.PASSWORDLESS_TEMPLATE_CHOICES:
                # Differing from original lib: we allow optional template and pass this to send_token
                template_idx = serializer.validated_data.get(
                    'template')  # default 1
                template_name = [
                    choice
                    for choice in api_settings.PASSWORDLESS_TEMPLATE_CHOICES
                    if choice[0] == template_idx
                ][0][1]
            # Create and send callback token
            success = TokenService.send_token(user,
                                              self.alias_type,
                                              template=template_name,
                                              **self.message_payload)

            # Respond With Success Or Failure of Sent
            if success:
                status_code = status.HTTP_200_OK
                response_detail = self.success_response
            else:
                status_code = status.HTTP_400_BAD_REQUEST
                response_detail = self.failure_response
            return Response({'detail': response_detail}, status=status_code)
        else:
            return Response(serializer.error_messages,
                            status=status.HTTP_400_BAD_REQUEST)
def update_alias_verification(sender, instance, **kwargs):
    """
    Flags a user's email as unverified if they change it.
    Optionally sends a verification token to the new endpoint.
    """
    if isinstance(instance, User):

        if instance.id:

            if api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFIED is True:
                """
                For marking email aliases as not verified when a user changes it.
                """
                email_field = api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME
                email_verified_field = api_settings.PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME

                # Verify that this is an existing instance and not a new one.
                try:
                    user_old = User.objects.get(
                        id=instance.id)  # Pre-save object
                    instance_email = getattr(instance,
                                             email_field)  # Incoming Email
                    old_email = getattr(user_old,
                                        email_field)  # Pre-save object email

                    if instance_email != old_email and instance_email != "" and instance_email is not None:
                        # Email changed, verification should be flagged
                        setattr(instance, email_verified_field, False)
                        if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True:
                            email_subject = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_SUBJECT
                            email_plaintext = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_PLAINTEXT_MESSAGE
                            email_html = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_TOKEN_HTML_TEMPLATE_NAME
                            message_payload = {
                                'email_subject': email_subject,
                                'email_plaintext': email_plaintext,
                                'email_html': email_html
                            }
                            success = TokenService.send_token(
                                instance, 'email', **message_payload)

                            if success:
                                logger.info(
                                    'drfpasswordless: Successfully sent email on updated address: %s'
                                    % instance_email)
                            else:
                                logger.info(
                                    'drfpasswordless: Failed to send email to updated address: %s'
                                    % instance_email)

                except User.DoesNotExist:
                    # User probably is just initially being created
                    return

            if api_settings.PASSWORDLESS_USER_MARK_MOBILE_VERIFIED is True:
                """
                For marking mobile aliases as not verified when a user changes it.
                """
                mobile_field = api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME
                mobile_verified_field = api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME

                # Verify that this is an existing instance and not a new one.
                try:
                    user_old = User.objects.get(
                        id=instance.id)  # Pre-save object
                    instance_mobile = getattr(instance,
                                              mobile_field)  # Incoming mobile
                    old_mobile = getattr(
                        user_old, mobile_field)  # Pre-save object mobile

                    if instance_mobile != old_mobile and instance_mobile != "" and instance_mobile is not None:
                        # Mobile changed, verification should be flagged
                        setattr(instance, mobile_verified_field, False)
                        if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True:
                            mobile_message = api_settings.PASSWORDLESS_MOBILE_MESSAGE
                            message_payload = {
                                'mobile_message': mobile_message
                            }
                            success = TokenService.send_token(
                                instance, 'mobile', **message_payload)

                            if success:
                                logger.info(
                                    'drfpasswordless: Successfully sent SMS on updated mobile: %s'
                                    % instance_mobile)
                            else:
                                logger.info(
                                    'drfpasswordless: Failed to send SMS to updated mobile: %s'
                                    % instance_mobile)

                except User.DoesNotExist:
                    # User probably is just initially being created
                    pass
Esempio n. 6
0
    def post(self, request, *args, **kwargs):
        # Only allow auth types allowed in settings.
        if self.alias_type.upper() not in api_settings.PASSWORDLESS_AUTH_TYPES:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        # NOTE: this potentially CREATES a User with the given alias (email/phone) and other user-data (depending on the settings),
        # if create=true was given and the User doesn't exist already
        if serializer.is_valid(raise_exception=True):
            user = serializer.validated_data['user']
            # Create and send callback token

            if serializer.validated_data.get(
                    "country", "") == "fi" and self.message_payload_fi != {}:
                payload = self.message_payload_fi.copy(
                )  # copy or we'll change the class-global dict...
            else:
                payload = self.message_payload.copy(
                )  # copy or we'll change the class-global dict...

            # If desktop=true is provided, we format the callback as a normal text and not a link (for use in desktop logins)
            # Set linkbase to an empty string in that case, as the placeholder for it is in the SMS template anyway.
            if serializer.validated_data.get('desktop', False):
                payload['desktop'] = True
                payload['linkbase'] = ''
            else:
                # If devlink=true is provided during the request, we use a different link base for the callback link, to support dev-apps
                if serializer.validated_data.get("country", "") == "fi":
                    payload[
                        "linkbase"] = api_settings.PASSWORDLESS_FI_LINK_BASE
                elif serializer.validated_data.get("devlink", False):
                    payload[
                        "linkbase"] = api_settings.PASSWORDLESS_DEV_LINK_BASE
                else:
                    payload[
                        'linkbase'] = api_settings.PASSWORDLESS_PROD_LINK_BASE

            if not user.is_active:  # in this case, mimic the user not being found at all (used for soft-deletion)
                return Response(status=status.HTTP_404_NOT_FOUND)

            if not user.is_demo:
                # This can fail for various reasons: an SMS can fail to reach a valid mobile number, an email can have
                # an incorrect domain. We get False back in those cases.
                send_success = TokenService.send_token(user, self.alias_type,
                                                       **payload)
            else:
                send_success = False

            if send_success:
                status_code = status.HTTP_200_OK
                response_detail = self.success_response
                response_code = None
            else:
                status_code = status.HTTP_400_BAD_REQUEST
                response_detail = self.failure_response
                response_code = 'sending_error'
            return Response({
                'detail': response_detail,
                'code': response_code
            },
                            status=status_code)
        else:
            return Response(serializer.error_messages,
                            status=status.HTTP_400_BAD_REQUEST)