Пример #1
0
class ViewEmailLoginTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        # Set up data for the whole TestCase
        cls.new_user: User = User.objects.create(
            email="*****@*****.**",
            membership_started_at=datetime.now() - timedelta(days=5),
            membership_expires_at=datetime.now() + timedelta(days=5),
            slug="ujlbu4"
        )

        cls.broker = brokers.get_broker()
        cls.assertTrue(cls.broker.ping(), 'broker is not available')

    def setUp(self):
        self.client = HelperClient(user=self.new_user)

        self.broker.purge_queue()

    def test_login_by_email_positive(self):
        # when
        response = self.client.post(reverse('email_login'),
                                    data={'email_or_login': self.new_user.email, })

        # then
        self.assertContains(response=response, text="Вам отправлен код!", status_code=200)
        issued_code = Code.objects.filter(recipient=self.new_user.email).get()
        self.assertIsNotNone(issued_code)

        # check email was sent
        packages = self.broker.dequeue()
        task_signed = packages[0][1]
        task = SignedPackage.loads(task_signed)
        self.assertEqual(task['func'].__name__, 'send_auth_email')
        self.assertEqual(task['args'][0].id, self.new_user.id)
        self.assertEqual(task['args'][1].id, issued_code.id)

        # check notify wast sent
        packages = self.broker.dequeue()
        task_signed = packages[0][1]
        task = SignedPackage.loads(task_signed)
        self.assertEqual(task['func'].__name__, 'notify_user_auth')
        self.assertEqual(task['args'][0].id, self.new_user.id)
        self.assertEqual(task['args'][1].id, issued_code.id)

        # it's not yet authorised, only code was sent
        self.assertFalse(self.client.is_authorised())

    def test_login_user_not_exist(self):
        response = self.client.post(reverse('email_login'),
                                    data={'email_or_login': '******', })
        self.assertContains(response=response, text="Такого юзера нет 🤔", status_code=200)

    def test_secret_hash_login(self):
        response = self.client.post(reverse('email_login'),
                                    data={'email_or_login': self.new_user.secret_auth_code, })

        self.assertRedirects(response=response, expected_url=f'/user/{self.new_user.slug}/',
                             fetch_redirect_response=False)
        self.assertTrue(self.client.is_authorised())

    def test_secret_hash_user_not_exist(self):
        response = self.client.post(reverse('email_login'),
                                    data={'email_or_login': '******', })
        self.assertContains(response=response, text="Такого юзера нет 🤔", status_code=200)

    @skip("todo")
    def test_secret_hash_cancel_user_deletion(self):
        # todo: mark user as deleted
        self.assertTrue(False)

    def test_email_login_missed_input_data(self):
        response = self.client.post(reverse('email_login'), data={})
        self.assertRedirects(response=response, expected_url=f'/auth/login/',
                             fetch_redirect_response=False)

    def test_email_login_wrong_method(self):
        response = self.client.get(reverse('email_login'))
        self.assertRedirects(response=response, expected_url=f'/auth/login/',
                             fetch_redirect_response=False)

        response = self.client.put(reverse('email_login'))
        self.assertRedirects(response=response, expected_url=f'/auth/login/',
                             fetch_redirect_response=False)

        response = self.client.delete(reverse('email_login'))
        self.assertRedirects(response=response, expected_url=f'/auth/login/',
                             fetch_redirect_response=False)
Пример #2
0
class ViewsAuthTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        # Set up data for the whole TestCase
        cls.new_user: User = User.objects.create(
            email="*****@*****.**",
            membership_started_at=datetime.now() - timedelta(days=5),
            membership_expires_at=datetime.now() + timedelta(days=5),
            slug="ujlbu4"
        )

    def setUp(self):
        self.client = HelperClient(user=self.new_user)

    def test_join_anonymous(self):
        response = self.client.get(reverse('join'))
        # check auth/join.html is rendered
        self.assertContains(response=response, text="Всегда рады новым членам", status_code=200)

    def test_join_authorised(self):
        self.client.authorise()

        response = self.client.get(reverse('join'))
        self.assertRedirects(response=response, expected_url=f'/user/{self.new_user.slug}/',
                             fetch_redirect_response=False)

    def test_login_anonymous(self):
        response = self.client.get(reverse('login'))
        # check auth/join.html is rendered
        self.assertContains(response=response, text="Вход по почте или нику", status_code=200)

    def test_login_authorised(self):
        self.client.authorise()

        response = self.client.get(reverse('login'))
        self.assertRedirects(response=response, expected_url=f'/user/{self.new_user.slug}/',
                             fetch_redirect_response=False)

    def test_logout_success(self):
        self.client.authorise()

        response = self.client.post(reverse('logout'))

        self.assertRedirects(response=response, expected_url=f'/', fetch_redirect_response=False)
        self.assertFalse(self.client.is_authorised())

    def test_logout_unauthorised(self):
        response = self.client.post(reverse('logout'))
        self.assertTrue(self.client.is_access_denied(response))

    def test_logout_wrong_method(self):
        self.client.authorise()

        response = self.client.get(reverse('logout'))
        self.assertEqual(response.status_code, HttpResponseNotAllowed.status_code)

        response = self.client.put(reverse('logout'))
        self.assertEqual(response.status_code, HttpResponseNotAllowed.status_code)

        response = self.client.delete(reverse('logout'))
        self.assertEqual(response.status_code, HttpResponseNotAllowed.status_code)

    def test_debug_dev_login_unauthorised(self):
        response = self.client.post(reverse('debug_dev_login'))
        self.assertTrue(self.client.is_authorised())

        me = self.client.print_me()
        self.assertIsNotNone(me['id'])
        self.assertEqual(me['email'], '*****@*****.**')
        self.assertTrue(me['is_email_verified'])
        self.assertTrue(me['slug'], 'dev')
        self.assertEqual(me['moderation_status'], 'approved')
        self.assertEqual(me['roles'], ['god'])
        # todo: check created post (intro)

    def test_debug_dev_login_authorised(self):
        self.client.authorise()

        response = self.client.post(reverse('debug_dev_login'))
        self.assertTrue(self.client.is_authorised())

        me = self.client.print_me()
        self.assertTrue(me['slug'], self.new_user.slug)

    def test_debug_random_login_unauthorised(self):
        response = self.client.post(reverse('debug_random_login'))
        self.assertTrue(self.client.is_authorised())

        me = self.client.print_me()
        self.assertIsNotNone(me['id'])
        self.assertIn('@random.dev', me['email'])
        self.assertTrue(me['is_email_verified'])
        self.assertEqual(me['moderation_status'], 'approved')
        self.assertEqual(me['roles'], [])
Пример #3
0
class TestStripeWebhookView(TestCase):

    def setUp(self):
        self.client = HelperClient()

        self.existed_user: User = User.objects.create(
            email="*****@*****.**",
            membership_started_at=datetime.now() - timedelta(days=5),
            membership_expires_at=datetime.now() + timedelta(days=5),
            slug="ujlbu4"
        )

    @staticmethod
    def read_json_event(event_file_name):
        current_dir = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(current_dir, f'./_stubs/{event_file_name}.json')
        with open(file_path, 'r') as f:
            json_event = yaml.safe_load(f.read())

        return json_event

    def test_event_checkout_session_completed_positive(self):
        # links:
        #   https://stripe.com/docs/webhooks/signatures
        #   https://stripe.com/docs/api/events/object

        # given
        product = PRODUCTS["club1"]
        opened_payment: Payment = Payment.create(reference=f"random-reference-{uuid.uuid4()}",
                                                 user=self.existed_user,
                                                 product=product)

        strip_secret = "stripe_secret"
        with self.settings(STRIPE_WEBHOOK_SECRET=strip_secret):
            json_event = self.read_json_event('checkout.session.completed')
            json_event['data']['object']['id'] = opened_payment.reference

            timestamp = int(time.time())
            signed_payload = f"{timestamp}.{json.dumps(json_event)}"
            computed_signature = WebhookSignature._compute_signature(signed_payload, strip_secret)

            # when
            header = {'HTTP_STRIPE_SIGNATURE': f't={timestamp},v1={computed_signature}'}
            response = self.client.post(reverse("stripe_webhook"), data=json_event,
                                        content_type='application/json', **header)

            # then
            self.assertEqual(response.status_code, 200)
            # subscription prolongated
            user = User.objects.get(id=self.existed_user.id)
            self.assertAlmostEquals(user.membership_expires_at,
                                    self.existed_user.membership_expires_at + product['data']['timedelta'],
                                    delta=timedelta(seconds=10))

    @skip("do we need throw error in case payment not found?")
    def test_event_checkout_session_completed_negative_payment_not_found(self):
        # given
        strip_secret = "stripe_secret"
        with self.settings(STRIPE_WEBHOOK_SECRET=strip_secret):
            json_event = self.read_json_event('checkout.session.completed')
            json_event['data']['object']['id'] = "some-payment-reference-not-existed"  # not existed payment reference

            timestamp = int(time.time())
            signed_payload = f"{timestamp}.{json.dumps(json_event)}"
            computed_signature = WebhookSignature._compute_signature(signed_payload, strip_secret)

            # when
            header = {'HTTP_STRIPE_SIGNATURE': f't={timestamp},v1={computed_signature}'}
            response = self.client.post(reverse("stripe_webhook"), data=json_event,
                                        content_type='application/json', **header)

            # then
            self.assertEqual(response.status_code, 409)  # conflict due to payment not found (let it try latter)
            # subscription expiration not prolongated
            user = User.objects.get(id=self.existed_user.id)
            self.assertEqual(user.membership_expires_at, self.existed_user.membership_expires_at)

    def test_event_invoice_paid_with_billing_reason_subscription_create_positive(self):
        # links:
        #   https://stripe.com/docs/webhooks/signatures
        #   https://stripe.com/docs/api/events/object

        # given
        strip_secret = "stripe_secret"
        with self.settings(STRIPE_WEBHOOK_SECRET=strip_secret):
            json_event = self.read_json_event('invoice.paid')
            json_event['data']['object']['id'] = f'payment-id-{uuid.uuid4()}'
            json_event['data']['object']['billing_reason'] = "subscription_create"

            timestamp = int(time.time())
            signed_payload = f"{timestamp}.{json.dumps(json_event)}"
            computed_signature = WebhookSignature._compute_signature(signed_payload, strip_secret)

            # when
            header = {'HTTP_STRIPE_SIGNATURE': f't={timestamp},v1={computed_signature}'}
            response = self.client.post(reverse("stripe_webhook"), data=json_event,
                                        content_type='application/json', **header)

            # then
            self.assertEqual(response.status_code, 200)
            # subscription not prolonging, cause it assumes it has already done in `checkout.session.completed` event
            user = User.objects.get(id=self.existed_user.id)
            self.assertEqual(user.membership_expires_at, self.existed_user.membership_expires_at)

    def test_event_invoice_paid_with_billing_reason_subscription_cycle_positive(self):
        # given
        strip_secret = "stripe_secret"
        with self.settings(STRIPE_WEBHOOK_SECRET=strip_secret):
            self.existed_user.stripe_id = f'stripe-id-{uuid.uuid4()}'
            self.existed_user.save()

            json_event = self.read_json_event('invoice.paid')
            json_event['data']['object']['id'] = f'payment-id-{uuid.uuid4()}'
            json_event['data']['object']['billing_reason'] = "subscription_cycle"
            json_event['data']['object']['customer'] = self.existed_user.stripe_id
            product = PRODUCTS['club3_recurrent_yearly']
            json_event['data']['object']['lines']["data"][0]["plan"]["id"] = product['stripe_id']

            timestamp = int(time.time())
            signed_payload = f"{timestamp}.{json.dumps(json_event)}"
            computed_signature = WebhookSignature._compute_signature(signed_payload, strip_secret)

            # when
            header = {'HTTP_STRIPE_SIGNATURE': f't={timestamp},v1={computed_signature}'}
            response = self.client.post(reverse("stripe_webhook"), data=json_event,
                                        content_type='application/json', **header)

            # then
            # subscription prolonged
            self.assertEqual(response.status_code, 200)
            # subscription prolonged
            user = User.objects.get(id=self.existed_user.id)
            self.assertAlmostEquals(user.membership_expires_at,
                                    self.existed_user.membership_expires_at + product['data']['timedelta'],
                                    delta=timedelta(seconds=10))

    @skip("do we need throw error in case payment not found?")
    def test_event_invoice_paid_negative_user_not_found(self):
        # given
        strip_secret = "stripe_secret"
        with self.settings(STRIPE_WEBHOOK_SECRET=strip_secret):
            strip_secret = "stripe_secret"
            with self.settings(STRIPE_WEBHOOK_SECRET=strip_secret):
                self.existed_user.stripe_id = f'stripe-id-{uuid.uuid4()}'
                self.existed_user.save()

                json_event = self.read_json_event('invoice.paid')
                json_event['data']['object']['id'] = f'payment-id-{uuid.uuid4()}'
                json_event['data']['object']['billing_reason'] = "subscription_cycle"
                json_event['data']['object']['customer'] = "not-existed-user"

                timestamp = int(time.time())
                signed_payload = f"{timestamp}.{json.dumps(json_event)}"
                computed_signature = WebhookSignature._compute_signature(signed_payload, strip_secret)

                # when
                header = {'HTTP_STRIPE_SIGNATURE': f't={timestamp},v1={computed_signature}'}
                response = self.client.post(reverse("stripe_webhook"), data=json_event,
                                            content_type='application/json', **header)

                # then
                self.assertEqual(response.status_code, 409)  # conflict due to payment not found (let it try latter)
                # subscription expiration not prolonged
                user = User.objects.get(id=self.existed_user.id)
                self.assertEqual(user.membership_expires_at, self.existed_user.membership_expires_at)

    def test_event_customer_updated_positive(self):
        strip_secret = "stripe_secret"
        with self.settings(STRIPE_WEBHOOK_SECRET=strip_secret):
            self.assertEqual(self.existed_user.stripe_id, None)

            json_event = self.read_json_event('customer.updated')
            json_event['data']['object']['email'] = self.existed_user.email

            timestamp = int(time.time())
            signed_payload = f"{timestamp}.{json.dumps(json_event)}"
            computed_signature = WebhookSignature._compute_signature(signed_payload, strip_secret)

            # when
            header = {'HTTP_STRIPE_SIGNATURE': f't={timestamp},v1={computed_signature}'}
            response = self.client.post(reverse("stripe_webhook"), data=json_event,
                                        content_type='application/json', **header)

            # then
            self.assertEqual(response.status_code, 200)
            # subscription not prolonging, cause it assumes it has already done in `checkout.session.completed` event
            user = User.objects.get(id=self.existed_user.id)
            self.assertEqual(user.stripe_id, json_event['data']['object']['id'])
            self.assertEqual(user.membership_expires_at, self.existed_user.membership_expires_at)

    def test_negative_no_payload(self):
        header = {'HTTP_STRIPE_SIGNATURE': 'xxx'}
        response = self.client.post(reverse("stripe_webhook"), content_type='application/json', **header)

        self.assertEqual(response.status_code, 400)

    def test_negative_no_signature(self):
        response = self.client.post(reverse("stripe_webhook"), data={"xxx": 1}, content_type='application/json')

        self.assertEqual(response.status_code, 400)

    def test_negative_invalid_signature(self):
        header = {'HTTP_STRIPE_SIGNATURE': 'invalid-signature'}
        with self.settings(STRIPE_WEBHOOK_SECRET="stripe_secret"):
            response = self.client.post(reverse("stripe_webhook"), data={"xxx": 1}, content_type='application/json',
                                        **header)

            self.assertEqual(response.status_code, 400)