Beispiel #1
0
    def check_plugin(self, request):
        if self.plugin == 0:
            return True, ''
        elif self.plugin == 1:
            auth = BasicAuthentication()
            try:
                user, password = auth.authenticate(request)
            except:
                return False, 'Authentication credentials were not provided'

            if self.consumers.filter(user=user):
                return True, ''
            else:
                return False, 'Permission not Allowed'
        elif self.plugin == 2:
            apikey = request.META.get('HTTP_APIKEY')
            consumers = self.consumers.all()
            for consumer in consumers:
                if apikey == consumer.apikey:
                    return True, ''
            return False, 'Apikey Needed'
        elif self.plugin == 3:
            consumer = self.consumers.all()
            if not consumer:
                return False, 'consumer need'
            request.META['HTTP_AUTHORIZATION'] = requests.auth._basic_auth_str(
                consumer[0].user.username, consumer[0].apikey)
            return True, ''
        else:
            raise NotImplementedError('Plugin %d not implementd' % self.plugin)
Beispiel #2
0
    def check_plugin(self, request):
        if self.plugin == 0:
            return True, ''

        elif self.plugin == 1:
            auth = BasicAuthentication()
            try:
                user, password = auth.authenticate(request)
            except:
                return False, 'Authentication credentials were not provided'

            if self.consumers.filter(user=user):
                return True, ''
            else:
                return False, Response('permission not allowed',
                                       status.HTTP_403_FORBIDDEN)
        elif self.plugin == 2:
            apikey = request.META.get('HTTP_APIKEY')
            consumers = self.consumers.all()
            for consumer in consumers:
                if apikey == consumer.apikey:
                    return True, ''
            return False, 'apikey need'
        elif self.plugin == 3:
            consumer = self.consumers.all()
            if not consumer:
                return False, 'consumer need'
            request.META['HTTP_AUTHORIZATION'] = requests.auth._basic_auth_str(
                consumer[0].user.username, consumer[0].apikey)
            return True, ''
        elif self.plugin == 4:
            authenticator = self.authenticators.all()
            if not authenticator:
                return False, 'authorizer need'
            else:
                authenticator = authenticator[0]
                headers = dict()
                for key in authenticator.headers.split(','):
                    value = request.headers.get(key)
                    if value is not None:
                        headers[key] = value
                _logger.info('Authenticating via: %s' %
                             authenticator.remote_url)
                response = requests.post(authenticator.remote_url,
                                         headers=headers,
                                         timeout=self.TIME_OUT)
                authed = response.headers.get(self.AUTHED_HEADER_NAME)
                if authed is None:
                    return False, 'authorized header needed'
                elif authed:
                    # return {headers}
                    data = response.json()
                    data = data.get('ret') or data
                    return True, data
                else:
                    return False, self.to_rest_response(response)
        else:
            return False, Response("plugin %d not implemented" % self.plugin,
                                   status=status.HTTP_501_NOT_IMPLEMENTED)
Beispiel #3
0
 def middleware(request):
     if not request.path.startswith("/api/"):
         auth = request.META.get("HTTP_AUTHORIZATION")
         if auth and auth.startswith("Basic "):
             backend = BasicAuthentication()
             user, _ = backend.authenticate(request)
             request.user = user
     return get_response(request)
Beispiel #4
0
def authenticate(request):

	""" 
	If recruiter makes it into this function, they are already authenticated.
	Send back the JSON object for the recruiter.
	"""

	authenticator = BasicAuthentication()

	recruiter_tuple = authenticator.authenticate(request)

	recruiter = recruiter_tuple[0]

	return HttpResponse("true")
Beispiel #5
0
    def create(self, request):
        user = BasicAuthentication().authenticate(request)
        if user is None:
            return Response({'message': "Forbidden"},
                            status=status.HTTP_403_FORBIDDEN)

        data = JSONParser().parse(request)
        api_serializer = OLTPBenchSerializer(data=data)
        if not api_serializer.is_valid():
            return Response(api_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

        api_serializer.save()
        db_serializer = OLTPBenchResultSerializer(
            data=api_serializer.instance.convert_to_db_json())
        if not db_serializer.is_valid():
            return Response(db_serializer.errors,
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        try:
            db_serializer.save()
        except Exception as e:
            return Response({'message': str(e)},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response(api_serializer.validated_data,
                        status=status.HTTP_201_CREATED)
    def resolve_user(self, request, target):
        """ retrieve a gestalt that was authenticated via HTTP authentication

        Fail silently and return None if no HTTP authentication data was transmitted. An HTTP
        authentication can be forced later by responding with a 401 HTTP status code. This relaxed
        approach allows to combine this authentication method with other fallback methods.
        """
        auth = BasicAuthentication()
        try:
            result = auth.authenticate(request)
        except (exceptions.NotAuthenticated, exceptions.AuthenticationFailed):
            return None
        if result is None:
            return None
        else:
            return result[0].gestalt
    def create(self, request):
        """ First check that the an authorized user posted the request. Then validate the API request body. Next convert
        the request body into a format suitable for the database. Finally, store the new artifact stats result in the
        database. """
        user = BasicAuthentication().authenticate(request)
        if user is None:
            logger.debug('Invalid authentication')
            return Response({'message': 'Forbidden'},
                            status=HTTP_403_FORBIDDEN)

        data = JSONParser().parse(request)
        api_serializer = ArtifactStatsSerializer(data=data)
        if not api_serializer.is_valid():
            logger.debug(f'Bad Request: {api_serializer.errors}')
            return Response(api_serializer.errors, status=HTTP_400_BAD_REQUEST)

        api_serializer.save()
        db_serializer = ArtifactStatsResultSerializer(
            data=api_serializer.instance.convert_to_db_json())
        db_serializer.smudge_timestamp()
        if not db_serializer.is_valid():
            logger.error(f'Invalid db_serializer: {db_serializer.errors}')
            return Response(db_serializer.errors,
                            status=HTTP_500_INTERNAL_SERVER_ERROR)
        try:
            db_serializer.save()
        except Exception as err:
            logger.error(f'ArtifactStatsViewSet create failed: {err}')
            return Response({'message': str(err)},
                            status=HTTP_500_INTERNAL_SERVER_ERROR)

        return Response(api_serializer.validated_data, status=HTTP_201_CREATED)
    def resolve_user(self, request, target):
        """ retrieve a gestalt that was authenticated via HTTP authentication

        Fail silently and return None if no HTTP authentication data was transmitted. An HTTP
        authentication can be forced later by responding with a 401 HTTP status code. This relaxed
        approach allows to combine this authentication method with other fallback methods.
        """
        auth = BasicAuthentication()
        try:
            result = auth.authenticate(request)
        except (exceptions.NotAuthenticated, exceptions.AuthenticationFailed):
            return None
        if result is None:
            return None
        else:
            return result[0].gestalt
Beispiel #9
0
 def post(self, request, format='json'):
     username = request.data.get('username')
     password = request.data.get('password')
     authobj = BasicAuthentication()
     try:
         roleList = []
         res = authobj.authenticate_credentials(username, password)
         user = userRoles.objects.filter(user=User.objects.get(
             username=username))
         for indUser in user:
             for j in indUser.roles.all():
                 roleList.append(j.roleName)
         response = {"status": "1", "roles": roleList}
         return Response(response)
     except Exception as e:
         response = {"status": "0", "description": str(e)}
         return Response(response)
Beispiel #10
0
    def get_direct_queryset(cls, request, **initkwargs):
        """
        TODO: Temporary until a better way is found
        """
        self = cls(**initkwargs)
        request = Request(request, authenticators=(BasicAuthentication(), SessionAuthentication()))
        self.request = request

        return self.get_queryset()
Beispiel #11
0
 def get_authenticators(self):
     try:
         # check if you are the User-Agent of ODK
         # https://github.com/opendatakit/collect/blob/81b105cef60a113efd1954d782648219ec4733e6/collect_app/src/main/java/org/odk/collect/android/application/Collect.java#L221
         if 'org.odk.collect.android' in self.request.META[
                 'HTTP_USER_AGENT']:
             return [BasicAuthentication()]
     except Exception:
         pass
     return [CsrfExemptSessionAuthentication()]
Beispiel #12
0
    def auth_request(self, **kwargs):

        # check for caching token
        if 'caching' in settings.G3WADMIN_LOCAL_MORE_APPS and 'g3wsuite_caching_token' in self.request.GET and \
                settings.TILESTACHE_CACHE_TOKEN == self.request.GET['g3wsuite_caching_token']:
            return True

        if self.request.user.has_perm('qdjango.view_project', self.project) or\
                get_anonymous_user().has_perm('qdjango.view_project', self.project):
            return True
        else:
            # try to authenticate by http basic authentication
            try:
                ba = BasicAuthentication()
                user, other = ba.authenticate(self.request)
                return user.has_perm('qdjango.view_project', self.project)
            except Exception as e:
                print(e)
                pass

            raise AuthForbiddenRequest()
Beispiel #13
0
    def post(self, request, format=None):
        """
        This leverages the HTTP basic authentication middleware
        that exists for authenticating requests to the application.

        The difference lies in where the user data is coming from.
        This data will be a part of the request payload, probably as
        Base64 encoded data.
        """
        auth = BasicAuthentication()

        serializer = UserAuthSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        encoded = serializer.data['value']
        credentials = decode_credentials(encoded)

        user = auth.authenticate_credentials(
            credentials['username'], credentials['password']
        )
        instance = user[0]
        serialized_user = UserSerializer(instance)

        return Response({'user': serialized_user.data})
Beispiel #14
0
    def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)
        data = {}

        # user = SessionAuthentication.authenticate(request)
        # if user != None:
        #     data['user'] = user
        #     return Response(data)
        # else:
        #     pass

        if serializer.is_valid():
            user = BasicAuthentication(request)
            print(user)
            if user == None:
                data['response'] = 'User not found'
                return Response(data, status=status.HTTP_404_NOT_FOUND)
            else:
                data['username'] = user.username
                return Response(data, status=status.HTTP_200_OK)
        else:
            return Response({'Not Found': 'Bs'},
                            status=status.HTTP_404_NOT_FOUND)
Beispiel #15
0
 def test_basic_authentication_raises_error_if_user_not_found(self):
     auth = BasicAuthentication()
     with pytest.raises(exceptions.AuthenticationFailed):
         auth.authenticate_credentials('invalid id', 'invalid password')
Beispiel #16
0
from django.http import HttpResponseNotFound
from django.shortcuts import get_object_or_404
from django.shortcuts import render

from patchwork.filters import DelegateFilter
from patchwork.forms import BundleForm
from patchwork.forms import DeleteBundleForm
from patchwork.models import Bundle
from patchwork.models import BundlePatch
from patchwork.models import Project
from patchwork.views import generic_list
from patchwork.views.utils import bundle_to_mbox

if settings.ENABLE_REST_API:
    from rest_framework.authentication import BasicAuthentication  # noqa
    basic_auth = BasicAuthentication()
else:
    basic_auth = None


@login_required
def bundle_list(request, project_id=None):
    project = None

    if request.method == 'POST':
        form_name = request.POST.get('form_name', '')

        if form_name == DeleteBundleForm.name:
            form = DeleteBundleForm(request.POST)
            if form.is_valid():
                bundle = get_object_or_404(Bundle,
class AuthFsDavView(RestAuthViewMixIn, DavView):
    authentications = (BasicAuthentication(), SessionAuthentication())
Beispiel #18
0
 def get_authenticators(self):
     return [BasicAuthentication(), NoCsrfSessionAuthentication(), JWTAuthentication()]
 def test_basic_authentication_raises_error_if_user_not_found(self):
     auth = BasicAuthentication()
     with pytest.raises(exceptions.AuthenticationFailed):
         auth.authenticate_credentials('invalid id', 'invalid password')
Beispiel #20
0
 def get_authenticators(self):
     if self.request.method == "GET":
         return
     return (BasicAuthentication(), )