Esempio n. 1
0
    def check(self, *a, **kw):

        auth_check = authorization.AuthCheck(method=self.obj.__name__)
        self.obj(auth_check, *a, **kw)

        if self.raise_type == RETURN_AUTH_CHECK:
            return auth_check

        elif self.raise_type == RETURN_BOOL:
            return bool(auth_check)

        else:
            assert (self.raise_type in [RETURN_TEMPLATE, RETURN_DECORATOR])
            if auth_check:
                if self.raise_type == RETURN_DECORATOR:
                    return self.closure()
                else:
                    return auth_check
            elif auth_check.need_login():
                # Authentication might help
                from adhocracy.lib.helpers import login_redirect_url
                from pylons.controllers.util import redirect
                redirect(login_redirect_url())
            else:
                from adhocracy.lib.templating import ret_abort
                log.debug("Aborting due to authorisation error: %s" %
                          repr(self.obj))
                ret_abort(_("We're sorry, but it seems that you lack the "
                            "permissions to continue."),
                          code=403)
Esempio n. 2
0
    def leave(self, id, format='html'):
        c.page_instance = self._get_current_instance(id)
        if not c.page_instance in c.user.instances:
            return ret_abort(
                entity=c.page_instance, format=format,
                message=_("You're not a member of %(instance)s.") % {
                    'instance': c.page_instance.label})
        elif c.user == c.page_instance.creator:
            return ret_abort(
                entity=c.page_instance, format=format,
                message=_("You're the founder of %s, cannot leave.") % {
                    'instance': c.page_instance.label})
        require.instance.leave(c.page_instance)

        for membership in c.user.memberships:
            if membership.is_expired():
                continue
            if membership.instance == c.page_instance:
                membership.expire()
                model.meta.Session.add(membership)

                c.user.revoke_delegations(c.page_instance)

                event.emit(event.T_INSTANCE_LEAVE, c.user,
                           instance=c.page_instance)
        model.meta.Session.commit()
        return ret_success(entity=c.page_instance, format=format,
                           message=_("You've left %(instance)s.") % {
                               'instance': c.page_instance.label})
Esempio n. 3
0
    def check(self, *a, **kw):

        auth_check = authorization.AuthCheck(method=self.obj.__name__)
        self.obj(auth_check, *a, **kw)

        if self.raise_type == RETURN_AUTH_CHECK:
            return auth_check

        elif self.raise_type == RETURN_BOOL:
            return bool(auth_check)

        else:
            assert(self.raise_type in [RETURN_TEMPLATE, RETURN_DECORATOR])
            if auth_check:
                if self.raise_type == RETURN_DECORATOR:
                    return self.closure()
                else:
                    return auth_check
            elif auth_check.need_login():
                # Authentication might help
                from adhocracy.lib.helpers import login_redirect_url
                from pylons.controllers.util import redirect
                redirect(login_redirect_url())
            else:
                from adhocracy.lib.templating import ret_abort
                log.debug("Aborting due to authorisation error: %s" %
                          repr(self.obj))
                ret_abort(_("We're sorry, but it seems that you lack the "
                            "permissions to continue."), code=403)
Esempio n. 4
0
    def _decorate(f, *a, **kw):
        def check():
            if config.get('skip_authentication'):
                return True

            method = request.environ.get('REQUEST_METHOD').upper()
            if not method in methods:
                return False

            if method in ['POST', 'PUT']:  # hack
                return True

            identifier = request.environ.get(
                'repoze.who.identity', {}).get('identifier')
            if (identifier is not None and
                isinstance(identifier, BasicAuthPlugin)):
                return True

            if request.params.get(KEY) == token_id():
                return True

            return False
        if check():
            return f(*a, **kw)
        else:
            from adhocracy.lib.templating import ret_abort
            ret_abort(_("I'm sorry, it looks like we made a mistake "
                        "(CSRF alert). Please try again."), code=403)
Esempio n. 5
0
    def details(self, proposal_id, selection_id, format='html'):
        '''
        '''
        selection = get_entity_or_abort(model.Selection, selection_id)
        proposal = get_entity_or_abort(model.Proposal, proposal_id)
        if selection.proposal is not proposal:
            ret_abort(_('Page not Found'), code=404)
        c.page = selection.page
        variant_polls = dict(selection.variant_polls)
        variant_to_show = selection.selected
        if not variant_to_show:
            variant_to_show = model.Text.HEAD

        variant_items = PageController.variant_items(c.page,
                                                       selection=selection)
        get_score = lambda item: \
            selection.variant_poll(item['variant']).tally.score
        c.variant_items = PageController.insert_variant_score_and_sort(
            variant_items, get_score)

        c.variant_details = PageController.variant_details(
            c.page, variant_to_show)
        c.variant_details_json = json.dumps(c.variant_details, indent=4)
        c.selection_details = PageController.selection_urls(selection)
        c.selection_details_json = json.dumps(c.selection_details, indent=4)
        c.current_variant_poll = variant_polls[variant_to_show]
        c.selection = selection
        if format == 'overlay':
            return render('/proposal/details.html', overlay=True)
        return render('/proposal/details.html')
Esempio n. 6
0
    def leave(self, id, format='html'):
        c.page_instance = self._get_current_instance(id)
        if not c.page_instance in c.user.instances:
            return ret_abort(
                entity=c.page_instance, format=format,
                message=_("You're not a member of %(instance)s.") % {
                                    'instance': c.page_instance.label})
        elif c.user == c.page_instance.creator:
            return ret_abort(
                entity=c.page_instance, format=format,
                message=_("You're the founder of %s, cannot leave.") % {
                                    'instance': c.page_instance.label})
        require.instance.leave(c.page_instance)

        for membership in c.user.memberships:
            if membership.is_expired():
                continue
            if membership.instance == c.page_instance:
                membership.expire()
                model.meta.Session.add(membership)

                c.user.revoke_delegations(c.page_instance)

                event.emit(event.T_INSTANCE_LEAVE, c.user,
                           instance=c.page_instance)
        model.meta.Session.commit()
        return ret_success(entity=c.page_instance, format=format,
                           message=_("You've left %(instance)s.") % {
                                'instance': c.page_instance.label})
Esempio n. 7
0
    def _decorate(f, *a, **kw):
        def check():

            method = request.environ.get('REQUEST_METHOD').upper()
            if not method in methods:
                return False

            if method in ['POST', 'PUT']:  # hack
                return True

            identifier = request.environ.get('repoze.who.identity',
                                             {}).get('identifier')
            if (identifier is not None
                    and isinstance(identifier, BasicAuthPlugin)):
                return True

            if request.params.get(KEY) == token_id():
                return True

            return False

        if check():
            return f(*a, **kw)
        else:
            from adhocracy.lib.templating import ret_abort
            ret_abort(_("I'm sorry, it looks like we made a mistake "
                        "(CSRF alert). Please try again."),
                      code=403)
Esempio n. 8
0
 def connect(self):
     if not openid_login_allowed() and "facebook" not in allowed_login_types():
         ret_abort(_("Connection not allowed, single sign-on has been " "disabled on this installation"), code=403)
     require.user.edit(c.user)
     if not c.user:
         h.flash(_("No OpenID was entered."), "warning")
         redirect("/login")
     return render("/openid/connect.html")
Esempio n. 9
0
    def __call__(self, *a, **kw):
        ret = self.obj(*a, **kw)
        if not ret:
            from adhocracy.lib.templating import ret_abort

            log.debug("Aborting due to error with permission: %s" % repr(self.obj))
            ret_abort(_("We're sorry, but it seems that you lack the " "permissions to continue."), code=403)
        return ret
Esempio n. 10
0
 def connect(self):
     if not openid_login_allowed():
         ret_abort(_("Connection not allowed, OpenID has been disabled on this installation"), code=403)
     require.user.edit(c.user)
     if not c.user:
         h.flash(_("No OpenID was entered."), 'warning')
         redirect("/login")
     return render("/openid/connect.html")
Esempio n. 11
0
 def __call__(self, *a, **kw):
     ret = self.obj(*a, **kw)
     if not ret:
         from adhocracy.lib.templating import ret_abort
         log.debug("Aborting due to error with permission: %s" %
                   repr(self.obj))
         ret_abort(_("We're sorry, but it seems that you lack the "
                     "permissions to continue."),
                   code=403)
     return ret
Esempio n. 12
0
 def create_form(self, topic):
     topic = model.Delegateable.find(int(topic))
     if topic is None:
         return ret_abort(_('Wrong topic'))  # FIXME: better msg
     require.comment.create_on(topic)
     variant = request.params.get('variant', None)
     if hasattr(topic, 'variants') and not variant in topic.variants:
         return ret_abort(_("Comment topic has no variant %s") % variant,
                          code=400)
     return self._render_ajax_create_form(None, topic, variant)
Esempio n. 13
0
 def create_form(self, topic):
     topic = model.Delegateable.find(int(topic))
     if topic is None:
         return ret_abort(_('Wrong topic'))  # FIXME: better msg
     require.comment.create_on(topic)
     variant = request.params.get('variant', None)
     if hasattr(topic, 'variants') and not variant in topic.variants:
         return ret_abort(_("Comment topic has no variant %s") % variant,
                          code=400)
     return self._render_ajax_create_form(None, topic, variant)
Esempio n. 14
0
    def request_auth(self):
        if 'shibboleth' not in allowed_login_types():
            ret_abort(_("Shibboleth authentication not enabled"), code=403)

        came_from = request.GET.get('came_from', '/')

        came_from_qs = urlencode({'came_from': came_from})
        shib_qs = urlencode(
            {'target': '/shibboleth/post_auth?%s' % came_from_qs})

        redirect('/Shibboleth.sso/Login?%s' % shib_qs)
Esempio n. 15
0
    def request_auth(self):
        if 'shibboleth' not in allowed_login_types():
            ret_abort(_("Shibboleth authentication not enabled"), code=403)

        came_from = request.GET.get('came_from', '/')

        came_from_qs = urlencode({'came_from': came_from})
        shib_qs = urlencode(
            {'target': '/shibboleth/post_auth?%s' % came_from_qs})

        redirect('/Shibboleth.sso/Login?%s' % shib_qs)
Esempio n. 16
0
 def connect(self):
     if (not openid_login_allowed()
             and 'facebook' not in allowed_login_types()):
         ret_abort(_("Connection not allowed, single sign-on has been "
                     "disabled on this installation"),
                   code=403)
     require.user.edit(c.user)
     if not c.user:
         h.flash(_("No OpenID was entered."), 'warning')
         redirect("/login")
     return render("/openid/connect.html")
Esempio n. 17
0
    def wrapper(self):
        allowed_sender_options = self.get_allowed_sender_options(c.user)
        sender = self.form_result.get('sender')
        if ((sender not in allowed_sender_options) or
                (not allowed_sender_options[sender]['enabled'])):
            return ret_abort(_("Sorry, but you're not allowed to set these "
                               "message options"), code=403)

        recipients = User.all_q()
        filter_instances = self.form_result.get('filter_instances')
        recipients = recipients.join(Membership).filter(
            Membership.instance_id.in_(filter_instances))
        filter_badges = self.form_result.get('filter_badges')
        if filter_badges:
            recipients = recipients.join(UserBadges,
                                         UserBadges.user_id == User.id)
            recipients = recipients.filter(
                UserBadges.badge_id.in_([fb.id for fb in filter_badges]))

        return func(self,
                    allowed_sender_options[sender]['email'],
                    self.form_result.get('subject'),
                    self.form_result.get('body'),
                    recipients,
                    )
Esempio n. 18
0
    def fix_autojoin(self):
        config_autojoin = config.get('adhocracy.instances.autojoin')
        if not config_autojoin:
            return ret_abort('autojoin is not enabled')

        users = model.User.all()
        instances = model.Instance.all(include_hidden=True)
        added = 0
        if config_autojoin != 'ALL':
            instance_keys = [key.strip() for key in config_autojoin.split(",")]
            instances = [
                instance for instance in instances
                if instance.key in instance_keys
            ]
        for user in users:
            to_join = set(instances)
            for m in user.memberships:
                to_join.discard(m.instance)
            for instance in to_join:
                autojoin_membership = model.Membership(user, instance,
                                                       instance.default_group)
                model.meta.Session.add(autojoin_membership)
                added += 1
        if added > 0:
            model.meta.Session.commit()

        flash(_('Autojoin fixed - added %s memberships.') % added, 'success')
        return redirect(base_url('/admin'))
Esempio n. 19
0
def check_csrf(methods=ALL_METHODS):

    method = request.environ.get('REQUEST_METHOD').upper()
    if method in methods:

        identifier = request.environ.get(
            'repoze.who.identity', {}).get('identifier')
        if (identifier is not None and
                isinstance(identifier, BasicAuthPlugin)):
            return
        if request.params.get(KEY) == token_id():
            return

    from adhocracy.lib.templating import ret_abort
    ret_abort(_("I'm sorry, it looks like we made a mistake "
                "(CSRF alert). Please try again."), code=403)
Esempio n. 20
0
 def revoke(self):
     if not openid_login_allowed():
         ret_abort(_("Removal not allowed, OpenID has been disabled on " "this installation"), code=403)
     require.user.edit(c.user)
     id = request.params.get("id")
     openid = model.OpenID.by_id(id)
     if not openid:
         abort(404, _("No OpenID with ID '%s' exists.") % id)
     page_user = openid.user
     if not (page_user == c.user or can.user.manage()):
         abort(403, _("You're not authorized to change %s's settings.") % id)
     openid.delete()
     model.meta.Session.commit()
     h.flash(_("Successfully removed OpenID from account"), "success")
     log.info("User %s revoked OpenID '%s'" % (c.user.user_name, id))
     redirect(h.entity_url(c.user, member="settings/login"))
Esempio n. 21
0
    def create(self):
        require.user.create()
        if self.email_is_blacklisted(self.form_result['email']):
            return ret_abort(_("Sorry, but we don't accept registrations with "
                               "this email address."), category='error',
                             code=403)

        # SPAM protection recaptcha
        captacha_enabled = config.get('recaptcha.public_key', "")
        if captacha_enabled:
            recaptcha_response = h.recaptcha.submit()
            if not recaptcha_response.is_valid:
                c.recaptcha = h.recaptcha.displayhtml(
                    use_ssl=True,
                    error=recaptcha_response.error_code)
                redirect("/register")
        # SPAM protection hidden input
        input_css = self.form_result.get("input_css")
        input_js = self.form_result.get("input_js")
        if input_css or input_js:
            redirect("/")

        #create user
        user = model.User.create(self.form_result.get("user_name"),
                                 self.form_result.get("email").lower(),
                                 password=self.form_result.get("password"),
                                 locale=c.locale)
        model.meta.Session.commit()

        event.emit(event.T_USER_CREATE, user)
        libmail.send_activation_link(user)

        if c.instance:
            membership = user.instance_membership(c.instance)
            if membership is None:
                membership = model.Membership(user, c.instance,
                                              c.instance.default_group)
                model.meta.Session.expunge(membership)
                model.meta.Session.add(membership)
                model.meta.Session.commit()

        # authenticate the new registered member using the repoze.who
        # api. This is done here and not with an redirect to the login
        # to omit the generic welcome message
        who_api = get_api(request.environ)
        login = self.form_result.get("user_name").encode('utf-8')
        credentials = {
            'login': login,
            'password': self.form_result.get("password").encode('utf-8')}
        authenticated, headers = who_api.login(credentials)
        if authenticated:
            # redirect to dashboard with login message
            session['logged_in'] = True
            session.save()
            location = h.base_url('/user/%s/dashboard' % login)
            raise HTTPFound(location=location, headers=headers)
        else:
            raise Exception('We have added the user to the Database '
                            'but cannot authenticate him: '
                            '%s (%s)' % (credentials['login'], user))
Esempio n. 22
0
def check_csrf(methods=ALL_METHODS):

    method = request.environ.get('REQUEST_METHOD').upper()
    if method in methods:

        identifier = request.environ.get(
            'repoze.who.identity', {}).get('identifier')
        if (identifier is not None and
                isinstance(identifier, BasicAuthPlugin)):
            return
        if request.params.get(KEY) == token_id():
            return

    from adhocracy.lib.templating import ret_abort
    ret_abort(_("I'm sorry, it looks like we made a mistake "
                "(CSRF alert). Please try again."), code=403)
Esempio n. 23
0
    def activity(self, id, format='html'):
        c.page_instance = get_entity_or_abort(model.Instance, id)
        require.instance.show(c.page_instance)

        if format == 'sline':
            ret_abort(u'Sparkline data is not available anymore.', code=410)

        events = model.Event.find_by_instance(c.page_instance, limit=50)

        if format == 'rss':
            return event.rss_feed(events, _('%s News' % c.page_instance.label),
                                  h.base_url(c.page_instance),
                                  _("News from %s") % c.page_instance.label)

        c.tile = tiles.instance.InstanceTile(c.page_instance)
        c.events_pager = pager.events(events)
        return render("/instance/activity.html")
Esempio n. 24
0
    def activity(self, id, format="html"):
        c.page_instance = get_entity_or_abort(model.Instance, id)
        require.instance.show(c.page_instance)

        if format == "sline":
            ret_abort(u"Sparkline data is not available anymore.", code=410)

        events = model.Event.find_by_instance(c.page_instance, limit=50)

        if format == "rss":
            return event.rss_feed(
                events, _("%s News" % c.page_instance.label), h.base_url(), _("News from %s") % c.page_instance.label
            )

        c.tile = tiles.instance.InstanceTile(c.page_instance)
        c.events_pager = pager.events(events)
        return render("/instance/activity.html")
Esempio n. 25
0
 def revoke(self):
     if not openid_login_allowed():
         ret_abort(_("Removal not allowed, OpenID has been disabled on "
                     "this installation"),
                   code=403)
     require.user.edit(c.user)
     id = request.params.get('id')
     openid = model.OpenID.by_id(id)
     if not openid:
         abort(404, _("No OpenID with ID '%s' exists.") % id)
     page_user = openid.user
     if not (page_user == c.user or can.user.manage()):
         abort(403,
               _("You're not authorized to change %s's settings.") % id)
     openid.delete()
     model.meta.Session.commit()
     h.flash(_("Successfully removed OpenID from account"), 'success')
     log.info("User %s revoked OpenID '%s'" % (c.user.user_name, id))
     redirect(h.entity_url(c.user, member='settings/login'))
Esempio n. 26
0
 def import_do(self):
     options = ImportForm().to_python(dict(request.params))
     if not can_welcome() and options['welcome']:
         return ret_abort(_("Requested generation of welcome codes, but "
                            "welcome functionality"
                            "(adhocracy.enable_welcome) is not enabled."),
                          code=403)
     obj = request.POST['importfile']
     options['user_personal'] = True
     adhocracy.lib.importexport.import_(options, obj.file)
     return render('admin/import_success.html', {})
Esempio n. 27
0
def check_csrf(methods=ALL_METHODS):

    method = request.environ.get('REQUEST_METHOD').upper()
    if method in methods:

        identifier = request.environ.get('repoze.who.identity',
                                         {}).get('identifier')
        if (identifier is not None
                and isinstance(identifier, BasicAuthPlugin)):
            return
        if request.params.get(KEY) == token_id():
            return

    from adhocracy.lib.templating import ret_abort
    from adhocracy.lib import helpers as h
    msg = '<p>%s</p><a href="%s">%s</a>' % (
        _(u'The requested action could not be performed, because the session '
          'which was active when you visited the previous page has expired.'),
        h.site.current_url(), _(u'Back to your current session'))
    ret_abort(msg, code=403)
Esempio n. 28
0
 def username(self):
     """
     Called when the nickname proposed by the OpenID identity provider is
     unavailable locally.
     """
     if not openid_login_allowed():
         ret_abort(_("OpenID login has been disabled on this installation"), code=403)
     if "openid_req" in session:
         (openid, c.openid_username, email) = session["openid_req"]
         if request.method == "POST":
             c.user_name = forms.UniqueUsername(not_empty=True).to_python(self.form_result.get("login"))
             if c.user_name:
                 user = self._create(c.user_name, email, openid)
                 del session["openid_req"]
                 self._login(user, register=True)
         else:
             c.user_name = c.openid_username
         return render("/openid/username.html")
     else:
         redirect("/register")
Esempio n. 29
0
def check_csrf(methods=ALL_METHODS):

    method = request.environ.get('REQUEST_METHOD').upper()
    if method in methods:

        identifier = request.environ.get(
            'repoze.who.identity', {}).get('identifier')
        if (identifier is not None and
                isinstance(identifier, BasicAuthPlugin)):
            return
        if request.params.get(KEY) == token_id():
            return

    from adhocracy.lib.templating import ret_abort
    from adhocracy.lib import helpers as h
    msg = '<p>%s</p><a href="%s">%s</a>' % (
        _(u'The requested action could not be performed, because the session '
          'which was active when you visited the previous page has expired.'),
        h.site.current_url(),
        _(u'Back to your current session'))
    ret_abort(msg, code=403)
Esempio n. 30
0
 def username(self):
     """
     Called when the nickname proposed by the OpenID identity provider is
     unavailable locally.
     """
     if not openid_login_allowed():
         ret_abort(_("OpenID login has been disabled on this installation"),
                   code=403)
     if 'openid_req' in session:
         (openid, c.openid_username, email) = session['openid_req']
         if request.method == "POST":
             c.user_name = forms.UniqueUsername(not_empty=True).to_python(
                 self.form_result.get('login'))
             if c.user_name:
                 user = self._create(c.user_name, email, openid)
                 del session['openid_req']
                 self._login(user, register=True)
         else:
             c.user_name = c.openid_username
         return render('/openid/username.html')
     else:
         redirect('/register')
Esempio n. 31
0
    def oembed(self, format=u'json'):
        if 'url' not in request.params:
            return ret_abort(u"Required parameter 'url' is missing", code=400)

        u = urlparse.urlparse(request.params.get('url'))

        # validate input url
        if (u.scheme != config.get('adhocracy.protocol')
                or u.netloc != config.get('adhocracy.domain')):
            return ret_abort(u"URL not supported", code=404)

        # set format to overlay
        path = re.sub('(\.[^./]*)?$', '.overlay', u.path)
        new_url = urlparse.ParseResult(u.scheme, u.netloc, path,
                                       u.params, u.query, u.fragment)
        new_url = urlparse.urlunparse(new_url)

        width = min(640, int(request.params.get('maxwidth', 640)))
        height = int(request.params.get('maxheight', 750))

        html = ('<iframe src="%s" width="%i "height="%i"'
                ' frameborder="0"></iframe>' % (new_url, width, height))

        data = {
            'type': 'rich',
            'version': '1.0',
            'width': width,
            'height': height,
            'html': html,
            'provider_name': config.get('adhocracy.site.name'),
            'provider_url': h.base_url(instance=None, absolute=True),
        }

        if format == u'json':
            return render_json(data)
        else:
            ret_abort(u"The format parameter must be one of: {json}.",
                      code=501)
Esempio n. 32
0
    def oembed(self, format=u'json'):
        if 'url' not in request.params:
            return ret_abort(u"Required parameter 'url' is missing", code=400)

        u = urlparse.urlparse(request.params.get('url'))

        # validate input url
        if (u.scheme != config.get('adhocracy.protocol')
                or u.netloc != config.get('adhocracy.domain')):
            return ret_abort(u"URL not supported", code=404)

        # set format to overlay
        path = re.sub('(\.[^./]*)?$', '.overlay', u.path)
        new_url = urlparse.ParseResult(u.scheme, u.netloc, path, u.params,
                                       u.query, u.fragment)
        new_url = urlparse.urlunparse(new_url)

        width = min(640, int(request.params.get('maxwidth', 640)))
        height = int(request.params.get('maxheight', 750))

        html = ('<iframe src="%s" width="%i "height="%i"'
                ' frameborder="0"></iframe>' % (new_url, width, height))

        data = {
            'type': 'rich',
            'version': '1.0',
            'width': width,
            'height': height,
            'html': html,
            'provider_name': config.get('adhocracy.site.name'),
            'provider_url': h.base_url(instance=None, absolute=True),
        }

        if format == u'json':
            return render_json(data)
        else:
            ret_abort(u"The format parameter must be one of: {json}.",
                      code=501)
Esempio n. 33
0
    def post_auth(self):
        """
        This controller is called after successful Shibboleth authentication.
        It checks whether the authenticated user already exists. If yes, the
        corresponding Adhocracy user is logged in. If no, an intermediate step
        querying the user for additional information is performed and a new
        Adhocracy user is registered.

        In any case the Shibboleth headers are only used once for logging in
        and immediatly removed afterwards. The reason for this design decision
        is that Single-Sign-Off isn't recommended by Shibboleth as it is either
        very complicated or even impossible.

        NOTE: There isn't one clear way on how to deal with user deletion in
        environments with external user management. We now implemented the
        following:
        If a user logs in into a deleted account, this account is undeleted
        on the fly.
        """
        if 'shibboleth' not in allowed_login_types():
            ret_abort(_("Shibboleth authentication not enabled"), code=403)

        persistent_id = self._get_persistent_id()
        if persistent_id is None:
            ret_abort(_("This URL shouldn't be called directly"), code=403)

        user = User.find_by_shibboleth(persistent_id, include_deleted=True)

        if user is not None:
            if user.is_deleted():
                user.undelete()
                meta.Session.commit()
                h.flash(
                    _("User %s has been undeleted") % user.user_name,
                    'success')
            return self._login(user, h.user.post_login_url(user))
        else:
            return self._register(persistent_id)
Esempio n. 34
0
 def edit(self, key, lang, errors=None):
     backend = get_backend()
     sp = backend.get(key, lang)
     if not sp:
         return ret_abort(_('Cannot find static page to edit'), code=404)
     data = {'staticpage': sp}
     defaults = {
         'title': sp.title,
         'body': sp.body,
     }
     defaults.update(dict(request.params))
     defaults['_tok'] = csrf.token_id()
     return htmlfill.render(render('/static/edit.html', data),
                            defaults=defaults, errors=errors)
Esempio n. 35
0
    def purge_history(self, id, format='html'):
        c.comment = get_entity_or_abort(model.Comment, id)

        require.comment.revert(c.comment)
        revision = self.form_result.get('rev')
        if revision.comment != c.comment:
            return ret_abort(_("You're trying to purge a revision which "
                               "is not part of this comment's history"),
                             code=400, format=format)

        model.meta.Session.delete(revision)
        model.meta.Session.commit()
        return ret_success(message=_("The comment revision has been deleted."),
                           entity=c.comment, format=format)
Esempio n. 36
0
 def delete(self, id):
     c.delegation = get_entity_or_abort(model.Delegation, id)
     require.delegation.delete(c.delegation)
     if not c.delegation.principal == c.user:
         return ret_abort(_("Cannot access delegation %(id)s") %
                          {'id': id}, code=403)
     c.delegation.revoke()
     model.meta.Session.commit()
     event.emit(event.T_DELEGATION_REVOKE, c.user,
                topics=[c.delegation.scope],
                scope=c.delegation.scope, instance=c.instance,
                agent=c.delegation.agent)
     return ret_success(message=_("The delegation is now revoked."),
                        entity=c.delegation.scope)
Esempio n. 37
0
    def post_auth(self):
        """
        This controller is called after successful Shibboleth authentication.
        It checks whether the authenticated user already exists. If yes, the
        corresponding Adhocracy user is logged in. If no, an intermediate step
        querying the user for additional information is performed and a new
        Adhocracy user is registered.

        In any case the Shibboleth headers are only used once for logging in
        and immediatly removed afterwards. The reason for this design decision
        is that Single-Sign-Off isn't recommended by Shibboleth as it is either
        very complicated or even impossible.

        NOTE: There isn't one clear way on how to deal with user deletion in
        environments with external user management. We now implemented the
        following:
        If a user logs in into a deleted account, this account is undeleted
        on the fly.
        """
        if 'shibboleth' not in allowed_login_types():
            ret_abort(_("Shibboleth authentication not enabled"), code=403)

        persistent_id = self._get_persistent_id()
        if persistent_id is None:
            ret_abort(_("This URL shouldn't be called directly"), code=403)

        user = User.find_by_shibboleth(persistent_id, include_deleted=True)

        if user is not None:
            if user.is_deleted():
                user.undelete()
                meta.Session.commit()
                h.flash(_("User %s has been undeleted") % user.user_name,
                        'success')
            return self._login(user, h.user.post_login_url(user))
        else:
            return self._register(persistent_id)
Esempio n. 38
0
    def import_do(self):
        try:
            options = ImportForm().to_python(dict(request.params))
        except formencode.Invalid as i:
            return self.import_dialog(errors=i.unpack_errors())

        if not can_welcome() and options['welcome']:
            return ret_abort(_("Requested generation of welcome codes, but "
                               "welcome functionality"
                               "(adhocracy.enable_welcome) is not enabled."),
                             code=403)
        obj = request.POST['importfile']
        options['user_personal'] = True
        adhocracy.lib.importexport.import_(options, obj.file)
        return render('admin/import_success.html', {})
Esempio n. 39
0
    def assign(self, key):
        treatment = model.Treatment.find(key)
        if not treatment:
            return ret_abort(_("Could not find the entity '%s'") % id,
                             code=404)

        if assign_users(treatment):
            model.meta.Session.commit()

            h.flash(_("All users have been assigned to their respective "
                      "treatment badges."), 'success')
        else:
            h.flash(_("All users are already assigned to their respective "
                      "treatment badges."))
        return redirect(h.base_url('/admin/treatment/'))
Esempio n. 40
0
    def update(self, key, lang):
        backend = get_backend()
        sp = backend.get(key, lang)
        if not sp:
            return ret_abort(_('Cannot find static page to edit'), code=404)

        try:
            form_result = EditForm().to_python(request.params)
        except Invalid as i:
            return self.edit(errors=i.unpack_errors())

        sp.title = form_result.get('title')
        sp.body = form_result.get('body')
        sp.commit()
        helpers.flash(_('Page updated'), 'notice')
        return redirect(helpers.base_url('/static/'))
Esempio n. 41
0
 def delete(self, id):
     c.delegation = get_entity_or_abort(model.Delegation, id)
     require.delegation.delete(c.delegation)
     if not c.delegation.principal == c.user:
         return ret_abort(_("Cannot access delegation %(id)s") % {'id': id},
                          code=403)
     c.delegation.revoke()
     model.meta.Session.commit()
     event.emit(event.T_DELEGATION_REVOKE,
                c.user,
                topics=[c.delegation.scope],
                scope=c.delegation.scope,
                instance=c.instance,
                agent=c.delegation.agent)
     return ret_success(message=_("The delegation is now revoked."),
                        entity=c.delegation.scope)
Esempio n. 42
0
File: user.py Progetto: whausen/part
 def new(self):
     if not h.allow_user_registration():
         return ret_abort(
             _("Sorry, registration has been disabled by administrator."),
             category='error', code=403)
     c.active_global_nav = "login"
     if c.user:
         redirect('/')
     else:
         captacha_enabled = config.get('recaptcha.public_key', "")
         c.recaptcha = captacha_enabled and h.recaptcha.displayhtml(
             use_ssl=True)
         session['came_from'] = request.params.get('came_from',
                                                   h.base_url())
         session.save()
         return render("/user/register.html")
Esempio n. 43
0
    def update(self, key, lang):
        backend = get_backend()
        sp = backend.get(key, lang)
        if not sp:
            return ret_abort(_('Cannot find static page to edit'), code=404)

        try:
            form_result = EditForm().to_python(request.params)
        except Invalid as i:
            return self.edit(errors=i.unpack_errors())

        sp.title = form_result.get('title')
        sp.body = form_result.get('body')
        sp.commit()
        helpers.flash(_('Page updated'), 'notice')
        return redirect(helpers.base_url('/static/'))
Esempio n. 44
0
    def purge_history(self, id, format='html'):
        c.comment = get_entity_or_abort(model.Comment, id)

        require.comment.revert(c.comment)
        revision = self.form_result.get('rev')
        if revision.comment != c.comment:
            return ret_abort(_("You're trying to purge a revision which "
                               "is not part of this comment's history"),
                             code=400,
                             format=format)

        model.meta.Session.delete(revision)
        model.meta.Session.commit()
        return ret_success(message=_("The comment revision has been deleted."),
                           entity=c.comment,
                           format=format)
Esempio n. 45
0
 def edit(self, key, lang, errors=None, format=u'html'):
     backend = get_backend()
     sp = backend.get(key, lang)
     if not sp:
         return ret_abort(_('Cannot find static page to edit'), code=404)
     data = {'staticpage': sp}
     defaults = {
         'title': sp.title,
         'body': sp.body,
     }
     defaults.update(dict(request.params))
     defaults['_tok'] = csrf.token_id()
     return htmlfill.render(render('/static/edit.html',
                                   data,
                                   overlay=format == u'overlay'),
                            defaults=defaults,
                            errors=errors)
Esempio n. 46
0
    def fix_autojoin(self):
        config_autojoin = config.get('adhocracy.instances.autojoin')
        if not config_autojoin:
            return ret_abort('autojoin is not enabled')

        users = model.User.all()
        added = 0
        for user in users:
            added += user.fix_autojoin(commit=False)
        if added > 0:
            model.meta.Session.commit()
            flash(
                _('Autojoin fixed - added %s memberships.') % added, 'success')
        else:
            flash(_('No need to fix autojoin.'), 'success')

        return redirect(base_url('/admin'))
Esempio n. 47
0
File: admin.py Progetto: alkadis/vcv
    def fix_autojoin(self):
        config_autojoin = config.get('adhocracy.instances.autojoin')
        if not config_autojoin:
            return ret_abort('autojoin is not enabled')

        users = model.User.all()
        added = 0
        for user in users:
            added += user.fix_autojoin(commit=False)
        if added > 0:
            model.meta.Session.commit()
            flash(_('Autojoin fixed - added %s memberships.') % added,
                  'success')
        else:
            flash(_('No need to fix autojoin.'), 'success')

        return redirect(base_url('/admin'))
Esempio n. 48
0
    def assign(self, key):
        treatment = model.Treatment.find(key)
        if not treatment:
            return ret_abort(_("Could not find the entity '%s'") % id,
                             code=404)

        if assign_users(treatment):
            model.meta.Session.commit()

            h.flash(
                _("All users have been assigned to their respective "
                  "treatment badges."), 'success')
        else:
            h.flash(
                _("All users are already assigned to their respective "
                  "treatment badges."))
        return redirect(h.base_url('/admin/treatment/'))
Esempio n. 49
0
    def assigned(self, key):
        treatment = model.Treatment.find(key)
        if not treatment:
            return ret_abort(_("Could not find the entity '%s'") % id,
                             code=404)

        assignments = [{
            'source_badge': source_badge,
            'variants': current_assignment,
        } for source_badge, current_assignment, unassigned in (
            get_assignments_by_source_badge(treatment))]

        data = {
            'assignments': assignments,
            'treatment': treatment,
        }
        return render('treatment/assigned.html', data)
Esempio n. 50
0
 def revert(self, id, format='html'):
     c.comment = get_entity_or_abort(model.Comment, id)
     require.comment.revert(c.comment)
     revision = self.form_result.get('to')
     if revision.comment != c.comment:
         return ret_abort(_("You're trying to revert to a revision which "
                            "is not partri of this comments history"),
                          code=400, format=format)
     rev = c.comment.create_revision(revision.text,
                                     c.user,
                                     sentiment=revision.sentiment)
     model.meta.Session.commit()
     event.emit(event.T_COMMENT_EDIT, c.user, instance=c.instance,
                topics=[c.comment.topic], comment=c.comment,
                topic=c.comment.topic, rev=rev)
     return ret_success(message=_("The comment has been reverted."),
                        entity=c.comment, format=format)
Esempio n. 51
0
    def wrapper(self):
        allowed_sender_options = self._get_allowed_sender_options(c.user)
        sender_email = self.form_result.get('sender_email')
        if ((sender_email not in allowed_sender_options)
                or (not allowed_sender_options[sender_email]['enabled'])):
            return ret_abort(_("Sorry, but you're not allowed to set these "
                               "message options"),
                             code=403)
        sender_name = None
        if has('global.message'):
            sender_name = self.form_result.get('sender_name')
        if not sender_name:
            sender_name = c.user.name

        recipients = User.all_q()
        filter_instances = self.form_result.get('filter_instances')
        recipients = recipients.join(Membership).filter(
            Membership.instance_id.in_(filter_instances))
        filter_badges = self.form_result.get('filter_badges')
        if filter_badges:
            recipients = recipients.join(UserBadges,
                                         UserBadges.user_id == User.id)
            recipients = recipients.filter(
                UserBadges.badge_id.in_([fb.id for fb in filter_badges]))

        if has('global.admin'):
            include_footer = self.form_result.get('include_footer')
        else:
            include_footer = True

        if len(filter_instances) == 1:
            instance = Instance.find(filter_instances[0])
        else:
            instance = None

        return func(
            self,
            self.form_result.get('subject'),
            self.form_result.get('body'),
            recipients.all(),
            sender_email=allowed_sender_options[sender_email]['email'],
            sender_name=sender_name,
            instance=instance,
            include_footer=include_footer,
        )
Esempio n. 52
0
    def wrapper(self):
        allowed_sender_options = self._get_allowed_sender_options(c.user)
        sender_email = self.form_result.get('sender_email')
        if ((sender_email not in allowed_sender_options) or
                (not allowed_sender_options[sender_email]['enabled'])):
            return ret_abort(_("Sorry, but you're not allowed to set these "
                               "message options"), code=403)
        sender_name = None
        if has('global.message'):
            sender_name = self.form_result.get('sender_name')
        if not sender_name:
            sender_name = c.user.name

        recipients = User.all_q()
        filter_instances = self.form_result.get('filter_instances')
        recipients = recipients.join(Membership).filter(
            Membership.instance_id.in_(filter_instances))
        filter_badges = self.form_result.get('filter_badges')
        if filter_badges:
            recipients = recipients.join(UserBadges,
                                         UserBadges.user_id == User.id)
            recipients = recipients.filter(
                UserBadges.badge_id.in_([fb.id for fb in filter_badges]))

        if has('global.admin'):
            include_footer = self.form_result.get('include_footer')
        else:
            include_footer = True

        if len(filter_instances) == 1:
            instance = Instance.find(filter_instances[0])
        else:
            instance = None

        return func(self,
                    self.form_result.get('subject'),
                    self.form_result.get('body'),
                    recipients.all(),
                    sender_email=allowed_sender_options[sender_email]['email'],
                    sender_name=sender_name,
                    instance=instance,
                    include_footer=include_footer,
                    )
Esempio n. 53
0
    def assigned(self, key):
        treatment = model.Treatment.find(key)
        if not treatment:
            return ret_abort(_("Could not find the entity '%s'") % id,
                             code=404)

        assignments = [
            {
                'source_badge': source_badge,
                'variants': current_assignment,
            }
            for source_badge, current_assignment, unassigned in (
                get_assignments_by_source_badge(treatment))]

        data = {
            'assignments': assignments,
            'treatment': treatment,
        }
        return render('treatment/assigned.html', data)
Esempio n. 54
0
    def import_do(self):
        try:
            options = ImportForm().to_python(dict(request.params))
        except formencode.Invalid as i:
            return self.import_dialog(errors=i.unpack_errors())

        if not can_welcome() and options["welcome"]:
            return ret_abort(
                _(
                    "Requested generation of welcome codes, but "
                    "welcome functionality"
                    "(adhocracy.enable_welcome) is not enabled."
                ),
                code=403,
            )
        obj = request.POST["importfile"]
        options["user_personal"] = True
        adhocracy.lib.importexport.import_(options, obj.file)
        return render("admin/import_success.html", {})
Esempio n. 55
0
 def bad_request(self, format='html'):
     log.debug("400 Request: %s" % request.params)
     return ret_abort(_("Invalid request. Please go back and try again."),
                      code=400,
                      format=format)
Esempio n. 56
0
 def not_implemented(self, format='html'):
     return ret_abort(_("The method you used is not implemented."),
                      code=400,
                      format=format)
Esempio n. 57
0
class CommentController(BaseController):

    @RequireInstance
    def index(self, format='html'):
        require.comment.index()
        comments = model.Comment.all()
        c.comments_pager = NamedPager(
            'comments', comments, tiles.comment.row, count=10,
            sorts={_("oldest"): sorting.entity_oldest,
                   _("newest"): sorting.entity_newest},
            default_sort=sorting.entity_newest)
        if format == 'json':
            return render_json(c.comments_pager)

        return self.not_implemented(format=format)

    @RequireInstance
    @validate(schema=CommentNewForm(), form="bad_request",
              post_only=False, on_get=True)
    def new(self, errors=None):
        c.topic = self.form_result.get('topic')
        c.reply = self.form_result.get('reply')
        c.wiki = self.form_result.get('wiki')
        c.variant = self.form_result.get('variant')
        defaults = dict(request.params)
        if c.reply:
            require.comment.reply(c.reply)
        else:
            require.comment.create_on(c.topic)
        return htmlfill.render(render('/comment/new.html'), defaults=defaults,
                               errors=errors, force_defaults=False)

    @RequireInstance
    @csrf.RequireInternalRequest(methods=['POST'])
    def create(self, format='html'):
        require.comment.create()
        try:
            self.form_result = CommentCreateForm().to_python(request.params)
        except Invalid, i:
            return self.new(errors=i.unpack_errors())

        topic = self.form_result.get('topic')
        reply = self.form_result.get('reply')

        if reply:
            require.comment.reply(reply)
        else:
            require.comment.create_on(topic)

        variant = self.form_result.get('variant')
        if hasattr(topic, 'variants') and not variant in topic.variants:
            return ret_abort(_("Comment topic has no variant %s") % variant,
                             code=400)

        comment = model.Comment.create(
            self.form_result.get('text'),
            c.user, topic,
            reply=reply,
            wiki=self.form_result.get('wiki'),
            variant=variant,
            sentiment=self.form_result.get('sentiment'),
            with_vote=can.user.vote())

        # watch comments by default!
        model.Watch.create(c.user, comment)
        model.meta.Session.commit()
        #watchlist.check_watch(comment)
        event.emit(event.T_COMMENT_CREATE, c.user, instance=c.instance,
                   topics=[topic], comment=comment, topic=topic,
                   rev=comment.latest)
        if len(request.params.get('ret_url', '')):
            redirect(request.params.get('ret_url') + "#c" + str(comment.id))
        if format != 'html':
            return ret_success(entity=comment, format=format)
        return ret_success(entity=comment, format='fwd')