import base64

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse

User = get_user_model()


class AuthTest(TestCase):
    fixtures = ["search/auth"]

    auth_headers = {
        "HTTP_AUTHORIZATION": "Basic "
        + base64.b64encode(
            bytes("superuser:912cf9812ffaccc168c3f04722eb4b66060c2c99e467fe51", "utf8")
        ).decode("utf8")
    }

    def test_auth_initialized(self):
        self.assertEqual(User.objects.count(), 2)

    def test_insufficient_rights(self):
        henk = User.objects.get(username="regularuser")
        self.client.force_login(henk)

        response = self.client.get(
            reverse("search:update_oscar_index"), **self.auth_headers
        )

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.url, "/manage/login/?next=/search/update_oscar_index/"
        )

    def test_sufficient_rights(self):
        henk = User.objects.get(username="admin")
        self.client.force_login(henk)

        response = self.client.get(
            reverse("search:update_oscar_index"), **self.auth_headers
        )

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, "/admin")

    def test_wrong_password(self):
        henk = User.objects.get(username="admin")
        self.client.force_login(henk)

        auth_headers = {
            "HTTP_AUTHORIZATION": "Basic "
            + base64.b64encode(bytes("superuser:verkeerd_password", "utf8")).decode(
                "utf8"
            )
        }

        response = self.client.get(reverse("search:update_oscar_index"), **auth_headers)

        self.assertEqual(response.status_code, 401)
