Пример #1
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

    # First, 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 we get Django 1.3 and resolve returning the URL name, we 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, e:
        access_log(request, 'error checking view perm: %s' % e, level=access_log_level)
        access_view = ''

      # 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.
      app_accessed = request._desktop_app
      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 ("desktop", "home", "home2", "about", "hue", "editor", "notebook", "indexer", "404", "500", "403") and \
          not (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 desktop.conf.DJANGO_DEBUG_MODE):
        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
Пример #2
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

    # First, 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 we get Django 1.3 and resolve returning the URL name, we 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, e:
        access_log(request, 'error checking view perm: %s' % e, level=access_log_level)
        access_view = ''

      # 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.
      app_accessed = request._desktop_app
      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 ("desktop", "home", "home2", "about", "hue", "editor", "notebook", "indexer", "404", "500", "403") 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 desktop.conf.DJANGO_DEBUG_MODE):
        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
Пример #3
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.
    """
        access_log_level = getattr(view_func, 'access_log_level', None)
        # First, 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 we get Django 1.3 and resolve returning the URL name, we 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, e:
                access_log(request,
                           'error checking view perm: %s',
                           e,
                           level=access_log_level)
                access_view = ''

            if request._desktop_app and \
                request._desktop_app != "desktop" and \
                not (request.user.has_hue_permission(action="access", app=request._desktop_app) or
                     request.user.has_hue_permission(action=access_view, app=request._desktop_app)):
                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':
                    request._desktop_app.capitalize()
                },
                                      error_code=401).response(request)
            else:
                log_page_hit(request, view_func, level=access_log_level)
                return None
Пример #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.
    """
        access_log_level = getattr(view_func, 'access_log_level', None)
        # First, 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)
            if request._desktop_app and \
                request._desktop_app != "desktop" and \
                not request.user.has_hue_permission(action="access", app=request._desktop_app):
                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': request._desktop_app.capitalize()
                      }).response(request)
            else:
                log_page_hit(request, view_func, level=access_log_level)
                return None

        logging.info("Redirecting to login page: %s", request.get_full_path())
        access_log(request, 'login redirection', level=access_log_level)
        if request.ajax:
            # 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:
            return HttpResponseRedirect(
                "%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                              urlquote(request.get_full_path())))
Пример #5
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.
    """
        access_log_level = getattr(view_func, "access_log_level", None)
        # First, 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 we get Django 1.3 and resolve returning the URL name, we 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, e:
                access_log(request, "error checking view perm: %s", e, level=access_log_level)
                access_view = ""

            # 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.
            app_accessed = request._desktop_app
            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 ("desktop", "home", "about")
                and not (
                    request.user.has_hue_permission(action="access", app=app_accessed)
                    or request.user.has_hue_permission(action=access_view, app=app_accessed)
                )
            ):
                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:
                log_page_hit(request, view_func, level=access_log_level)
                return None
Пример #6
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.
    """
        access_log_level = getattr(view_func, "access_log_level", None)
        # First, 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)
            if (
                request._desktop_app
                and request._desktop_app != "desktop"
                and not request.user.has_hue_permission(action="access", app=request._desktop_app)
            ):
                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": request._desktop_app.capitalize()}
                ).response(request)
            else:
                log_page_hit(request, view_func, level=access_log_level)
                return None

        logging.info("Redirecting to login page: %s", request.get_full_path())
        access_log(request, "login redirection", level=access_log_level)
        if request.ajax:
            # 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:
            return HttpResponseRedirect(
                "%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME, urlquote(request.get_full_path()))
            )
Пример #7
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.
    """
    access_log_level = getattr(view_func, 'access_log_level', None)
    # First, 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 we get Django 1.3 and resolve returning the URL name, we 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, e:
        access_log(request, 'error checking view perm: %s', e, level=access_log_level)
        access_view =''

      if request._desktop_app and \
          request._desktop_app != "desktop" and \
          not (request.user.has_hue_permission(action="access", app=request._desktop_app) or
               request.user.has_hue_permission(action=access_view, app=request._desktop_app)):
        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': request._desktop_app.capitalize()}, error_code=401).response(request)
      else:
        log_page_hit(request, view_func, level=access_log_level)
        return None
Пример #8
0
class LoginAndPermissionMiddleware(object):
    """
  Middleware that forces all views (except those that opt out) through authentication.
  """
    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.
    """
        access_log_level = getattr(view_func, 'access_log_level', None)
        # First, 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 we get Django 1.3 and resolve returning the URL name, we 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, e:
                access_log(request,
                           'error checking view perm: %s',
                           e,
                           level=access_log_level)
                access_view = ''

            # 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.
            app_accessed = request._desktop_app
            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 ("desktop", "home", "about") and \
                not (request.user.has_hue_permission(action="access", app=app_accessed) or
                     request.user.has_hue_permission(action=access_view, app=app_accessed)):
                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:
                log_page_hit(request, view_func, level=access_log_level)
                return None

        logging.info("Redirecting to login page: %s", request.get_full_path())
        access_log(request, 'login redirection', level=access_log_level)
        if request.ajax:
            # 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:
            return HttpResponseRedirect(
                "%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME,
                              urlquote(request.get_full_path())))
Пример #9
0
class LoginAndPermissionMiddleware(object):
  def process_request(self, request):
    # When local user login, oidc middleware refresh token if oidc_id_token_expiration doesn't exists!
    if request.session.get('_auth_user_backend', '') == 'desktop.auth.backend.AllowFirstUserDjangoBackend'\
            and 'desktop.auth.backend.OIDCBackend' in desktop.conf.AUTH.BACKEND.get():
      request.session['oidc_id_token_expiration'] = time.time() + 300

  """
  Middleware that forces all views (except those that opt out) through authentication.
  """
  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

    # First, 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 we get Django 1.3 and resolve returning the URL name, we 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, e:
        access_log(request, 'error checking view perm: %s' % e, level=access_log_level)
        access_view = ''

      # 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.
      app_accessed = request._desktop_app
      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 ("desktop", "home", "home2", "about", "hue", "editor", "notebook", "indexer", "404", "500", "403") and \
          not (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 desktop.conf.DJANGO_DEBUG_MODE):
        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

    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")
    if request.ajax and all(no_idle_backend not in desktop.conf.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 IS_EMBEDDED.get():
        return HttpResponseForbidden()
      else:
        return HttpResponseRedirect("%s?%s=%s" % (settings.LOGIN_URL, REDIRECT_FIELD_NAME, urlquote(request.get_full_path())))
Пример #10
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())))
Пример #11
0
def dt_login(request, from_modal=False):
    redirect_to = request.REQUEST.get('next', '/')
    is_first_login_ever = first_login_ever()
    backend_names = auth_forms.get_backend_names()
    is_active_directory = auth_forms.is_active_directory()
    is_ldap_option_selected = 'server' not in request.POST or request.POST['server'] == 'LDAP' \
                              or request.POST['server'] in auth_forms.get_ldap_server_keys()

    if is_active_directory and is_ldap_option_selected:
        UserCreationForm = auth_forms.LdapUserCreationForm
        AuthenticationForm = auth_forms.LdapAuthenticationForm
    else:
        UserCreationForm = auth_forms.UserCreationForm
        if 'ImpersonationBackend' in backend_names:
            AuthenticationForm = ImpersonationAuthenticationForm
        else:
            AuthenticationForm = auth_forms.AuthenticationForm

    if request.method == 'POST':
        request.audit = {
            'operation': 'USER_LOGIN',
            'username': request.POST.get('username')
        }

        # For first login, need to validate user info!
        first_user_form = is_first_login_ever and UserCreationForm(
            data=request.POST) or None
        first_user = first_user_form and first_user_form.is_valid()

        if first_user or not is_first_login_ever:
            auth_form = AuthenticationForm(data=request.POST)

            if auth_form.is_valid():
                # Must login by using the AuthenticationForm. It provides 'backends' on the User object.
                user = auth_form.get_user()
                userprofile = get_profile(user)

                login(request, user)

                if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()

                try:
                    ensure_home_directory(request.fs, user)
                except (IOError, WebHdfsException), e:
                    LOG.error(
                        'Could not create home directory at login for %s.' %
                        user,
                        exc_info=e)

                if require_change_password(userprofile):
                    return HttpResponseRedirect(
                        urlresolvers.reverse(
                            'useradmin.views.edit_user',
                            kwargs={'username': user.username}))

                userprofile.first_login = False
                userprofile.last_activity = datetime.now()
                userprofile.save()

                msg = 'Successful login for user: %s' % user.username
                request.audit['operationText'] = msg
                access_log(request, msg)
                if from_modal or request.REQUEST.get('fromModal',
                                                     'false') == 'true':
                    return JsonResponse({'auth': True})
                else:
                    return HttpResponseRedirect(redirect_to)
            else:
                request.audit['allowed'] = False
                msg = 'Failed login for user: %s' % request.POST.get(
                    'username')
                request.audit['operationText'] = msg
                access_warn(request, msg)
                if from_modal or request.REQUEST.get('fromModal',
                                                     'false') == 'true':
                    return JsonResponse({'auth': False})