예제 #1
0
@pytest.mark.parametrize(
    ("path", "expected"),
    [("/foo/bar/", True), ("/static/wat/", False),
     ("/_debug_toolbar/thing/", False)],
)
def test_activate_hook(path, expected):
    request = pretend.stub(path=path)
    assert config.activate_hook(request) == expected


@pytest.mark.parametrize(
    ("exc_info", "expected"),
    [
        (None, False),
        ((ValueError, ValueError(), None), True),
        ((HTTPForbidden, HTTPForbidden(), None), True),
        ((HTTPUnauthorized, HTTPUnauthorized(), None), True),
        ((BasicAuthBreachedPassword, BasicAuthBreachedPassword(), None),
         False),
        ((BasicAuthFailedPassword, BasicAuthFailedPassword(), None), False),
    ],
)
def test_commit_veto(exc_info, expected):
    request = pretend.stub(exc_info=exc_info)
    response = pretend.stub()

    assert bool(config.commit_veto(request, response)) == expected


@pytest.mark.parametrize("route_kw", [None, {}, {"foo": "bar"}])
def test_template_view(route_kw):
예제 #2
0
 def _makeOne(self, *arg, **kw):
     from pyramid.httpexceptions import HTTPForbidden
     return HTTPForbidden(*arg, **kw)
예제 #3
0
파일: api.py 프로젝트: pepastach/pypicloud
def change_password(request, old_password, new_password):
    """ Change a user's password """
    if not request.access.verify_user(request.userid, old_password):
        return HTTPForbidden()
    request.access.edit_user_password(request.userid, new_password)
    return request.response
예제 #4
0
def get_entity_events(request):
    """Returns entity "events" like TimeLogs, Vacations and Tasks which are
    events to be drawn in Calendars
    """
    logger.debug('get_entity_events is running')

    from stalker_pyramid.views import multi_permission_checker
    if not multi_permission_checker(
            request, ['Read_User', 'Read_TimeLog', 'Read_Vacation']):
        from pyramid.httpexceptions import HTTPForbidden
        return HTTPForbidden(headers=request)

    from stalker_pyramid.views import EntityViewBase
    keys = EntityViewBase.get_multi_string(request, 'keys')
    entity_id = request.matchdict.get('id', -1)

    logger.debug('keys: %s' % keys)
    logger.debug('entity_id : %s' % entity_id)

    sql_query = ""
    if 'time_log' in keys:
        sql_query = """
        select
            "TimeLogs".id,
            'timelogs' as entity_type, -- entity_type
            "Task_SimpleEntities".name || ' (' || parent_names.path_names || ')' as title,
            (extract(epoch from "TimeLogs".start::timestamp AT TIME ZONE 'UTC') * 1000)::bigint as start,
            (extract(epoch from "TimeLogs".end::timestamp AT TIME ZONE 'UTC') * 1000)::bigint as end,
            'label-success' as "className",
            false as "allDay",
            "Status_SimpleEntities".name as status
        from "TimeLogs"
        join "Tasks" on "TimeLogs".task_id = "Tasks".id
        join "SimpleEntities" as "Task_SimpleEntities" on "Tasks".id = "Task_SimpleEntities".id
        join "SimpleEntities" as "Status_SimpleEntities" on "Tasks".status_id = "Status_SimpleEntities".id

        join (
            with recursive recursive_task(id, parent_id, path, path_names) as (
                select
                    task.id,
                    task.project_id,
                    array[task.project_id] as path,
                    ("Projects".code || '') as path_names
                from "Tasks" as task
                join "Projects" on task.project_id = "Projects".id
                where task.parent_id is NULL
            union all
                select
                    task.id,
                    task.parent_id,
                    (parent.path || task.parent_id) as path,
                    (parent.path_names || '|' || "Parent_SimpleEntities".name) as path_names
                from "Tasks" as task
                join recursive_task as parent on task.parent_id = parent.id
                join "SimpleEntities" as "Parent_SimpleEntities" on parent.id = "Parent_SimpleEntities".id
                --where parent.id = t_path.parent_id
            ) select
                recursive_task.id,
                recursive_task.path,
                recursive_task.path_names
            from recursive_task
            order by path
        ) as parent_names on "TimeLogs".task_id = parent_names.id

        where "TimeLogs".resource_id = %(id)s
        """ % {
            'id': entity_id
        }

    if 'vacation' in keys:
        vacation_sql_query = """
        select
            "Vacations".id,
            'vacations' as entity_type,
            "Type_SimpleEntities".name as title,
            (extract(epoch from "Vacations".start::timestamp at time zone 'UTC') * 1000)::bigint as start,
            (extract(epoch from "Vacations".end::timestamp at time zone 'UTC') * 1000)::bigint as end,
            'label-yellow' as "className",
            true as "allDay",
            NULL as status
        from "Vacations"
        join "SimpleEntities" on "Vacations".id = "SimpleEntities".id
        join "Types" on "SimpleEntities".type_id = "Types".id
        join "SimpleEntities" as "Type_SimpleEntities" on "Types".id = "Type_SimpleEntities".id
        where "Vacations".entity_id is NULL or "Vacations".entity_id = %(id)s
        """ % {
            'id': entity_id
        }

        if sql_query != '':
            sql_query = '(%s) union (%s)' % (sql_query, vacation_sql_query)
        else:
            sql_query = vacation_sql_query

    if 'task' in keys:
        task_sql_query = """
        select
            "Tasks".id,
            'tasks' as entity_type,
            "Task_SimpleEntities".name || ' (' || parent_names.path_names || ')' as title,
            (extract(epoch from "Tasks".computed_start::timestamp at time zone 'UTC') * 1000)::bigint as start,
            (extract(epoch from "Tasks".computed_end::timestamp at time zone 'UTC') * 1000)::bigint as end,
            'label' as "className",
            false as "allDay",
            "Status_SimpleEntities".name as status
        from "Tasks"
        join "SimpleEntities" as "Task_SimpleEntities" on "Tasks".id = "Task_SimpleEntities".id
        join "SimpleEntities" as "Status_SimpleEntities" on "Tasks".status_id = "Status_SimpleEntities".id

        join (
            with recursive recursive_task(id, parent_id, path, path_names) as (
                select
                    task.id,
                    task.project_id,
                    array[task.project_id] as path,
                    ("Projects".code || '') as path_names
                from "Tasks" as task
                join "Projects" on task.project_id = "Projects".id
                where task.parent_id is NULL
            union all
                select
                    task.id,
                    task.parent_id,
                    (parent.path || task.parent_id) as path,
                    (parent.path_names || '|' || "Parent_SimpleEntities".name) as path_names
                from "Tasks" as task
                join recursive_task as parent on task.parent_id = parent.id
                join "SimpleEntities" as "Parent_SimpleEntities" on parent.id = "Parent_SimpleEntities".id
                --where parent.id = t_path.parent_id
            ) select
                recursive_task.id,
                recursive_task.path,
                recursive_task.path_names
            from recursive_task
            order by path
        ) as parent_names on "Tasks".id = parent_names.id

        join "Task_Resources" on "Tasks".id = "Task_Resources".task_id

        where "Task_Resources".resource_id = %(id)s and "Tasks".computed_end > current_date::date at time zone 'UTC'
        """ % {
            'id': entity_id
        }

        if sql_query != '':
            sql_query = '(%s) union (%s)' % (sql_query, task_sql_query)
        else:
            sql_query = task_sql_query

    from stalker.db.session import DBSession
    result = DBSession.connection().execute(sql_query)
    return [{
        'id': r[0],
        'entity_type': r[1],
        'title': r[2],
        'start': r[3],
        'end': r[4],
        'className': r[5],
        'allDay': r[6],
        'status': r[7]
    } for r in result.fetchall()]
예제 #5
0
    def update(self):
        request = self.request
        context = self.context
        login_url = request.resource_url(request.context, 'login')
        login_url2 = request.resource_url(request.context, '@@login')
        referrer = self.params('came_from')
        if not referrer:
            referrer = request.path_url

        if '/auditstream-sse' in referrer:
            # If we're being invoked as the result of a failed request to the
            # auditstream sse view, bail.  Otherwise the came_from will be set to
            # the auditstream URL, and the user who this happens to will eventually
            # be redirected to it and they'll be left scratching their head when
            # they see e.g. "id: 0-10\ndata: " when they log in successfully.
            return HTTPForbidden()

        if login_url in referrer or login_url2 in referrer:
            # never use the login form itself as came_from
            referrer = request.resource_url(request.virtual_root)

        came_from = request.session.setdefault('novaideo.came_from', referrer)
        login = ''
        password = ''
        message = None
        messages = {}
        if 'form.submitted' in request.params:

            try:
                check_csrf_token(request)
            except:
                request.sdiapi.flash(_('Failed login (CSRF)'), 'danger')
            else:
                self.execute(None)
                login = request.params['email'].strip()
                password = request.params['password']
                novaideo_catalog = find_catalog('novaideo')
                dace_catalog = find_catalog('dace')
                identifier_index = novaideo_catalog['identifier']
                object_provides_index = dace_catalog['object_provides']
                query = object_provides_index.any([IPerson.__identifier__]) &\
                        identifier_index.any([login])
                users = list(query.execute().all())
                user = users[0] if users else None
                valid_check = user and user.check_password(password)
                if valid_check and \
                   (has_role(user=user, role=('SiteAdmin', )) or \
                   'active' in getattr(user, 'state', [])):
                    request.session.pop('novaideo.came_from', None)
                    headers = remember(request, get_oid(user))
                    request.registry.notify(LoggedIn(login, user,
                                               context, request))
                    user.last_connection = datetime.datetime.now(tz=pytz.UTC)
                    if hasattr(user, 'reindex'):
                        user.reindex()

                    return HTTPFound(location=came_from, headers=headers)
                elif valid_check and 'deactivated' in getattr(user, 'state', []):
                    error = ViewError()
                    error.principalmessage = _("Disabled account! Contact the site administrator to activate your account.")
                    message = error.render_message(request)
                    messages.update({error.type: [message]})
                else:
                    error = ViewError()
                    error.principalmessage = _("Failed login")
                    message = error.render_message(request)
                    messages.update({error.type: [message]})

        # Pass this through FBO views (e.g., forbidden) which use its macros.
        template = get_renderer('novaideo:views/user_management/templates/login.pt').implementation()
        login_bodies = []
        try:
            login_navbars = generate_navbars(
                request, request.root,
                process_id=CONNECTOR_PROCESSES,
                node_id='login',
                descriminators=['body-action'])
            login_bodies = login_navbars['body_actions']
        except Exception as e:
            log.warning(e)

        values = dict(
            url=request.resource_url(request.virtual_root, 'login'),
            came_from=came_from,
            login=login,
            password=password,
            login_template=template,
            logins=login_bodies
            )
        body = self.content(args=values, template=self.template)['body']
        item = self.adapt_item(body, self.viewid)
        item['messages'] = messages
        result = {}
        result['coordinates'] = {self.coordinates: [item]}
        return result
예제 #6
0
def post_upload(context, request):
    properties = context.upgrade_properties()
    if properties['status'] not in ('uploading', 'upload failed'):
        raise HTTPForbidden(
            'status must be "uploading" to issue new credentials')

    accession_or_external = properties.get(
        'accession') or properties['external_accession']
    external = context.propsheets.get('external', None)
    if external is None:
        # Handle objects initially posted as another state.
        bucket = request.registry.settings['file_upload_bucket']
        uuid = context.uuid
        mapping = context.schema['file_format_file_extension']
        file_extension = mapping[properties['file_format']]
        date = properties['date_created'].split('T')[0].replace('-', '/')
        key = '{date}/{uuid}/{accession_or_external}{file_extension}'.format(
            accession_or_external=accession_or_external,
            date=date,
            file_extension=file_extension,
            uuid=uuid,
            **properties)
    elif external.get('service') == 's3':
        bucket = external['bucket']
        key = external['key']
    else:
        raise HTTPNotFound(detail='External service {} not expected'.format(
            external.get('service')))

    name = 'up{time:.6f}-{accession_or_external}'.format(
        accession_or_external=accession_or_external,
        time=time.time(),
        **properties)[:32]  # max 32 chars
    profile_name = request.registry.settings.get('file_upload_profile_name')
    upload_creds = UploadCredentials(bucket,
                                     key,
                                     name,
                                     profile_name=profile_name)
    s3_transfer_allow = request.registry.settings.get(
        'external_aws_s3_transfer_allow', 'false')
    creds = upload_creds.external_creds(
        s3_transfer_allow=asbool(s3_transfer_allow),
        s3_transfer_buckets=request.registry.settings.get(
            'external_aws_s3_transfer_buckets'),
    )
    new_properties = None
    if properties['status'] == 'upload failed':
        new_properties = properties.copy()
        new_properties['status'] = 'uploading'

    registry = request.registry
    registry.notify(BeforeModified(context, request))
    context.update(new_properties, {'external': creds})
    registry.notify(AfterModified(context, request))

    rendered = request.embed('/%s/@@object' % context.uuid, as_user=True)
    result = {
        'status': 'success',
        '@type': ['result'],
        '@graph': [rendered],
    }
    return result
예제 #7
0
def callback(request):
    code = request.params.get('code', '')
    try:
        credentials = flow.step2_exchange(code)
    except FlowExchangeError:
        raise HTTPForbidden
    data = requests.get(USER_INFO_URI % credentials.access_token, verify=False)
    google_profile = data.json()
    email = google_profile['email']

    EXTRA_EMAILS = request.registry.settings.get('GOOGLE_EXTRA_EMAILS', '')
    EXTRA_EMAILS = EXTRA_EMAILS.split('\n')
    config = ApplicationConfig.get_current_config(allow_empty=True)
    freelancers = config.get_freelancers()
    clients_emails = Client.get_emails()

    is_employee = (email.endswith(
        '@%s' % request.registry.settings['COMPANY_DOMAIN'])
                   or email in EXTRA_EMAILS)

    if is_employee:
        group = 'employee'
    elif email in freelancers:
        group = 'freelancer'
    elif email in clients_emails:
        group = 'client'
    else:
        WARN_LOG(
            u"Forbidden acccess for profile:\n%s\n client's emails:\n%s\nfreelancer's emails:\n%s"
            % (google_profile, clients_emails, freelancers))
        return HTTPForbidden()

    user = DBSession.query(User).filter(User.email == email).first()
    if user is not None:
        if credentials.refresh_token:
            DEBUG(u'Adding refresh token %s for user %s' % (
                credentials.refresh_token,
                user.name,
            ))
            user.refresh_token = credentials.refresh_token
            DBSession.add(user)
        DEBUG(u'Signing in existing user %s' % (user.name, ))
    else:
        LOG(u'Creating new user with name %s and email %s, group: %s' %
            (google_profile['name'], google_profile['email'], group))
        user = User(
            name=google_profile['name'],
            email=email,
            refresh_token=credentials.refresh_token or '',
            groups=[group],
            roles=[],
        )

        DBSession.add(user)
        DBSession.flush()
    headers = remember(request, user.id)
    DEBUG(u'User %s set' % user.name)
    if group == 'client':
        location = request.url_for('/scrum/sprint/list')
    else:
        location = '/'
    return HTTPFound(
        location=location,
        headers=headers,
    )
예제 #8
0
def auth_view(request: pyramid.request.Request) -> None:
    """Get the authentication view."""
    if not is_auth(request):
        raise HTTPForbidden(
            "Missing or invalid secret (parameter, X-API-Key header or cookie)"
        )
예제 #9
0
파일: xreport.py 프로젝트: c2corg/v6_api
    def put(self):
        if not _has_permission(self.request, self.request.validated['id']):
            raise HTTPForbidden('No permission to change this xreport')

        return self._put(Xreport, schema_xreport)
예제 #10
0
    def read_many(self, public=False):
        """
        Return many :term:`Stakeholders`.

        .. seealso::
            :ref:`read-many`

        For each :term:`Stakeholder`, only one version is visible,
        always the latest visible version to the current user. This
        means that logged in users can see their own pending versions
        and moderators of the current profile can see pending versions
        as well. If you don't want to show pending versions, consider
        using
        :class:`lmkp.views.stakeholders.StakeholderView.read_many_public`
        instead.

        By default, the :term:`Stakeholders` are ordered with the
        :term:`Stakeholder` having the most recent change being on top.

        Args:
            ``public`` (bool): A boolean indicating whether to return
            only versions visible to the public (eg. pending) or not.

        Matchdict parameters:

            ``/stakeholders/{output}``

            ``output`` (str): If the output format is not valid, a 404
            Response is returned.

            The following output formats are supported:

                ``json``: Return the :term:`Stakeholders` as JSON.

                ``html``: Return the :term:`Stakeholders` as HTML (eg.
                the `Grid View`)

                ``form``: Returns the form to create a new
                :term:`Stakeholder`.

                ``download``: Returns the page to download
                :term:`Stakeholders`.

        Request parameters:
            ``page`` (int): The page parameter is used to paginate
            :term:`Items`. In combination with ``pagesize`` it defines
            the offset.

            ``pagesize`` (int): The pagesize parameter defines how many
            :term:`Items` are displayed at once. It is used in
            combination with ``page`` to allow pagination.

            ``status`` (str): Use the status parameter to limit results
            to displaying only versions with a certain :term:`status`.

        Returns:
            ``HTTPResponse``. Either a HTML or a JSON response.
        """
        output_format = get_output_format(self.request)

        if output_format == 'json':

            items = stakeholder_protocol.read_many(self.request, public=False)

            return render_to_response('json', items, self.request)

        elif output_format == 'html':

            page, page_size = get_page_parameters(self.request)
            items = stakeholder_protocol.read_many(self.request,
                                                   public=public,
                                                   limit=page_size,
                                                   offset=page_size * page -
                                                   page_size)

            spatial_filter = None
            status_filter = get_status_parameter(self.request)
            __, is_moderator = get_user_privileges(self.request)

            template_values = self.get_base_template_values()
            template_values.update({
                'data':
                items['data'] if 'data' in items else [],
                'total':
                items['total'] if 'total' in items else 0,
                'spatialfilter':
                spatial_filter,
                'invfilter':
                None,
                'statusfilter':
                status_filter,
                'currentpage':
                page,
                'pagesize':
                page_size,
                'is_moderator':
                is_moderator,
                'handle_query_string':
                handle_query_string
            })

            return render_to_response(
                get_customized_template_path(self.request,
                                             'stakeholders/grid.mak'),
                template_values, self.request)

        elif output_format == 'form':

            is_logged_in, __ = get_user_privileges(self.request)
            if not is_logged_in:
                raise HTTPForbidden()

            new_involvement = self.request.params.get('inv', None)
            template_values = renderForm(self.request,
                                         'stakeholders',
                                         inv=new_involvement)

            if isinstance(template_values, Response):
                return template_values

            template_values.update({
                'profile': get_current_profile(self.request),
                'locale': get_current_locale(self.request)
            })

            return render_to_response(
                get_customized_template_path(self.request,
                                             'stakeholders/form.mak'),
                template_values, self.request)

        elif output_format == 'download':

            download_view = DownloadView(self.request)

            return download_view.download_customize('stakeholders')

        else:
            raise HTTPNotFound()
예제 #11
0
def form(context, request):
    """
    XXX: Cannot merge into single view
        because of the way patient forms are handled
    """

    db_session = request.db_session
    visit = context.__parent__.__parent__
    allowed_schemata = (
        db_session.query(datastore.Schema)
        .join(models.study_schema_table)
        .join(models.Study)
        .join(models.Cycle)
        .filter(models.Cycle.id.in_([cycle.id for cycle in visit.cycles])))
    allowed_versions = [s.publish_date for s in allowed_schemata]

    if request.has_permission('retract'):
        transition = modes.ALL
    elif request.has_permission('transition'):
        transition = modes.AVAILABLE
    else:
        transition = modes.AUTO

    Form = make_form(
        db_session,
        context.schema,
        entity=context,
        show_metadata=True,
        transition=transition,
        allowed_versions=allowed_versions,
    )

    form = Form(request.POST, data=entity_data(context))

    if request.method == 'POST':

        if not request.has_permission('edit', context):
            raise HTTPForbidden()

        if form.validate():
            upload_dir = request.registry.settings['studies.blob.dir']
            apply_data(db_session, context, form.data, upload_dir)
            db_session.flush()
            request.session.flash(
                _(u'Changes saved for: ${form}', mapping={
                    'form': context.schema.title}),
                'success')
            return HTTPFound(location=request.current_route_path(
                _route_name='studies.visit'))

    return {
        'visit': view_json(visit, request),
        'form': render_form(
            form,
            disabled=not request.has_permission('edit'),
            cancel_url=request.current_route_path(_route_name='studies.visit'),
            attr={
                'method': 'POST',
                'action': request.current_route_path(),
                'role': 'form'
            }
        ),
    }
예제 #12
0
    def read_one(self, public=False):
        """
        Return one :term:`Stakeholder`.

        .. seealso::
            :ref:`read-one`

        Read one :term:`Stakeholder` or one version of a
        :term:`Stakeholder`. By default, this is the latest visible
        version to the current user. This means that logged in users can
        see their own pending version and moderators of the current
        profile can see a pending version as well. If you don't want to
        see a version pending, consider using
        :class:`lmkp.views.stakeholders.StakeholderView.read_one_public`
        instead.

        Args:
            ``public`` (bool): A boolean indicating to return only a
            version visible to the public (eg. pending) or not.

        Matchdict parameters:

            ``/stakeholders/{output}/{uid}``

            ``output`` (str): If the output format is not valid, a 404
            Response is returned.

            The following output formats are supported:

                ``json``: Return the :term:`Stakeholder` as JSON. All
                versions visible to the current user are returned.

                ``html``: Return the :term:`Stakeholder` as HTML (eg.
                the `Detail View`).

                ``form``: Returns the form to edit an existing
                :term:`Stakeholder`.

                ``compare``: Return the page to compare two versions of
                the :term:`Stakeholder`.

                ``review``: Return the page to review a pending version
                of a :term:`Stakeholder`.

            ``uid`` (str): An :term:`Stakeholder` :term:`UID`.

        Request parameters:
            ``translate`` (bool): Return translated values or not. This
            is only valid for the output format ``json``.

            ``v`` (int): Indicate a specific version to return. This is
            only valid for the output formats ``html`` and ``form``.

            ``camefrom`` (uid): Only valid for output format ``review``.
            Indicate a :term:`Activity` to return to after reviewing the
            :term:`Stakeholder`.

            ``ref`` (int) and ``new`` (int): Indicate specific versions.
            This is only valid for the output formats ``compare`` and
            ``review``.

        Returns:
            ``HTTPResponse``. Either a HTML or a JSON response.
        """
        output_format = get_output_format(self.request)

        uid = self.request.matchdict.get('uid', None)
        if validate_uuid(uid) is not True:
            raise HTTPNotFound()

        if output_format == 'json':

            translate = self.request.params.get('translate',
                                                'true').lower() == 'true'

            item = stakeholder_protocol.read_one(self.request,
                                                 uid=uid,
                                                 public=public,
                                                 translate=translate)

            return render_to_response('json', item, self.request)

        elif output_format == 'html':

            version = self.request.params.get('v', None)

            item = stakeholder_protocol.read_one(self.request,
                                                 uid=uid,
                                                 public=public,
                                                 translate=False)

            for i in item.get('data', []):

                item_version = i.get('version')
                if version is None:
                    # If there was no version provided, show the first
                    # version visible to the user
                    version = str(item_version)

                if str(item_version) == version:

                    template_values = self.get_base_template_values()
                    template_values.update(
                        renderReadonlyForm(self.request, 'stakeholders', i))
                    template_values.update({
                        'uid': uid,
                        'shortuid': shorten_uuid(uid),
                        'version': version,
                        # Temporarily disabled comments
                        'site_key': None,
                        # 'site_key': comments_sitekey(self.request)['site_key'],
                        # 'comments_url': self.request.registry.settings[
                        #     'lmkp.comments_url']
                    })

                    return render_to_response(
                        get_customized_template_path(
                            self.request, 'stakeholders/details.mak'),
                        template_values, self.request)

            return HTTPNotFound()

        elif output_format == 'form':

            is_logged_in, __ = get_user_privileges(self.request)
            if not is_logged_in:
                raise HTTPForbidden()

            version = self.request.params.get('v', None)

            item = stakeholder_protocol.read_one(self.request,
                                                 uid=uid,
                                                 public=False,
                                                 translate=False)

            for i in item.get('data', []):

                item_version = i.get('version')
                if version is None:
                    # If there was no version provided, show the first
                    # version visible to the user
                    version = str(item_version)

                if str(item_version) == version:

                    template_values = renderForm(self.request,
                                                 'stakeholders',
                                                 itemJson=i)
                    if isinstance(template_values, Response):
                        return template_values

                    template_values.update(self.get_base_template_values())

                    return render_to_response(
                        get_customized_template_path(self.request,
                                                     'stakeholders/form.mak'),
                        template_values, self.request)

            return HTTPNotFound()

        elif output_format in ['review', 'compare']:

            if output_format == 'review':
                # Only moderators can see the review page.
                is_logged_in, is_moderator = get_user_privileges(self.request)
                if not is_logged_in or not is_moderator:
                    raise HTTPForbidden()

            review = StakeholderReview(self.request)
            is_review = output_format == 'review'
            available_versions = review._get_available_versions(
                Stakeholder, uid, review=is_review)
            recalculated = False
            default_ref_version, default_new_version = review. \
                _get_valid_versions(Stakeholder, uid)

            try:
                ref_version = int(self.request.params.get('ref'))
            except:
                ref_version = None

            # For review or if no valid reference version is provided, use the
            # default reference version.
            if (output_format == 'review' or ref_version is None or ref_version
                    not in [v.get('version') for v in available_versions]):
                ref_version = default_ref_version

            try:
                new_version = int(self.request.params.get('new'))
            except:
                new_version = None

            if new_version is None or new_version not in [
                    v.get('version') for v in available_versions
            ]:
                new_version = default_new_version

            if output_format == 'review':
                # If the Items are to be reviewed, only the changes which were
                # applied to the new_version are of interest
                items, recalculated = review.get_comparison(
                    Stakeholder, uid, ref_version, new_version)
            else:
                # If the Items are to be compared, the versions as they are
                # stored in the database are of interest, without any
                # recalculation
                items = [
                    stakeholder_protocol.read_one_by_version(self.request,
                                                             uid,
                                                             ref_version,
                                                             translate=False),
                    stakeholder_protocol.read_one_by_version(self.request,
                                                             uid,
                                                             new_version,
                                                             translate=False)
                ]

            template_values = renderReadonlyCompareForm(self.request,
                                                        'stakeholders',
                                                        items[0],
                                                        items[1],
                                                        review=is_review)

            # Collect the metadata
            ref_metadata = {}
            new_metadata = {}
            missing_keys = []
            reviewable = False
            if items[0] is not None:
                ref_metadata = items[0].get_metadata(self.request)
            # Collect metadata and missing keys for the new version
            if items[1] is not None:
                new_metadata = items[1].get_metadata(self.request)

                items[1].mark_complete(
                    get_mandatory_keys(self.request, 'sh', False))
                missing_keys = items[1]._missing_keys
                localizer = get_localizer(self.request)
                if localizer.locale_name != 'en':
                    db_lang = DBSession.query(Language).filter(
                        Language.locale == localizer.locale_name).first()
                    missing_keys = get_translated_db_keys(
                        SH_Key, missing_keys, db_lang)
                    missing_keys = [m[1] for m in missing_keys]

                reviewable = (len(missing_keys) == 0
                              and 'reviewableMessage' in template_values
                              and template_values['reviewableMessage'] is None)

            if output_format == 'review':
                pending_versions = []
                for v in sorted(available_versions,
                                key=lambda v: v.get('version')):
                    if v.get('status') == 1:
                        pending_versions.append(v.get('version'))
                template_values['pendingVersions'] = pending_versions

            template_values.update(self.get_base_template_values())
            template_values.update({
                'identifier':
                uid,
                'refVersion':
                ref_version,
                'refMetadata':
                ref_metadata,
                'newVersion':
                new_version,
                'newMetadata':
                new_metadata,
                'missingKeys':
                missing_keys,
                'reviewable':
                reviewable,
                'recalculated':
                recalculated,
                'camefrom':
                self.request.params.get('camefrom', ''),
            })

            if output_format == 'review':
                template = get_customized_template_path(
                    self.request, 'stakeholders/review.mak')
            else:
                template = get_customized_template_path(
                    self.request, 'stakeholders/compare.mak')

            return render_to_response(template, template_values, self.request)

        # elif output_format == 'formtest':
        #
        #     version = self.request.params.get('v', None)
        #
        #     # Test if an Item is valid according to the form configuration
        #     items = stakeholder_protocol.read_one(
        #         self.request, uid=uid, public=False, translate=False)
        #
        #     for i in item.get('data', []):
        #
        #         item_version = i.get('version')
        #         if version is None:
        #             # If there was no version provided, show the first
        #             # version visible to the user
        #             version = str(item_version)
        #
        #         if str(item_version) == version:
        #
        #             categorylist = getCategoryList(
        #                 self.request, 'stakeholders')
        #             return render_to_response(
        #                 'json', checkValidItemjson(categorylist, i),
        #                 self.request)
        #
        #     return HTTPNotFound()

        else:
            raise HTTPNotFound()
예제 #13
0
파일: utils.py 프로젝트: jysandy/chestify
 def login_check(request):
     if request.authenticated_userid is not None:
         return view_func(request)
     else:
         return HTTPForbidden()
예제 #14
0
def webhook(request):
    """ Handle github webhook. """

    github_secret = request.registry.settings.get("github.secret")

    hex = hmac.new(github_secret, request.body, hashlib.sha1).hexdigest()
    valid_sig = "sha1=%s" % hex

    if 'X-Hub-Signature' not in request.headers:
        msg = "No X-Hub-Signature provided"
        raise HTTPUnauthorized(msg)

    actual_sig = request.headers['X-Hub-Signature']

    if actual_sig != valid_sig:
        msg = "Invalid X-Hub-Signature"
        raise HTTPForbidden(msg)

    if 'payload' in request.params:
        # pubsubhubbub
        payload = request.params['payload']
        payload = json.loads(payload)
    else:
        # whatever webhooks
        payload = request.json_body

    event_type = request.headers['X-Github-Event'].lower()

    # github sends us a 'ping' when we first subscribe to let us know that
    # it worked.
    if event_type == 'ping':
        event_type = 'webhook'

        # They don't actually tell us which repo is signed up, so, for
        # presentation purposes only, we'll rip out the repo name here and
        # build a nice human-clickable url.
        tokens = payload['hook']['url'].split('/')
        owner, repo = tokens[-4], tokens[-3]
        payload['compare'] = 'https://github.com/%s/%s' % (owner, repo)

    # Convert github.watch messages to github.star messages.
    # See http://da.gd/sUNkj
    if event_type == 'watch':
        event_type = 'star'

    # Turn just 'issues' into 'issue.reopened'
    if event_type == 'issues':
        event_type = 'issue.' + payload['action']

    # Same here
    if event_type == 'pull_request':
        event_type = 'pull_request.' + payload['action']

    # Make issues comments match our scheme more nicely
    if event_type == 'issue_comment':
        event_type = 'issue.comment'

    # Strip out a bunch of redundant information that github sends us
    payload = prune_useless_urls(payload)

    # Build a little table of github usernames to fas usernames so
    # consumers can have an easy time.
    fas_usernames = build_fas_lookup(payload)
    payload['fas_usernames'] = fas_usernames

    fedmsg.publish(
        modname="github",
        topic=event_type,
        msg=payload,
    )

    return "OK"
예제 #15
0
def hsts_redirect_to_https(event, secure_url=None):
    """Redirects `http://` GET requests to `https://` and blocks non `https://`
      requests to other request methods.
      
      Setup::
      
          >>> from mock import Mock
          >>> mock_request = Mock()
          >>> mock_event = Mock()
          >>> mock_event.request = mock_request
      
      Noop if the request is over https://
      
          >>> mock_request.scheme = 'https'
          >>> hsts_redirect_to_https(mock_event)
      
      Or if the value of the configured ``hsts.protocol_header`` is https::
      
          >>> mock_request.scheme = 'http'
          >>> mock_request.registry.settings = {'hsts.protocol_header': 'Foo'}
          >>> mock_request.headers = {'Foo': 'https'}
          >>> hsts_redirect_to_https(mock_event)
      
      Otherwise if a GET request, redirects to the https equivalent::
      
          >>> mock_request.scheme = 'http'
          >>> mock_request.registry.settings = {'hsts.protocol_header': 'Foo'}
          >>> mock_request.headers = {'Foo': 'http'}
          >>> mock_request.method = 'GET'
          >>> mock_request.url = 'http://foo.com'
          >>> try:
          ...     hsts_redirect_to_https(mock_event)
          ... except Exception as err:
          ...     assert err.status_int == 302
      
      Otherwise forbidden::
      
          >>> mock_request.method = 'POST'
          >>> try:
          ...     hsts_redirect_to_https(mock_event)
          ... except Exception as err:
          ...     assert err.status_int == 403
      
    """

    # Compose.
    if secure_url is None:
        secure_url = ensure_secure_url

    # Unpack the event.
    request = event.request
    settings = request.registry.settings

    # Exit if this is https (or any secure protocol).
    if request.scheme.endswith('s'):
        return

    # E.g.: on Heroku, they pass the protocol though using `X-Forwarded-Proto`.
    protocol_header = settings.get('hsts.protocol_header', None)
    if protocol_header:
        protocol = request.headers.get(protocol_header)
        if protocol and protocol.endswith('s'):
            return

    # If this is an insecure GET request, then redirect.
    if request.method == 'GET' or request.method == 'HEAD':
        raise HTTPFound(location=secure_url(request.url))

    # Otherwise refuse the request.
    raise HTTPForbidden()
예제 #16
0
def not_found_view(error, request):
    if request.method == 'POST' and isinstance(error, PredicateMismatch):
        # Return a 403 error on CSRF token mismatch.
        if not check_csrf_token(request, raises=False):
            return HTTPForbidden()
    return error
예제 #17
0
def make_403_error(message, realm="CIOC RPC"):
    error = HTTPForbidden()
    error.content_type = "text/plain"
    error.text = message
    return error
def verfiy_user_access_to_bill(user, bill):
    """Raise HTTPForbidden if use has no access."""
    if user is None or user.id != bill.user.id:
        raise HTTPForbidden()
예제 #19
0
def hello(request):
    """Say hello."""
    if request.openapi_validated.parameters["query"]["name"] == "admin":
        raise HTTPForbidden()
    return {"hello": request.openapi_validated.parameters["query"]["name"]}
예제 #20
0
 def _secure(context, request):
     if not has_permission(permission, context, request):
         raise HTTPForbidden('no permission')
     else:
         return view(context, request)
예제 #21
0
def viewPoints(request):
    lecture = request.context.lecture
    try:
        ls = lecture.lecture_students.filter(
            models.LectureStudent.student_id == request.user.id).one()
    except exc.NoResultFound:
        return HTTPForbidden()
    visible_exams = lecture.exams.filter((models.Exam.results_hidden == False)
                                         |
                                         (models.Exam.results_hidden == None))
    exams = visible_exams.all()
    exams_by_category = [{
        'id':
        cat['id'],
        'name':
        cat['name'],
        'exams':
        visible_exams.filter(models.Exam.category == cat['id']).all()
    } for cat in utils.categories]
    exams_by_category = [cat for cat in exams_by_category if cat['exams']]
    results = {}
    for exam in exams:
        results[exam.id] = exam.getResultsForStudent(ls.student)
    for exams in exams_by_category:
        sum_all = sum(
            [x for x in [results[e.id]['sum'] for e in exams['exams']] if x])
        max_all = sum(
            [x for x in [e.getMaxpoints() for e in exams['exams']] if x])
        exams['sum'] = sum_all
        exams['max'] = max_all
    exams_with_registration = [
        e for e in lecture.exams.all() if e.registration != None
    ]
    registrations = {}
    for reg in request.db.query(models.ExamAdmission).filter(
            models.ExamAdmission.exam_id.in_([
                e.id for e in exams_with_registration
            ])).filter(models.ExamAdmission.student_id == ls.student_id).all():
        registrations[reg.exam_id] = reg
    for exam in exams_with_registration:
        if not exam.id in registrations:
            registrations[exam.id] = models.ExamAdmission(exam=exam,
                                                          student=request.user)
        if 'registration-%s' % exam.id in request.POST:
            newreg = request.POST['registration-%s' % exam.id]
            if newreg == '':
                newreg = None
            elif newreg == '0':
                newreg = False
            elif newreg == '1':
                newreg = True
            else:
                raise ValueError
            registrations[exam.id].registration = newreg
            request.db.merge(registrations[exam.id])
            request.db.commit()
    exams_with_admission = [
        e for e in lecture.exams.all() if e.admission != None
    ]
    admissions = {}
    for adm in request.db.query(models.ExamAdmission).filter(
            models.ExamAdmission.exam_id.in_([
                e.id for e in exams_with_admission
            ])).filter(models.ExamAdmission.student_id == ls.student_id).all():
        admissions[adm.exam_id] = adm
    for exam in exams_with_admission:
        if not exam.id in admissions:
            admissions[exam.id] = models.ExamAdmission(exam=exam,
                                                       student=request.user)
    grades = request.user.student_grades.filter(
        models.StudentGrade.grading.has(
            models.Grading.lecture_id == lecture.id)).all()
    return {
        'lecture': lecture,
        'results': results,
        'exams_by_category': exams_by_category,
        'registrations': registrations,
        'admissions': admissions,
        'grades': grades,
    }
    return HTTPFound(
        location=request.route_url('lecture_view', lecture_id=lecture.id))
예제 #22
0
파일: security.py 프로젝트: dholth/sharder
def forbidden_view(request):
    """Throw a 401 if not logged in."""
    if not request.remote_user:
        return HTTPUnauthorized()
    return HTTPForbidden()
예제 #23
0
def post_extract(request):
    """
    Create a new extract.
    """
    extract_data = json.loads(request.body)
    discussion_id = int(request.matchdict['discussion_id'])
    user_id = authenticated_userid(request)
    if not user_id:
        # Straight from annotator
        token = request.headers.get('X-Annotator-Auth-Token')
        if token:
            token = decode_token(token,
                                 request.registry.settings['session.secret'])
            if token:
                user_id = token['userId']
    user_id = user_id or Everyone
    if not user_has_permission(discussion_id, user_id, P_ADD_EXTRACT):
        #TODO: maparent:  restore this code once it works:
        #return HTTPForbidden(result=ACLDenied(permission=P_ADD_EXTRACT))
        return HTTPForbidden()
    if not user_id or user_id == Everyone:
        # TODO: Create an anonymous user.
        raise HTTPServerError("Anonymous extracts are not implemeted yet.")
    content = None
    uri = extract_data.get('uri')
    important = extract_data.get('important', False)
    annotation_text = None
    if uri:
        # Straight from annotator
        annotation_text = extract_data.get('text')
    else:
        target = extract_data.get('target')
        if not (target or uri):
            raise HTTPBadRequest("No target")

        target_class = sqla.get_named_class(target.get('@type'))
        if issubclass(target_class, Post):
            post_id = target.get('@id')
            post = Post.get_instance(post_id)
            if not post:
                raise HTTPNotFound("Post with id '%s' not found." % post_id)
            content = post
        elif issubclass(target_class, Webpage):
            uri = target.get('url')
    if uri and not content:
        content = Webpage.get_instance(uri)
        if not content:
            # TODO: maparent:  This is actually a singleton pattern, should be
            # handled by the AnnotatorSource now that it exists...
            source = AnnotatorSource.default_db.query(
                AnnotatorSource).filter_by(discussion_id=discussion_id).filter(
                    cast(AnnotatorSource.name, Unicode) ==
                    'Annotator').first()
            if not source:
                source = AnnotatorSource(name='Annotator',
                                         discussion_id=discussion_id,
                                         type='source')
            content = Webpage(url=uri, discussion_id=discussion_id)
    extract_body = extract_data.get('quote', '')

    idea_id = extract_data.get('idIdea', None)
    if idea_id:
        idea = Idea.get_instance(idea_id)
        if (idea.discussion.id != discussion_id):
            raise HTTPBadRequest(
                "Extract from discussion %s cannot be associated with an idea from a different discussion."
                % extract.get_discussion_id())
    else:
        idea = None

    new_extract = Extract(creator_id=user_id,
                          owner_id=user_id,
                          discussion_id=discussion_id,
                          body=extract_body,
                          idea=idea,
                          important=important,
                          annotation_text=annotation_text,
                          content=content)
    Extract.default_db.add(new_extract)

    for range_data in extract_data.get('ranges', []):
        range = TextFragmentIdentifier(extract=new_extract,
                                       xpath_start=range_data['start'],
                                       offset_start=range_data['startOffset'],
                                       xpath_end=range_data['end'],
                                       offset_end=range_data['endOffset'])
        TextFragmentIdentifier.default_db.add(range)
    Extract.default_db.flush()

    return {'ok': True, '@id': new_extract.uri()}
예제 #24
0
 def __enter__(self):
     """Verify api key set in constructor"""
     if not AuthHelper.check_login(self.request, self.username):
         raise HTTPForbidden('Invalid Authorization')
예제 #25
0
파일: api.py 프로젝트: TheWug/weasyl
def api_user_view_(request):
    # Helper functions for this view.
    def convert_commission_price(value, options):
        return d.text_price_symbol(options) + d.text_price_amount(value)

    def convert_commission_setting(target):
        if target == "o":
            return "open"
        elif target == "s":
            return "sometimes"
        elif target == "f":
            return "filled"
        elif target == "c":
            return "closed"
        else:
            return None

    userid = request.userid
    otherid = profile.resolve_by_username(request.matchdict['login'])
    user = profile.select_profile(otherid)

    rating = d.get_rating(userid)
    o_config = user.pop('config')
    o_settings = user.pop('settings')

    if not otherid and "h" in o_config:
        raise HTTPForbidden(
            json={
                "error": {
                    "code": 200,
                    "text": "Profile hidden from unlogged users.",
                },
            })

    del user['userid']
    del user['commish_slots']

    user['created_at'] = d.iso8601(user.pop('unixtime'))
    user['media'] = api.tidy_all_media(user.pop('user_media'))
    user['login_name'] = d.get_sysname(user['username'])
    user['profile_text'] = markdown(user['profile_text'])

    user['folders'] = folder.select_list(otherid)

    commissions = {
        "details": None,
        "price_classes": None,
        "commissions": convert_commission_setting(o_settings[0]),
        "trades": convert_commission_setting(o_settings[1]),
        "requests": convert_commission_setting(o_settings[2])
    }

    commission_list = commishinfo.select_list(otherid)
    commissions['details'] = commission_list['content']

    if len(commission_list['class']) > 0:
        classes = list()
        for cclass in commission_list['class']:
            commission_class = {"title": cclass['title']}

            if len(commission_list['price']) > 0:
                prices = list()
                for cprice in (i for i in commission_list['price']
                               if i['classid'] == cclass['classid']):
                    if 'a' in cprice['settings']:
                        ptype = 'additional'
                    else:
                        ptype = 'base'

                    price = {
                        "title":
                        cprice['title'],
                        "price_min":
                        convert_commission_price(cprice['amount_min'],
                                                 cprice['settings']),
                        "price_max":
                        convert_commission_price(cprice['amount_min'],
                                                 cprice['settings']),
                        'price_type':
                        ptype
                    }
                    prices.append(price)
                commission_class['prices'] = prices

            classes.append(commission_class)
        commissions['price_classes'] = classes

    user['commission_info'] = commissions

    user['relationship'] = profile.select_relation(userid,
                                                   otherid) if userid else None

    if 'O' in o_config:
        submissions = collection.select_list(userid,
                                             rating,
                                             11,
                                             otherid=otherid)
        more_submissions = 'collections'
        featured = None
    elif 'A' in o_config:
        submissions = character.select_list(userid,
                                            rating,
                                            11,
                                            otherid=otherid)
        more_submissions = 'characters'
        featured = None
    else:
        submissions = submission.select_list(userid,
                                             rating,
                                             11,
                                             otherid=otherid,
                                             profile_page_filter=True)
        more_submissions = 'submissions'
        featured = submission.select_featured(userid, otherid, rating)

    for sub in submissions:
        tidy_submission(sub)

    user['recent_submissions'] = submissions
    user['recent_type'] = more_submissions

    if featured:
        tidy_submission(featured)

    user['featured_submission'] = featured

    statistics, show_statistics = profile.select_statistics(otherid)
    del statistics['staff_notes']
    user['statistics'] = statistics if show_statistics else None

    user_info = profile.select_userinfo(otherid, config=o_config)
    if not user_info['show_age']:
        user_info['age'] = None
    del user_info['show_age']
    del user_info['birthday']
    user_info['location'] = user_info.pop('country')
    user['user_info'] = user_info
    user['link'] = d.absolutify_url("/~" + user['login_name'])

    return user
예제 #26
0
def __ensure_task_locked(task, user):
    locked_task = get_locked_task(task.project_id, user)
    if locked_task != task:
        raise HTTPForbidden("You need to lock the task first.")
예제 #27
0
 def delete_requests(self):
     self.send(auth='', exception=HTTPUnauthorized())
     self.send(auth='bad_user:'******'other_user:', exception=HTTPForbidden())
     self.send(status=204)
예제 #28
0
 def is_allowed(self, request):
     if self.user.isAdmin():
         return True
     else:
         raise HTTPForbidden()
예제 #29
0
 def require_administrator(request):
     if not request.user.is_administrator:
         raise HTTPForbidden(
             explanation="Membership in group 'administrators' required!")
예제 #30
0
    def challenge(self, request, content="Unauthorized"):
        if self.authenticated_userid(request):
            return HTTPUnauthorized(content, headers=self.forget(request))

        return HTTPForbidden(content, headers=self.forget(request))