from __future__ import absolute_import

from django.contrib.auth.models import AnonymousUser, User
from django.utils.crypto import constant_time_compare
from rest_framework import exceptions
from rest_framework.authentication import (
    BasicAuthentication, get_authorization_header
)
from rest_framework.exceptions import AuthenticationFailed
from participant.models import Participant
from study.models import Study


class PaticipantBasicAuthentication(BasicAuthentication):
    def authenticate_header(self, request):
        return 'xBasic realm="%s"' % self.www_authenticate_realm

    def authenticate(self, request):
        participant = request.META.get('HTTP_PARTICIPANT_AUTHORIZATION')
        study = request.META.get('HTTP_STUDY_AUTHORIZATION')
        if not participant or not study:
            raise exceptions.NotAuthenticated

        try:
            user = Participant.objects.get(email=participant)
        except Participant.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such participant')

        return (user, study)

class StudyBasicAuthentication(BasicAuthentication):
    def authenticate_header(self, request):
        return 'xBasic realm="%s"' % self.www_authenticate_realm

    def authenticate(self, request):
        study = request.META.get('HTTP_STUDY_AUTHORIZATION')

        if not study:
            raise exceptions.NotAuthenticated

        try:
            user = Study.objects.get(title=study)
        except Participant.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such participant')

        return (user, None)