# Copyright (C) 2019  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import base64

from django.utils.encoding import force_str

from passerelle.base.models import ApiUser
from passerelle.base.signature import sign_query
from passerelle.utils import get_request_users


def test_get_request_users_publik_signature(db, rf):
    request = rf.get('/?' + sign_query('orig=orig', key='publikkey'))
    assert get_request_users(request) == []

    api_user = ApiUser.objects.create(keytype='SIGN', username='orig', key='publikkey')
    assert get_request_users(request) == [api_user]

    request = rf.get('/?orig=orig&signature=xxx')
    assert get_request_users(request) == []


def test_get_request_users_apikey(db, rf):
    request = rf.get('/', data={'apikey': 'apikey'})
    assert get_request_users(request) == []

    api_user = ApiUser.objects.create(keytype='API', key='apikey')
    assert get_request_users(request) == [api_user]


def test_get_request_users_http_auth_basic(db, rf):
    api_user = ApiUser.objects.create(keytype='SIGN', username='john', key='password')
    encoded = force_str(base64.b64encode(b'john:password'))
    request = rf.get('/', HTTP_AUTHORIZATION='Basic ' + encoded)
    assert get_request_users(request) == [api_user]


def test_get_request_users_http_auth_invalid(db, rf):
    request = rf.get('/', HTTP_AUTHORIZATION='')
    assert get_request_users(request) == []

    # no param
    request = rf.get('/', HTTP_AUTHORIZATION='Basic')
    assert get_request_users(request) == []

    # invalid base64
    request = rf.get('/', HTTP_AUTHORIZATION='Basic xx')
    assert get_request_users(request) == []

    # missing : in decoded base64
    request = rf.get('/', HTTP_AUTHORIZATION='Basic ' + force_str(base64.b64encode(b'x')))
    assert get_request_users(request) == []

    # other schemes are ignored
    request = rf.get('/', HTTP_AUTHORIZATION='Bearer')
    assert get_request_users(request) == []
    request = rf.get('/', HTTP_AUTHORIZATION='Digest kjkjlkjlkjljlkj')
    assert get_request_users(request) == []
