def claim(self, request):
     #Is the ticket open?
     if self.get_workflow_state() != 'open':
         raise Forbidden("Access already granted with this ticket")
     #Find required resources and do some basic validation
     meeting = find_interface(self, IMeeting)
     assert meeting
     userid = authenticated_userid(request)
     if userid is None:
         raise Forbidden("You can't claim a ticket unless you're authenticated.")
     meeting.add_groups(userid, self.roles)
     self.claimed_by = userid
     self.set_workflow_state(request, 'closed')
     self.closed = utcnow()
Beispiel #2
0
    def _get_client(self):
        """If the request can be identified and a client configuration for
        the client is found, the client (dict) is returned.
        Otherwise `Forbidden` is raised.
        """
        origin = self.request.headers.get('X-BRIDGE-ORIGIN', None)
        if origin is None:
            raise Forbidden()

        client = getUtility(IClientManager).get_client_by_id(origin)
        if client is None:
            raise Forbidden()

        return client
Beispiel #3
0
def paste_node(context, request):
    id, action = request.session['kotti.paste']
    item = DBSession.query(Node).get(id)
    if item is not None:
        if action == 'cut':
            if not has_permission('edit', item, request):
                raise Forbidden()
            item.__parent__.children.remove(item)
            context.children.append(item)
            del request.session['kotti.paste']
        elif action == 'copy':
            copy = item.copy()
            name = copy.name
            if not name:  # for root
                name = copy.title
            name = title_to_name(name, blacklist=context.keys())
            copy.name = name
            context.children.append(copy)
        request.session.flash(
            _(u'${title} pasted.', mapping=dict(title=item.title)), 'success')
    else:
        request.session.flash(
            _(u'Could not paste node. It does not exist anymore.'), 'error')
    if not request.is_xhr:
        location = resource_url(context, request)
        return HTTPFound(location=location)
Beispiel #4
0
def deactivate_profile_view(context, request):
    page_title = 'Deactivate user account for %s %s' % (context.firstname,
                                                        context.lastname)
    api = TemplateAPI(context, request, page_title)

    name = context.__name__
    myself = authenticated_userid(request) == context.__name__

    if not api.user_is_admin and not myself:
        raise Forbidden("Only owner or admin can deactivate profile")

    confirm = request.params.get('confirm')
    if confirm:
        try:
            find_users(context).remove(name)
        except KeyError:
            pass
        workflow = get_workflow(IProfile, 'security', context)
        workflow.transition_to_state(context, request, 'inactive')
        if myself:
            return logout_view(context, request, reason='User removed')
        query = {'status_message': 'Deactivated user account: %s' % name}
        parent = context.__parent__
        location = resource_url(parent, request, query=query)

        return HTTPFound(location=location)

    # Show confirmation page.
    return dict(api=api, myself=myself)
Beispiel #5
0
    def paste_nodes(self):
        """ Paste nodes view.  Paste formerly copied or cutted nodes into the
        current context.  Note that a cutted node can not be pasted into itself.

        :result: Redirect response to the referrer of the request.
        :rtype: pyramid.httpexceptions.HTTPFound
        """
        ids, action = self.request.session["kotti.paste"]
        for count, id in enumerate(ids):
            item = DBSession.query(Node).get(id)
            if item is not None:
                if action == "cut":
                    if not self.request.has_permission("edit", item):
                        raise Forbidden()
                    item.__parent__.children.remove(item)
                    item.name = title_to_name(item.name, blacklist=self.context.keys())
                    self.context[item.name] = item
                    if count is len(ids) - 1:
                        del self.request.session["kotti.paste"]
                elif action == "copy":
                    copy = item.copy()
                    name = copy.name
                    if not name:  # for root
                        name = copy.title
                    name = title_to_name(name, blacklist=self.context.keys())
                    copy.name = name
                    self.context[name] = copy
                self.flash(
                    _("${title} was pasted.", mapping=dict(title=item.title)), "success"
                )
            else:
                self.flash(_("Could not paste node. It no longer exists."), "error")
        DBSession.flush()
        if not self.request.is_xhr:
            return self.back()
Beispiel #6
0
def test_view(request):
    debug = False
    f = Flash()
    f.critical('flashin test...')
    #~ relaties = DBSession.query(Relatie)
    relaties_dinsdag = request.mongo_db['relaties'].find(
        {"Relatie.children.news.children.day.text": "dinsdag"})
    relaties_vrijdag = request.mongo_db['relaties'].find(
        {"Relatie.children.news.children.day.text": "dinsdag"})
    records = dict()
    records['dinsdag'] = dict(
        (record['_id'], type(record['_id'])) for record in relaties_dinsdag)
    records['vrijdag'] = dict(
        (record['_id'], record) for record in relaties_vrijdag)
    l = type(records['dinsdag'].items())
    #~ g = TestView.get_grid(Relatie, relaties)
    debug = '\n'.join((str(type(records)), str(l)))
    userid = authenticated_userid(request)
    if userid is None:
        raise Forbidden()
    return {
        'relaties': records,
        'greeting': 'Hello, {n}!'.format(n=userid),
        'debug': debug,
        'flash': f.render(),
    }
Beispiel #7
0
    def paste_nodes(self):
        """
        Paste nodes view. Paste formerly copied or cutted nodes into the
        current context. Note that a cutted node can not be pasted into itself.

        :result: Redirect response to the referrer of the request.
        :rtype: pyramid.httpexceptions.HTTPFound
        """
        ids, action = self.request.session['kotti.paste']
        for count, id in enumerate(ids):
            item = DBSession.query(Node).get(id)
            if item is not None:
                if action == 'cut':
                    if not has_permission('edit', item, self.request):
                        raise Forbidden()
                    item.__parent__.children.remove(item)
                    self.context.children.append(item)
                    if count is len(ids) - 1:
                        del self.request.session['kotti.paste']
                elif action == 'copy':
                    copy = item.copy()
                    name = copy.name
                    if not name:  # for root
                        name = copy.title
                    name = title_to_name(name, blacklist=self.context.keys())
                    copy.name = name
                    self.context.children.append(copy)
                self.flash(
                    _(u'${title} was pasted.', mapping=dict(title=item.title)),
                    'success')
            else:
                self.flash(_(u'Could not paste node. It no longer exists.'),
                           'error')
        if not self.request.is_xhr:
            return self.back()
Beispiel #8
0
def valid_model_id(request):
    """
    A Cornice validator that returns a 404 if a valid model was not found
    in the user's session.
    """
    model = None
    model_id = request.matchdict.get('model_id', None)
    Model = request.registry.settings.Model

    if model_id:
        try:
            model = Model.get(model_id)
        except Model.DoesNotExist:
            model = None

    if model is None:
        request.errors.add('body', 'model', 'Model not found.')
        request.errors.status = 404
        return

    authenticated_model_id = request.session.get(
        request.registry.settings['model_session_key'], None)

    if model.id != authenticated_model_id:
        raise Forbidden()

    request.validated['model'] = model
def forbidden_view(request):
    # do not allow a user to login if they are already logged in
    if authenticated_userid(request):
        return Forbidden()

    loc = route_url('login', request, _query=(('next', request.path), ))
    return HTTPFound(location=loc)
Beispiel #10
0
def peopledirectory_view(context, request):
    # show the first accessible tab
    for section_id in context.order:
        section = context[section_id]
        if has_permission('view', section, request):
            return HTTPFound(location=resource_url(section, request))
    raise Forbidden("No accessible sections")
Beispiel #11
0
def manage_stashes(event):
    """Pyramid listener that attaches the current stash, if any, to
    ``request.stash``.  Also changes the request method to POST if a return key
    was used and there is any stashed POST data."""

    request = event.request
    request.stash = None

    key = key_from_request(request)
    stash = fetch_stash(request, request.path, key)

    if stash:
        request.stash = stash
        log.debug("Consuming stash '{0}: {1}'".format(request.path, stash))

        if key and stash['post']:
            # Turn this request into a POST.  This side-steps the anti-CSRF
            # protection measures in floof.app, so check the CSRF token here
            token = stash['post'].get('csrf_token')
            real_token = request.session.get_csrf_token()

            if token != real_token and 'paste.testing' not in request.environ:
                from pyramid.exceptions import Forbidden
                raise Forbidden('Possible cross-site request forgery.')

            request.method = 'POST'

        drop_stash(request, request.path, key=stash['key'])
Beispiel #12
0
    def verify(*args, **kwargs):
        request = args[0].request
        if global_config.AUTH_ENABLED is True:
            api_key = extract_token(request)
            if not api_key:
                raise Forbidden(INVALID_API_KEY)

            userContext = UserContextFactory(request)
            user = userContext.get_member_by_api_key(api_key)
            if user is None:
                raise Forbidden(INVALID_API_KEY)
            else:
                return view_function(*args, **kwargs)

        else:
            return view_function(*args, **kwargs)
Beispiel #13
0
    def __getitem__(self, key):
        if key == 'current-user':
            user = get_current_user()
            if user == None:
                raise Forbidden()
            key = user.slug

        return Collection.__getitem__(self, key)
Beispiel #14
0
    def authorize(self):
        client = self._get_client()
        plugin = self._get_authorization_plugin(client.clientid)

        if plugin.is_authorized(client) != True:
            raise Forbidden()
        else:
            return True
Beispiel #15
0
 def test_traverser_raises_forbidden_instance(self):
     from pyramid.exceptions import Forbidden
     environ = self._makeEnviron()
     context = DummyContext()
     self._registerTraverserFactory(context, raise_error=Forbidden('foo'))
     router = self._makeOne()
     start_response = DummyStartResponse()
     why = exc_raised(Forbidden, router, environ, start_response)
     self.failUnless('foo' in why[0], why)
Beispiel #16
0
def delete_profile(request):
    userid = authenticated_userid(request)
    profile = db.Profile(request.matchdict["name"])
    profile_info = profile.get()
    if profile_info["uploader"] != userid:
        raise Forbidden("profile can only be deleted by uploader")
    try:
        pro_msg = profile.delete()
    except Exception, e:
        pro_msg = "ERROR: " + str(e)
Beispiel #17
0
    def test_login_authenticated(self):
        from pyramid.exceptions import Forbidden
        request = testing.DummyRequest()
        request.user = '******'
        request.exception = Forbidden()
        views = Views(request)

        response = views.login()

        self.assertIsInstance(response, Forbidden)
Beispiel #18
0
def pm_delete(request):
    pid = request.matchdict["id"]
    pm = DBSession.query(PrivateMessage).filter(
        PrivateMessage.id == pid).first()
    if pm.user_to == request.user or request.user.category == "admin":
        DBSession.delete(pm)
    else:
        raise Forbidden("That's not your PM")

    return HTTPFound(request.referrer or request.route_url('pms'))
Beispiel #19
0
def pm_read(request):
    pid = request.matchdict["id"]
    pm = DBSession.query(PrivateMessage).filter(
        PrivateMessage.id == pid).first()
    if pm.user_to == request.user:
        pm.is_read = True
        return {"pm": pm}
    elif request.user.category == "admin":  # FIXME has_permission
        return {"pm": pm}
    else:
        raise Forbidden("That's not your PM")
def check_auth(request):
    if request.user is None:
        raise Forbidden()

    # user white list
    authorized_users = request.registry.settings.get('authorized_users', '')
    authorized_users = authorized_users.split(',')
    for user in authorized_users:
        if request.user == user:
            return request.user

    # domain white list
    authorized_domains = request.registry.settings.get('authorized_domains',
                                                       'mozilla.com')
    authorized_domains = authorized_domains.split(',')
    for domain in authorized_domains:
        if request.user.endswith('@' + domain):
            return request.user

    raise Forbidden()
Beispiel #21
0
def lucky_number(request):
    """Pyramid view to generate a lucky number."""

    # Check that the user is authenticated.
    userid = authenticated_userid(request)
    if userid is None:
        raise Forbidden()

    # Generate and return the lucky number.
    number = random.randint(1, 100)
    return Response(TEMPLATE.format(**locals()), content_type="text/plain")
Beispiel #22
0
def forbidden_userprofiles(request):
    userid = authenticated_userid(request)
    allowed = db.UserProfiles(userid).get()
    md = request.matchdict
    looking = md["profiles"].split(',') if "profiles" in md else []
    if "name" in md:
        for name in md["name"].split(","):
            looking.append(name)
    # print looking, allowed
    for pname in looking:
        if pname not in allowed:
            raise Forbidden()
Beispiel #23
0
def set_info(request):
    """Set the public information for a **user**.

    You have to be that user, and *authenticated*.

    Returns *True* or *False*.
    """
    username = authenticated_userid(request)
    if request.matchdict["username"] != username:
        raise Forbidden()
    _USERS[username] = request.json_body
    return {'success': True}
Beispiel #24
0
    def dispatch(self):
        user_id = self.request.GET.get('user_id')

        if user_id and self.request.has_perm('admin'):
            user = User.query.get(user_id)
        elif user_id:
            raise Forbidden()
        else:
            user = self.request.user
        form = UserEditForm(self.request.POST, obj=user)
        if self.request.method == 'POST' and form.validate():
            user.availability_link = form.availability_link.data or None
            user.tasks_link = form.tasks_link.data or None
            user.skype = form.skype.data or None
            user.phone = form.phone.data or None
            user.phone_on_desk = form.phone_on_desk.data or None
            user.irc = form.irc.data or None
            user.location = form.location.data or None
            user.start_work = form.start_work.data or None
            user.description = form.description.data or None
            user.date_of_birth = form.date_of_birth.data or None
            user.roles = form.roles.data
            if self.request.has_perm('admin'):
                user.is_active = form.is_active.data
                groups = form.groups.data
                if "freelancer" in groups:
                    groups.remove('freelancer')
                    user.freelancer = True
                else:
                    user.freelancer = False
                user.groups = groups
                user.start_full_time_work = form.start_full_time_work.data or None
                user.stop_work = form.stop_work.data or None
            if self.request.has_perm('admin'):
                user.employment_contract = form.employment_contract.data

            if form.avatar.data:
                preview = Preview(self.request)
                if not preview.swap_avatar(type='users', id=user.id):
                    self.flash(self._(u"No preview to swap"))

            self.flash(self._(u"User data saved"))
            LOG(u"User data saved")
            if user_id and self.request.has_perm('admin'):
                return HTTPFound(location=self.request.url_for(
                    '/user/edit', user_id=user_id))
            else:
                return HTTPFound(location=self.request.url_for('/user/edit'))

        if user.freelancer:
            form.groups.data = user.groups + ['freelancer']
        return dict(id=user.id, user=user, form=form)
Beispiel #25
0
    def dispatch(self):
        user_id = self.request.GET.get('user_id')

        if user_id and self.request.has_perm('can_edit_users'):
            user = User.query.get(user_id)
        elif user_id:
            raise Forbidden()
        else:
            user = self.request.user

        if not user:
            raise HTTPNotFound()

        form = UserEditForm(self.request.POST, obj=user)
        if self.request.method == 'POST' and form.validate():
            user.availability_link = form.availability_link.data or None
            user.tasks_link = form.tasks_link.data or None
            user.skype = form.skype.data or None
            user.phone = form.phone.data or None
            user.phone_on_desk = form.phone_on_desk.data or None
            user.irc = form.irc.data or None
            user.location = form.location.data or None
            user.start_work = form.start_work.data or None
            user.description = form.description.data or None
            user.date_of_birth = form.date_of_birth.data or None
            user.roles = form.roles.data
            if self.request.has_perm('can_edit_users'):
                user.is_active = form.is_active.data
                user.start_work_experience = form.start_work_experience.data or None
                user.start_full_time_work = form.start_full_time_work.data or None
                user.stop_work = form.stop_work.data or None
                user.employment_contract = form.employment_contract.data

            if self.request.has_perm('can_add_user_to_group'):
                groups = form.groups.data

                if 'coordinator' in user.groups:
                    groups.append('coordinator')
                user.groups = groups

            if form.avatar.data:
                preview = Preview(self.request)
                if not preview.swap_avatar(type='users', id=user.id):
                    self.flash(self._(u"No preview to swap"))

            self.flash(self._(u"User data saved"))
            LOG(u"User data saved")
            if user_id and self.request.has_perm('can_edit_users'):
                return HTTPFound(location=self.request.url_for('/user/edit', user_id=user_id))
            else:
                return HTTPFound(location=self.request.url_for('/user/edit'))
        return dict(id=user.id, user=user, form=form)
Beispiel #26
0
def provision_creds(request):
    """Pyramid view to provision MACAuth credentials."""

    # Check that the user is authenticated.
    userid = authenticated_userid(request)
    if userid is None:
        raise Forbidden()

    # Get a reference to the MACAuthenticationPolicy plugin.
    policy = request.registry.getUtility(IAuthenticationPolicy)
    policy = policy.get_policy(MACAuthenticationPolicy)

    # Generate a new id and secret key for the current user.
    id, key = policy.encode_mac_id(request, userid)
    return {"id": id, "key": key}
Beispiel #27
0
    def from_request(cls, request):
        server_secret = request.registry.settings['secret_key']
        client_secret = request.POST.get('secret')
        if client_secret != server_secret:
            raise Forbidden('Invalid secret')
        raw_message = RawMessage()
        raw_message.message_id = uuid.UUID(request.POST['message_id'])
        raw_message.sent_from = request.POST['from']
        raw_message.body = request.POST['message']
        raw_message.sent_to = request.POST['sent_to']
        raw_message.gateway_id = request.POST['device_id']
        raw_message.sent_timestamp = datetime.utcfromtimestamp(
            int(request.POST['sent_timestamp']) / 1000)

        return raw_message
Beispiel #28
0
def prevent_csrf(event):
    """Require a CSRF token on all POST requests.

    Ignore tests, though, for dev sanity.
    """
    request = event.request
    if (request.method == 'POST' and 'paste.testing' not in request.environ
            and not request.path.startswith('/_debug_toolbar/')
            and request.POST.get('csrf_token',
                                 None) != request.session.get_csrf_token()):

        # Token is wrong!
        if not request.cookies:
            raise NoCookiesError

        from pyramid.exceptions import Forbidden
        raise Forbidden('Possible cross-site request forgery detected.')
Beispiel #29
0
    def __call__(self):
        user = self.request.user
        if user is None:
            raise Forbidden()

        api = template_api(self.context, self.request)
        api.page_title = _("My preferences - ${title}",
                           mapping=dict(title=api.site_title))

        form = self.PreferencesFormView(user, self.request)()

        if self.request.is_response(form):
            return form

        return {
            "api": api,
            "form": form["form"],
            "macro": api.macro("kotti:templates/site-setup/master.pt"),
        }
Beispiel #30
0
def preferences(context, request):
    user = request.user
    if user is None:
        raise Forbidden()

    api = template_api(context, request)
    api.page_title = _(u"My preferences - ${title}",
                       mapping=dict(title=api.site_title))

    form = PreferencesFormView(user, request)()

    if request.is_response(form):
        return form

    return {
        'api': api,
        'form': form['form'],
        'macro': api.macro('kotti:templates/site-setup/master.pt'),
    }