Ejemplo n.º 1
0
    def authenticate(self, request):
        LOG.debug('DummyCustomAuthentication: %s' % request.path)
        user = find_or_create_user(username='******', password='******')
        ensure_has_a_group(user)
        user = rewrite_user(user)
        user.is_active = True

        return (user, None)
Ejemplo n.º 2
0
  def authenticate(self, request):
    authorization_header = request.META.get('HTTP_AUTHORIZATION')

    if not authorization_header:
      LOG.debug('JwtAuthentication: no authorization header')
      return None

    header, access_token = authorization_header.split(' ')

    if header != 'Bearer':
      LOG.debug('JwtAuthentication: no Bearer header')
      return None

    if not access_token:
      LOG.debug('JwtAuthentication: no Bearer value')
      return None

    LOG.debug('JwtAuthentication: got access token %s' % access_token)

    try:
      payload = jwt.decode(
        access_token,
        'secret',
        algorithms=["RS256"],
        verify=AUTH.VERIFY_CUSTOM_JWT.get()
      )
    except jwt.DecodeError:
      raise exceptions.AuthenticationFailed('JwtAuthentication: Invalid token')
    except jwt.ExpiredSignatureError:
      raise exceptions.AuthenticationFailed('JwtAuthentication: Token expired')
    except Exception as e:
      raise exceptions.AuthenticationFailed(e)
    
    if payload.get('user') is None:
      LOG.debug('JwtAuthentication: no user ID in token')
      return None

    LOG.debug('JwtAuthentication: got user ID %s and tenant ID %s' % (payload.get('user'), payload.get('tenantId')))

    user = find_or_create_user(payload.get('user'), is_superuser=False)
    ensure_has_a_group(user)
    user = rewrite_user(user)

    # Persist the token (to reuse for communicating with external services as the user, e.g. Impala)
    if ENABLE_ORGANIZATIONS.get():
      user.token = access_token
    else:
      user.profile.update_data({'jwt_access_token': access_token})
      user.profile.save()

    return (user, None)
Ejemplo n.º 3
0
    def handle(self, *args, **options):

        LOG.info("Removing any orphaned docs")

        start = time.time()

        totalUsers = User.objects.filter().values_list("id", flat=True)
        totalDocs = Document2.objects.exclude(owner_id__in=totalUsers)
        docstorage_id = "docstorage" + str(uuid.uuid4())
        docstorage_id = docstorage_id[:30]
        LOG.info("Creating new owner for all orphaned docs: %s" %
                 docstorage_id)
        docstorage = find_or_create_user(docstorage_id)
        docstorage = rewrite_user(docstorage)
        userprofile = get_profile(docstorage)
        userprofile.first_login = False
        userprofile.save()
        ensure_has_a_group(docstorage)
        new_home_dir = Document2.objects.create_user_directories(docstorage)

        for doc in totalDocs:
            if not doc.type == "directory":
                new_dir_name = "recover-" + str(doc.owner_id)
                new_sub_dir = Directory.objects.create(
                    name=new_dir_name,
                    owner=docstorage,
                    parent_directory=new_home_dir)
                doc1 = doc.doc.get()
                doc.owner = docstorage
                doc1.owner = docstorage
                doc.parent_directory = new_sub_dir
                doc.save()
                doc1.save()
                Document.objects.sync()
                LOG.info(
                    "Migrating orphaned doc: %s : %s : %s : %s : to orphaned doc owner: %s"
                    % (doc.name, doc.type, doc.owner_id, doc.parent_directory,
                       docstorage_id))

        for doc in totalDocs:
            if doc.type == "directory":
                LOG.info("Deleting orphaned directory: %s : %s : %s" %
                         (doc.name, doc.type, doc.owner_id))
                doc.delete()

        end = time.time()
        elapsed = (end - start)
        LOG.info("Total time elapsed (seconds): %.2f" % elapsed)
Ejemplo n.º 4
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        """
    We also perform access logging in ``process_view()`` since we have the view function,
    which tells us the log level. The downside is that we don't have the status code,
    which isn't useful for status logging anyways.
    """
        request.ts = time.time()
        request.view_func = view_func
        access_log_level = getattr(view_func, 'access_log_level', None)

        # Skip loop for oidc
        if request.path in [
                '/oidc/authenticate/', '/oidc/callback/', '/oidc/logout/',
                '/hue/oidc_failed/'
        ]:
            return None

        if request.path.startswith(
                '/api/') or request.path == '/notebook/api/create_session':
            return None

        # Skip views not requiring login

        # If the view has "opted out" of login required, skip
        if hasattr(view_func, "login_notrequired"):
            log_page_hit(request,
                         view_func,
                         level=access_log_level or logging.DEBUG)
            return None

        # There are certain django views which are also opt-out, but
        # it would be evil to go add attributes to them
        if view_func in DJANGO_VIEW_AUTH_WHITELIST:
            log_page_hit(request,
                         view_func,
                         level=access_log_level or logging.DEBUG)
            return None

        # If user is logged in, check that he has permissions to access the app
        if request.user.is_active and request.user.is_authenticated:
            AppSpecificMiddleware.augment_request_with_app(request, view_func)

            # Until Django 1.3 which resolves returning the URL name, just do a match of the name of the view
            try:
                access_view = 'access_view:%s:%s' % (
                    request._desktop_app, resolve(request.path)[0].__name__)
            except Exception as e:
                access_log(request,
                           'error checking view perm: %s' % e,
                           level=access_log_level)
                access_view = ''

            app_accessed = request._desktop_app
            app_libs_whitelist = [
                "desktop", "home", "home2", "about", "hue", "editor",
                "notebook", "indexer", "404", "500", "403"
            ]
            if has_connectors():
                app_libs_whitelist.append('metadata')
                if DASHBOARD_ENABLED.get():
                    app_libs_whitelist.append('dashboard')
            # Accessing an app can access an underlying other app.
            # e.g. impala or spark uses code from beeswax and so accessing impala shows up as beeswax here.
            # Here we trust the URL to be the real app we need to check the perms.
            ui_app_accessed = get_app_name(request)
            if app_accessed != ui_app_accessed and ui_app_accessed not in (
                    'logs', 'accounts', 'login'):
                app_accessed = ui_app_accessed

            if app_accessed and \
                app_accessed not in app_libs_whitelist and \
                not (
                    is_admin(request.user) or
                    request.user.has_hue_permission(action="access", app=app_accessed) or
                    request.user.has_hue_permission(action=access_view, app=app_accessed)
                ) and \
                not (app_accessed == '__debug__' and DJANGO_DEBUG_MODE.get()):
                access_log(request,
                           'permission denied',
                           level=access_log_level)
                return PopupException(_(
                    "You do not have permission to access the %(app_name)s application."
                ) % {
                    'app_name': app_accessed.capitalize()
                },
                                      error_code=401).response(request)
            else:
                if not hasattr(request, 'view_func'):
                    log_page_hit(request, view_func, level=access_log_level)
                return None

        if AUTH.AUTO_LOGIN_ENABLED.get():
            # Auto-create the hue/hue user if not already present
            user = find_or_create_user(username='******', password='******')
            ensure_has_a_group(user)
            user = rewrite_user(user)

            user.is_active = True
            user.save()

            user = authenticate(request, username='******', password='******')
            if user is not None:
                login(request, user)
                return None

        logging.info("Redirecting to login page: %s", request.get_full_path())
        access_log(request, 'login redirection', level=access_log_level)
        no_idle_backends = ("libsaml.backend.SAML2Backend",
                            "desktop.auth.backend.SpnegoDjangoBackend",
                            "desktop.auth.backend.KnoxSpnegoDjangoBackend")
        if request.ajax and all(no_idle_backend not in AUTH.BACKEND.get()
                                for no_idle_backend in no_idle_backends):
            # Send back a magic header which causes Hue.Request to interpose itself
            # in the ajax request and make the user login before resubmitting the
            # request.
            response = HttpResponse("/* login required */",
                                    content_type="text/javascript")
            response[MIDDLEWARE_HEADER] = 'LOGIN_REQUIRED'
            return response
        else:
            if request.GET.get('is_embeddable'):
                return JsonResponse(
                    {
                        'url':
                        "%s?%s=%s" %
                        (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                         quote('/hue' + request.get_full_path().replace(
                             'is_embeddable=true', '').replace('&&', '&')))
                    }
                )  # Remove embeddable so redirect from & to login works. Login page is not embeddable
            else:
                return HttpResponseRedirect(
                    "%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                                  quote(request.get_full_path())))
Ejemplo n.º 5
0
    def authenticate(self, request):
        authorization_header = request.META.get('HTTP_AUTHORIZATION')

        if not authorization_header:
            LOG.debug('JwtAuthentication: no authorization header from %s' %
                      request.path)
            return None

        header, access_token = authorization_header.split(' ')

        if header != 'Bearer':
            LOG.debug('JwtAuthentication: no Bearer header from %s' %
                      request.path)
            return None

        if not access_token:
            LOG.debug('JwtAuthentication: no Bearer value from %s' %
                      request.path)
            return None

        LOG.debug('JwtAuthentication: got access token from %s: %s' %
                  (request.path, access_token))

        public_key_pem = ''
        if AUTH.JWT.VERIFY.get():
            public_key_pem = self._handle_public_key(access_token)

        params = {
            'jwt': access_token,
            'key': public_key_pem,
            'issuer': AUTH.JWT.ISSUER.get(),
            'audience': AUTH.JWT.AUDIENCE.get(),
            'algorithms': ["RS256"]
        }

        if sys.version_info[0] > 2:
            params['options'] = {'verify_signature': AUTH.JWT.VERIFY.get()}
        else:
            params['verify'] = AUTH.JWT.VERIFY.get()

        try:
            payload = jwt.decode(**params)

        except jwt.DecodeError:
            LOG.error('JwtAuthentication: Invalid token')
            raise exceptions.AuthenticationFailed(
                'JwtAuthentication: Invalid token')
        except jwt.ExpiredSignatureError:
            LOG.error('JwtAuthentication: Token expired')
            raise exceptions.AuthenticationFailed(
                'JwtAuthentication: Token expired')
        except jwt.InvalidIssuerError:
            LOG.error('JwtAuthentication: issuer not match')
            raise exceptions.AuthenticationFailed(
                'JwtAuthentication: issuer not matching')
        except jwt.InvalidAudienceError:
            LOG.error('JwtAuthentication: audience not match or no audience')
            raise exceptions.AuthenticationFailed(
                'JwtAuthentication: audience not matching or no audience')
        except Exception as e:
            LOG.error('JwtAuthentication: %s' % str(e))
            raise exceptions.AuthenticationFailed(e)

        if payload.get('user') is None:
            LOG.debug('JwtAuthentication: no user ID in token')
            return None

        LOG.debug('JwtAuthentication: got user ID %s and tenant ID %s' %
                  (payload.get('user'), payload.get('tenantId')))

        user = find_or_create_user(payload.get('user'), is_superuser=False)
        ensure_has_a_group(user)
        user = rewrite_user(user)

        # Persist the token (to reuse for communicating with external services as the user, e.g. Impala)
        if ENABLE_ORGANIZATIONS.get():
            user.token = access_token
        else:
            user.profile.update_data({'jwt_access_token': access_token})
            user.profile.save()

        return (user, None)