Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
hub-client / dockerhub / middleware.py
Size: Mime:
# Copyright (c) 2015 Docker, Inc. All rights reserved.

import logging
import json

from django.core.exceptions import PermissionDenied
from django.utils.functional import SimpleLazyObject
from django.http import HttpResponse

from rest_framework import status

from dockerhub import utils

logger = logging.getLogger(__name__)


def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = utils.get_user(request)
    return request._cached_user


class AuthenticationMiddleware(object):
    def process_request(self, request):
        assert hasattr(request, 'session'), "The Hub authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."

        request.user = SimpleLazyObject(lambda: get_user(request))


class UserUUIDSessionMiddleware(object):
    def process_request(self, request):
        try:
            request.session['_user_uuid'] = request.user.uuid.hex
        except AttributeError:
            logger.info('User `{}` does not have a UUID'.format(request.user))
            pass


class DockerHubAPIExceptionMiddleware(object):
    def process_exception(self, request, exception):
        if request.META.get('PATH_INFO', '').startswith('/v2/'):
            if isinstance(exception, PermissionDenied):
                # Swagger is under /v2, but doesn't deal with permission error well
                status_code = status.HTTP_401_UNAUTHORIZED
                detail = str(exception)
            else:
                logger.error(
                    'Middleware caught 500 error: %s', exception,
                    extra=dict(context=request.path_info,
                               method=request.method,
                               path=request.get('RAW_URI', request.path_info)))

                status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
                detail = 'We have problem processing your request. '\
                         'This error has been logged and we will look into it.'

            response_data = {'error': True, 'detail': detail}
            return HttpResponse(
                json.dumps(response_data),
                content_type="application/json",
                status=status_code
            )