예제 #1
0
 def wrapper2(self, *args, **kwargs):
     projectid = self.kwargs.get('projectid', None)
     if not projectid:
         raise exceptions.NotAuthorized("Missing Project ID")
     project = project_db_handle.GetProjectInstanceById(projectid)
     if not project:
         raise exceptions.NotAuthorized("Invalid Project ID")
     if not project.state in expected_states:
         raise exceptions.NotAuthorized("Illegal Project state")
     return func(self, *args, **kwargs)
예제 #2
0
 def wrapper2(self, *args, **kwargs):
     expertid = self.kwargs.get('expertid', None)
     if not expertid:
         raise exceptions.NotAuthorized("Missing Expert ID")
     expert = expert_db_handle.GetExpertInstanceById(expertid)
     if not expert:
         raise exceptions.NotAuthorized("Invalid Expert ID")
     if not expert.state in expected_states:
         raise exceptions.NotAuthorized("Illegal Expert state")
     return func(self, *args, **kwargs)
예제 #3
0
 def get_tables(self):
     if not self._tables:
         self._tables = {}
         policy_rules = getattr(self.table_class._meta, 'policy_rules',
                                set())
         if policy_rules:
             if not policy_check(policy_rules, self.request):
                 raise exceptions.NotAuthorized("Illegal Visiting")
         elif not has_permissions(self.request.user,
                                  self.table_class._meta):
             raise exceptions.NotAuthorized("Illegal Visiting")
         self._tables[self.table_class._meta.name] = self.get_table()
     return self._tables
def get_user_from_request(request):
    """ Checks the current session and returns a :class:`~horizon.users.User`.

    If the session contains user data the User will be treated as
    authenticated and the :class:`~horizon.users.User` will have all
    its attributes set.

    If not, the :class:`~horizon.users.User` will have no attributes set.

    If the session contains invalid data,
    :exc:`~horizon.exceptions.NotAuthorized` will be raised.
    """
    if 'user_id' not in request.session:
        return User()
    try:
        return User(id=request.session['user_id'],
                    token=request.session['token'],
                    user=request.session['user_name'],
                    tenant_id=request.session['tenant_id'],
                    tenant_name=request.session['tenant'],
                    service_catalog=request.session['serviceCatalog'],
                    roles=request.session['roles'],
                    request=request)
    except KeyError:
        # If any of those keys are missing from the session it is
        # overwhelmingly likely that we're dealing with an outdated session.
        LOG.exception("Error while creating User from session.")
        request.session.clear()
        raise exceptions.NotAuthorized(_("Your session has expired. "
                                         "Please log in again."))
예제 #5
0
def GetReviewerInstanceById(project,
                            expertid,
                            project_expected_states=['start_review'],
                            reviewer_expected_states=[REVIEWER_SELECTED]):
    _input = {'projectid': str(project.id), 'expertid': expertid}
    if not project.state in project_expected_states:
        raise exceptions.NotAuthorized(
            _('No authority to visit project with id %(projectid)s') % _input)
    reviewer_state_regex = '[%s]' % (''.join(reviewer_expected_states))
    reviewers = project.reviewer_set.filter(expert__id=expertid,
                                            state__regex=reviewer_state_regex)
    if not len(reviewers) == 1:
        raise exceptions.NotAuthorized(
            _('Expert %(expertid)s has no authority to visit project with id %(projectid)s'
              ) % _input)
    return reviewers[0]
예제 #6
0
 def get_form(self, form_class=None):
     """Returns an instance of the form to be used in this view."""
     if not self._can_access(self.request):
         raise exceptions.NotAuthorized("Illegal Visiting")
     if form_class is None:
         form_class = self.get_form_class()
     return form_class(self.request, **self.get_form_kwargs())
예제 #7
0
 def get_context_data(self, **kwargs):
     if not policy.check((('monitoring', 'monitoring:monitoring'), ), self.request):
         raise exceptions.NotAuthorized()
     context = super(AlarmDetailView, self).get_context_data(**kwargs)
     self.get_initial()
     context["alarm"] = self.alarm
     context["cancel_url"] = self.get_success_url()
     return context
예제 #8
0
    def test_redirect_login_fail_to_login(self):
        url = settings.LOGIN_URL
        request = self.factory.post(url)

        mw = middleware.HorizonMiddleware()
        resp = mw.process_exception(request, exceptions.NotAuthorized())
        resp.client = self.client

        self.assertRedirects(resp, url)
예제 #9
0
 def get_context_data(self, **kwargs):
     if not policy.check((('monitoring', 'monitoring:monitoring'), ), self.request):
         raise exceptions.NotAuthorized()
     context = super(AlarmEditView, self).get_context_data(**kwargs)
     id = self.kwargs['id']
     context["cancel_url"] = self.get_success_url()
     context["action_url"] = reverse(constants.URL_PREFIX + 'alarm_edit',
                                     args=(id,))
     return context
예제 #10
0
 def wrapper(project, *args, **kwargs):
     if not isinstance(project, Project):
         if isinstance(project, (int, str, unicode)):
             projectid = project
             project = GetProjectInstanceById(projectid, returnDict=False)
     if not project or not isinstance(project, Project):
         raise exceptions.NotAuthorized(
             _('No authority to visit project with id %s') % str(project))
     return func(project, *args, **kwargs)
예제 #11
0
파일: views.py 프로젝트: zreigz/monasca-ui
 def get_context_data(self, **kwargs):
     if not policy.check(
         (('monitoring', 'monitoring:monitoring'), ), self.request):
         raise exceptions.NotAuthorized()
     context = super(NotificationCreateView, self). \
         get_context_data(**kwargs)
     context["cancel_url"] = self.get_success_url()
     action = constants.URL_PREFIX + 'notification_create'
     context["action_url"] = reverse(action)
     return context
예제 #12
0
 def get_workflow(self):
     """Returns the instantiated workflow class."""
     if not self._can_access(self.request):
         raise exceptions.NotAuthorized("Illegal Visiting")
     extra_context = self.get_initial()
     entry_point = self.request.GET.get("step", None)
     workflow = self.workflow_class(self.request,
                                    context_seed=extra_context,
                                    entry_point=entry_point)
     return workflow
예제 #13
0
def AllReviewSubmitted(project):
    _input = {'projectid': str(project.id)}
    if not project.state in ['start_review']:
        raise exceptions.NotAuthorized(
            _('No authority to visit project with id %(projectid)s') % _input)
    reviewers = project.reviewer_set.filter(state__exact=REVIEWER_SELECTED)
    for r in reviewers:
        if not r.review_state == REVIEW_STATE_COMMITTED:
            return False
    return True
예제 #14
0
파일: views.py 프로젝트: zreigz/monasca-ui
    def get_context_data(self, **kwargs):
        if not policy.check(
            (('monitoring', 'monitoring:monitoring'), ), self.request):
            raise exceptions.NotAuthorized()
        context = super(IndexView, self).get_context_data(**kwargs)
        num_results = 0
        contacts = []
        prev_page_stack = []
        page_offset = self.request.GET.get('page_offset')

        if 'prev_page_stack' in self.request.session:
            prev_page_stack = self.request.session['prev_page_stack']

        if page_offset is None:
            page_offset = 0
            prev_page_stack = []
        else:
            page_offset = int(page_offset)

        limit = utils.get_page_size(self.request)
        try:
            # To judge whether there is next page, get limit + 1
            results = api.monitor.alarmdef_list(self.request, page_offset,
                                                limit + 1)
            num_results = len(results)
            paginator = Paginator(results, limit)
            contacts = paginator.page(1)
        except EmptyPage:
            contacts = paginator.page(paginator.num_pages)
        except Exception:
            messages.error(self.request,
                           _("Could not retrieve alarm definitions"))
            return context

        context["contacts"] = contacts

        if num_results < limit + 1:
            context["page_offset"] = None
        else:
            context["page_offset"] = page_offset + limit

        if page_offset in prev_page_stack:
            index = prev_page_stack.index(page_offset)
            prev_page_stack = prev_page_stack[0:index]

        prev_page_offset = prev_page_stack[-1] if prev_page_stack else None
        if prev_page_offset is not None:
            context["prev_page_offset"] = prev_page_offset

        if len(prev_page_stack) > PREV_PAGE_LIMIT:
            del prev_page_stack[0]
        prev_page_stack.append(page_offset)
        self.request.session['prev_page_stack'] = prev_page_stack

        return context
예제 #15
0
 def get_context_data(self, **kwargs):
     if not policy.check(
         (('monitoring', 'monitoring:monitoring'), ), self.request):
         raise exceptions.NotAuthorized()
     context = super(AlarmFilterView, self).get_context_data(**kwargs)
     context["cancel_url"] = self.get_success_url()
     context["action_url"] = reverse(constants.URL_PREFIX + 'alarm_filter',
                                     args=())
     context["alarm_url"] = reverse_lazy(constants.URL_PREFIX + 'alarm_all',
                                         args=())
     return context
예제 #16
0
 def get_tables(self):
     if not self.table_classes:
         raise AttributeError('You must specify one or more DataTable '
                              'classes for the "table_classes" attribute '
                              'on %s.' % self.__class__.__name__)
     if not self._tables:
         for table in self.table_classes:
             policy_rules = getattr(table._meta, 'policy_rules', set())
             if policy_rules:
                 if not policy_check(policy_rules, self.request):
                     raise exceptions.NotAuthorized("Illegal Visiting")
             elif not has_permissions(self.request.user, table._meta):
                 raise exceptions.NotAuthorized("Illegal Visiting")
             func_name = "get_%s_table" % table._meta.name
             table_func = getattr(self, func_name, None)
             if table_func is None:
                 tbl = table(self.request, **self.kwargs)
             else:
                 tbl = table_func(self, self.request, **self.kwargs)
             self._tables[table._meta.name] = tbl
     return self._tables
예제 #17
0
    def test_redirect_login_fail_to_login(self):
        url = settings.LOGIN_URL
        request = self.factory.post(url)

        mw = middleware.HorizonMiddleware()
        resp = mw.process_exception(request, exceptions.NotAuthorized())
        resp.client = self.client

        if django.VERSION >= (1, 9):
            self.assertRedirects(resp, settings.TESTSERVER + url)
        else:
            self.assertRedirects(resp, url)
예제 #18
0
    def __init__(self, id=None, **kwargs):
        if id is None:
            self.id = getattr(settings, 'ADMIN_TOKEN')
        else:
            self.id = id 

        if not self.id:
            raise exceptions.NotAuthorized("Token not authorized")

        class Token:
            def __init__(self, id):
                self.id = id

        super(User, self).__init__(id=self.id, token=Token(self.id), **kwargs)
예제 #19
0
 def get_context_data(self, **kwargs):
     if not policy.check(
         (('monitoring', 'monitoring:monitoring'), ), self.request):
         raise exceptions.NotAuthorized()
     context = super(IndexView, self).get_context_data(**kwargs)
     try:
         region = self.request.user.services_region
         context["grafana_url"] = getattr(settings,
                                          'GRAFANA_URL').get(region, '')
     except AttributeError:
         # Catches case where Grafana 2 is not enabled.
         proxy_url_path = str(reverse_lazy(constants.URL_PREFIX + 'proxy'))
         api_root = self.request.build_absolute_uri(proxy_url_path)
         context["api"] = api_root
     context["dashboards"] = get_dashboard_links(self.request)
     # Ensure all links have a 'raw' attribute
     for link in context["dashboards"]:
         link['raw'] = link.get('raw', False)
     context['can_access_logs'] = policy.check(
         ((getattr(settings, 'KIBANA_POLICY_SCOPE'),
           getattr(settings, 'KIBANA_POLICY_RULE')), ), self.request)
     context['enable_kibana_button'] = settings.ENABLE_KIBANA_BUTTON
     context['show_grafana_home'] = settings.SHOW_GRAFANA_HOME
     return context
예제 #20
0
    def get_context_data(self, **kwargs):
        if not policy.check(
            (('monitoring', 'monitoring:monitoring'), ), self.request):
            raise exceptions.NotAuthorized()
        context = super(AlarmHistoryView, self).get_context_data(**kwargs)

        object_id = kwargs['id']
        ts_mode = self.request.GET.get('ts_mode')
        ts_offset = self.request.GET.get('ts_offset')

        try:
            alarm = api.monitor.alarm_get(self.request, object_id)
        except Exception:
            messages.error(self.request,
                           _("Could not retrieve alarm for %s") % object_id)
        context['alarm'] = alarm

        num_results = 0
        contacts = []
        prev_page_stack = []
        page_offset = self.request.GET.get('page_offset')
        limit = utils.get_page_size(self.request)
        if 'prev_page_stack' in self.request.session:
            prev_page_stack = self.request.session['prev_page_stack']

        if page_offset is None:
            page_offset = 0
            prev_page_stack = []
        try:
            # To judge whether there is next page, get limit + 1
            results = api.monitor.alarm_history(self.request, object_id,
                                                page_offset, limit + 1)
            num_results = len(results)
            paginator = Paginator(results, limit)
            contacts = paginator.page(1)
        except EmptyPage:
            contacts = paginator.page(paginator.num_pages)
        except Exception:
            messages.error(
                self.request,
                _("Could not retrieve alarm history for %s") % object_id)
            return context

        context["contacts"] = contacts
        context['timestamp_formats'] = alarm_history_ts_formats
        context['timestamp_selected'] = ts_mode or ''
        context['timestamp_offset'] = ts_offset or 0

        if num_results < limit + 1:
            context["page_offset"] = None
        else:
            context["page_offset"] = contacts.object_list[-1]["id"]

        if page_offset in prev_page_stack:
            index = prev_page_stack.index(page_offset)
            prev_page_stack = prev_page_stack[0:index]

        prev_page_offset = prev_page_stack[-1] if prev_page_stack else None
        if prev_page_offset is not None:
            context["prev_page_offset"] = prev_page_offset

        if len(prev_page_stack) > PREV_PAGE_LIMIT:
            del prev_page_stack[0]
        prev_page_stack.append(str(page_offset))
        self.request.session['prev_page_stack'] = prev_page_stack

        return context
예제 #21
0
    def get_context_data(self, **kwargs):
        if not policy.check(
            (('monitoring', 'monitoring:monitoring'), ), self.request):
            raise exceptions.NotAuthorized()
        context = super(AlarmServiceView, self).get_context_data(**kwargs)
        results = []
        num_results = 0  # make sure variable is set
        prev_page_stack = []
        page_offset = self.request.GET.get('page_offset')

        if 'prev_page_stack' in self.request.session:
            prev_page_stack = self.request.session['prev_page_stack']

        if page_offset is None:
            page_offset = 0
            prev_page_stack = []
        else:
            page_offset = int(page_offset)
        limit = utils.get_page_size(self.request)
        if self.service == 'all':
            try:
                # To judge whether there is next page, get limit + 1
                results = api.monitor.alarm_list(self.request, page_offset,
                                                 limit + 1)
                num_results = len(results)
                paginator = Paginator(results, limit)
                results = paginator.page(1)
            except EmptyPage:
                results = paginator.page(paginator.num_pages)
            except Exception:
                messages.error(self.request, _("Could not retrieve alarms"))
        else:
            if self.service[:2] == 'id':
                try:
                    name, value = self.service.split("=")
                    results = [api.monitor.alarm_show(self.request, value)]
                except Exception:
                    messages.error(self.request,
                                   _("Could not retrieve alarms"))
                    results = []
            else:
                try:
                    # To judge whether there is next page, get limit + 1
                    results = api.monitor.alarm_list_by_dimension(
                        self.request, self.service, page_offset, limit + 1)
                    num_results = len(results)
                    paginator = Paginator(results, limit)
                    results = paginator.page(1)
                except EmptyPage:
                    results = paginator.page(paginator.num_pages)
                except Exception:
                    messages.error(self.request,
                                   _("Could not retrieve alarms"))
                    results = []

        context["contacts"] = results
        context["service"] = self.service

        if num_results < limit + 1:
            context["page_offset"] = None
        else:
            context["page_offset"] = page_offset + limit

        if page_offset in prev_page_stack:
            index = prev_page_stack.index(page_offset)
            prev_page_stack = prev_page_stack[0:index]

        prev_page_offset = prev_page_stack[-1] if prev_page_stack else None
        if prev_page_offset is not None:
            context["prev_page_offset"] = prev_page_offset

        if len(prev_page_stack) > PREV_PAGE_LIMIT:
            del prev_page_stack[0]
        prev_page_stack.append(page_offset)
        self.request.session['prev_page_stack'] = prev_page_stack

        return context
예제 #22
0
 def _check_state(self, expertid):
     expert = expert_db_handle.GetExpertInstanceById(expertid)
     if expert.state != 'draft':
         raise exceptions.NotAuthorized("Illegal Visiting")
     return True
예제 #23
0
    def handle(self, request, data):
        if 'user_name' in request.session:
            if request.session['user_name'] != data['username']:
                # To avoid reusing another user's session, create a
                # new, empty session if the existing session
                # corresponds to a different authenticated user.
                request.session.flush()
        # Always cycle the session key when viewing the login form to
        # prevent session fixation
        request.session.cycle_key()

        # For now we'll allow fallback to OPENSTACK_KEYSTONE_URL if the
        # form post doesn't include a region.
        # jt
        default_region = (settings.OPENSTACK_KEYSTONE_URL, "Default Region")
        regions = getattr(settings, 'AVAILABLE_REGIONS', [default_region])
        #endpoint = data.get('region', None) or settings.OPENSTACK_KEYSTONE_URL
        #region_name = dict(self.fields['region'].choices)[endpoint]
        region_name = data.get('region', None) or "Default Region"
        endpoint = [r[0] for r in regions if r[1] == region_name][0]
        request.session['region_endpoint'] = endpoint
        request.session['region_name'] = region_name

        redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, None)
        # Make sure the requested redirect matches the protocol,
        # domain, and port of this request
        if redirect_to and not same_origin(
                request.build_absolute_uri(redirect_to),
                request.build_absolute_uri()):
            redirect_to = None

        if data.get('tenant', None):
            try:
                token = api.token_create(request, data.get('tenant'),
                                         data['username'], data['password'])
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                msg = _('Unable to authenticate for that project.')
                exceptions.handle(request, message=msg, escalate=True)
            _set_session_data(request, token)
            user = users.get_user_from_request(request)
            redirect = redirect_to or base.Horizon.get_user_home(user)
            return shortcuts.redirect(redirect)

        elif data.get('username', None):
            try:
                unscoped_token = api.token_create(request, '',
                                                  data['username'],
                                                  data['password'])
            except keystone_exceptions.Unauthorized:
                exceptions.handle(request, _('Invalid user name or password.'))
            except:
                # If we get here we don't want to show a stack trace to the
                # user. However, if we fail here, there may be bad session
                # data that's been cached already.
                request.user_logout()
                exceptions.handle(request,
                                  message=_("An error occurred authenticating."
                                            " Please try again later."),
                                  escalate=True)

            # Unscoped token
            request.session['unscoped_token'] = unscoped_token.id
            request.user.username = data['username']

            # Get the tenant list, and log in using first tenant
            # FIXME (anthony): add tenant chooser here?
            try:
                tenants = api.tenant_list_for_token(request, unscoped_token.id)
            except:
                exceptions.handle(request)
                tenants = []

            # Abort if there are no valid tenants for this user
            if not tenants:
                messages.error(request,
                               _('You are not authorized for any projects.') %
                               {"user": data['username']},
                               extra_tags="login")
                return

            # Create a token.
            # NOTE(gabriel): Keystone can return tenants that you're
            # authorized to administer but not to log into as a user, so in
            # the case of an Unauthorized error we should iterate through
            # the tenants until one succeeds or we've failed them all.
            while tenants:
                tenant = tenants.pop()
                try:
                    token = api.token_create_scoped(request, tenant.id,
                                                    unscoped_token.id)
                    break
                except:
                    # This will continue for recognized Unauthorized
                    # exceptions from keystoneclient.
                    exceptions.handle(request, ignore=True)
                    token = None
            if token is None:
                raise exceptions.NotAuthorized(
                    _("You are not authorized for any available projects."))

            _set_session_data(request, token)
            user = users.get_user_from_request(request)
        redirect = redirect_to or base.Horizon.get_user_home(user)
        return shortcuts.redirect(redirect)
예제 #24
0
    def handle(self, request, data):
        region = data.get('region', '').split(',')
        if len(region) > 1:
            request.session['region_endpoint'] = region[0]
            request.session['region_name'] = region[1]

        if data.get('tenant', None):
            try:
                token = api.token_create(request, data.get('tenant'),
                                         data['username'], data['password'])
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                exceptions.handle(request,
                                  message=_('Unable to authenticate tenant.'),
                                  escalate=True)
            tenant = None
            for t in tenants:
                if t.id == data.get('tenant'):
                    tenant = t
            _set_session_data(request, token)
            user = users.get_user_from_request(request)
            return shortcuts.redirect(base.Horizon.get_user_home(user))

        elif data.get('username', None):
            try:
                token = api.token_create(request, '', data['username'],
                                         data['password'])
            except keystone_exceptions.Unauthorized:
                exceptions.handle(request, _('Invalid user name or password.'))
            except:
                exceptions.handle(request, escalate=True)

            # Unscoped token
            request.session['unscoped_token'] = token.id
            request.user.username = data['username']

            # Get the tenant list, and log in using first tenant
            # FIXME (anthony): add tenant chooser here?
            try:
                tenants = api.tenant_list_for_token(request, token.id)
            except:
                exceptions.handle(request)
                tenants = []

            # Abort if there are no valid tenants for this user
            if not tenants:
                messages.error(request,
                               _('No tenants present for user: %(user)s') %
                               {"user": data['username']},
                               extra_tags="login")
                return

            # Create a token.
            # NOTE(gabriel): Keystone can return tenants that you're
            # authorized to administer but not to log into as a user, so in
            # the case of an Unauthorized error we should iterate through
            # the tenants until one succeeds or we've failed them all.
            while tenants:
                tenant = tenants.pop()
                try:
                    token = api.token_create_scoped(request, tenant.id,
                                                    token.id)
                    break
                except:
                    # This will continue for recognized "unauthorized"
                    # exceptions from keystoneclient.
                    exceptions.handle(request, ignore=True)
                    token = None
            if token is None:
                raise exceptions.NotAuthorized(
                    _("You are not authorized for any available tenants."))

            _set_session_data(request, token)
            user = users.get_user_from_request(request)
        return shortcuts.redirect(base.Horizon.get_user_home(user))
예제 #25
0
    def handle(self, request, data):
        try:
            if data.get('tenant', None):
                token = api.token_create(request,
                                         data.get('tenant'),
                                         data['username'],
                                         data['password'])

                tenants = api.tenant_list_for_token(request, token.id)
                tenant = None
                for t in tenants:
                    if t.id == data.get('tenant'):
                        tenant = t
                _set_session_data(request, token)
                user = users.get_user_from_request(request)
                return shortcuts.redirect(base.Horizon.get_user_home(user))

            elif data.get('username', None):
                try:
                    token = api.token_create(request,
                                             '',
                                             data['username'],
                                             data['password'])
                except keystone_exceptions.Unauthorized:
                    messages.error(request, _('Bad user name or password.'),
                            extra_tags="login")
                    return

                # Unscoped token
                request.session['unscoped_token'] = token.id
                request.user.username = data['username']

                # Get the tenant list, and log in using first tenant
                # FIXME (anthony): add tenant chooser here?
                tenants = api.tenant_list_for_token(request, token.id)

                # Abort if there are no valid tenants for this user
                if not tenants:
                    messages.error(request,
                                   _('No tenants present for user: %(user)s') %
                                    {"user": data['username']},
                                   extra_tags="login")
                    return

                # Create a token.
                # NOTE(gabriel): Keystone can return tenants that you're
                # authorized to administer but not to log into as a user, so in
                # the case of an Unauthorized error we should iterate through
                # the tenants until one succeeds or we've failed them all.
                while tenants:
                    tenant = tenants.pop()
                    try:
                        token = api.token_create_scoped(request,
                                                        tenant.id,
                                                        token.id)
                        break
                    except api_exceptions.Unauthorized as e:
                        token = None
                if token is None:
                    raise exceptions.NotAuthorized(
                        _("You are not authorized for any available tenants."))

                _set_session_data(request, token)
                user = users.get_user_from_request(request)
                return shortcuts.redirect(base.Horizon.get_user_home(user))

        except api_exceptions.Unauthorized as e:
            msg = _('Error authenticating: %s') % e.message
            LOG.exception(msg)
            messages.error(request, msg, extra_tags="login")
        except api_exceptions.ApiException as e:
            messages.error(request,
                           _('Error authenticating with keystone: %s') %
                           e.message, extra_tags="login")