Beispiel #1
0
 def get(self, id):
     try:
         id = int(id)
         u = User.get(id)
         if id != self.session['user'][
                 'id'] and UserPermissions.administrator not in User.get(
                     self.session['user']['id']).highest_permission_level:
             resp.forbidden()
         return self.render_page(u)
     except (SQLObjectNotFound, ValueError):
         resp.seeother('/users')
Beispiel #2
0
 def decorated_function(*args, **kwargs):
     app = flask.current_app
     if 'user' in app.session:
         u = User.get(app.session['user']['id'])
         if 'real_user' in app.session:
             real_user = User.get(app.session['real_user']['id'])
             # if the real user has at least the same right as the "logged as" user
             if u.highest_permission_level not in real_user.highest_permission_level:
                 resp.seeother('/logas/nobody')
         if permission_level in u.highest_permission_level:
             return f(*args, **kwargs)
         resp.forbidden()
Beispiel #3
0
 def render_page(self):
     current_user = User.get(self.session['user']['id'])
     plugin_dirs = self.plugin_manager.list_plugins()
     plugins = Plugin.update_plugins(plugin_dirs)
     return self.renderer.plugins(plugins=plugins,
                                  missing_dependencies=self.plugin_manager.missing_dependencies,
                                  current_user=current_user)
Beispiel #4
0
    def render_page(self, channel):
        current_user = User.get(self.session['user']['id'])

        now = datetime.now()
        last_update = self.plugin_manager.get_last_update(channel.id) or now
        if type(channel) is PluginChannel and last_update + timedelta(
                minutes=channel.cache_validity) < now:
            last_update = now
        try:
            vertical = channel.get_config_param(
                'vertical') if type(channel) is PluginChannel else False
        except KeyError:
            vertical = False
        return self.renderer.channeld(
            channel=channel,
            channel_type=type(channel).__name__,
            current_user=current_user,
            bundles=ChannelBundle.select().filter(
                ChannelBundle.q.id != channel.id),
            can_force_update=UserPermissions.administrator
            in current_user.highest_permission_level
            or (type(channel) is PluginChannel
                and channel.has_contrib(current_user)),
            last_update=last_update,
            vertical=vertical)
Beispiel #5
0
 def _send_email(self, user_id):
     self._lock.acquire()
     if user_id in self._digest:
         user_email = User.get(user_id).email
         try:
             web.sendmail(web.config.smtp_sendername, user_email,
                          self._subject, self._digest[user_id])
             del self._digest[user_id]
             del self._digest_hashes[user_id]
             self._last_email[user_id] = datetime.now()
             self._s.enter(self._interval.total_seconds(),
                           1,
                           self._send_email,
                           kwargs={'user_id': user_id})
             self._logger.debug(
                 'Next email batch will be in %d seconds for user %s' %
                 (self._interval.total_seconds(), user_email))
         except smtplib.SMTPException:
             self._logger.error(
                 'An error occured when sending email to %s' % user_email,
                 exc_info=True)
     else:
         del self._last_email[
             user_id]  # An email can be sent at any moment in the future
     self._lock.release()
Beispiel #6
0
 def render_page(self, channel):
     """ Render this page. """
     templates = sorted([(template, Templates[template]['name'])
                         for template in Templates])
     readable_params = []
     writable_params = []
     current_user = User.get(self.session['user']['id'])
     for param_id, param_attrs in sorted(
             channel.plugin.channels_params.items(),
             key=lambda x: x[1]['order']):
         read, write = channel.get_access_rights_for(param_id, current_user)
         if not write and read:
             readable_params.append((param_id, param_attrs))
         elif read and write:
             writable_params.append((param_id, param_attrs))
     readable_params, writable_params = self.get_params(
         channel, current_user)
     is_admin = current_user.super_admin or channel.has_admin(
         self.session['user']['id'])
     return self.renderer.channel(
         channel=channel,
         templates=templates,
         readable_params=readable_params,
         writable_params=writable_params,
         can_modify_cache=current_user.super_admin,
         can_modify_capsule_filter=current_user.super_admin,
         pattern=re.compile(r"list\[.*\]"))
Beispiel #7
0
 def get(self, bundle_id):
     try:
         bundle = ChannelBundle.get(bundle_id)
         u = User.get(self.session['user']['id'])
     except SQLObjectNotFound:
         resp.notfound()
     return self.render_page(bundle, u)
Beispiel #8
0
    def post(self):
        """ Handles building creation, editing and deletion. """
        current_user = User.get(self.session['user']['id'])
        form = self.form
        try:
            if form.action == 'delete':
                if not current_user.super_admin:
                    raise flask.redirect('',code=403)
                try:
                    id = int(form.id)
                except ValueError:
                    logger.warning('user %s tries to delete a building with invalid id (id = %s)', current_user.log_name, str(form.id))
                    raise ImmediateFeedback(form.action, 'invalid_id')
                try:
                    screens = Screen.selectBy(building=id)
                    if screens.count() > 0:
                        logger.warning('user %s tries to delete a building with screens still present in this building (id = %s)', current_user.log_name, str(id))
                        raise ImmediateFeedback(form.action, 'delete_building_but_screens_present', [(s.id, s.name) for s in screens])
                    Building.delete(id)
                    logger.info("building %s has been deleted by user %s", str(id), current_user.log_name)
                except SQLObjectNotFound as e:
                    logger.warning("user %s tries to delete a building with an id that doesn't exist (id = %s)", current_user.log_name, str(form.id))
                    raise ImmediateFeedback(form.action, 'no_id_matching')
            else:
                name = form.name.strip()
                if name == "":
                    raise ImmediateFeedback(form.action, 'empty_name')
                if len(form.name) > Building.sqlmeta.columns['name'].length:
                    raise ImmediateFeedback(form.action, 'too_long_name')
                if form.action == 'create':
                    try:
                        Building(name=form.name, city=form.city)
                        logger.info("building %s has been created by user %s", form.name, current_user.log_name)
                    except DuplicateEntryError:
                        logger.warning("user %s tries to create a building with a name that already exists (name = %s)", current_user.log_name, form.name)
                        raise ImmediateFeedback(form.action, 'name_already_exists')
                elif form.action == 'edit':
                    try:
                        id = int(form.id)
                    except ValueError:
                        logger.warning('user %s tries to edit a building with invalid id (id = %s)', current_user.log_name, str(form.id))
                        raise ImmediateFeedback(form.action, 'invalid_building_id')
                    try:
                        building = Building.get(id)
                    except SQLObjectNotFound as e:
                        logger.warning("user %s tries to edit a building with an id that doesn't exist (id = %s)", current_user.log_name, str(form.id))
                        raise ImmediateFeedback(form.action, 'no_id_matching')
                    try:
                        building.name = form.name
                        building.city = form.city
                    except DuplicateEntryError:
                        logger.warning("user %s tries to edit the building %s with a name already present (name = %d)", current_user.log_name, str(form.id), form.name)
                        raise ImmediateFeedback(form.action, 'name_already_exists')

                    logger.info("building %s has been edited by user %s (new name = %s)", str(id), current_user.log_name, form.name)
            add_feedback(form.action, 'ok')
        except ImmediateFeedback:
            store_form(form)
        return self.render_page()
Beispiel #9
0
 def can_subscribe(self, usr):
     """ Return whether this user has sufficient permission to be able to subscribe to this channel or not. """
     if isinstance(usr, dict):
         # Retreive User instance when called from template
         user = User.get(usr["id"])
     else:
         user = usr
     return self.subscription_right == 'public' or UserPermissions.administrator in user.highest_permission_level or user in self.authorized_subscribers
Beispiel #10
0
 def get(self, secret):
     user = User.selectBy(reset_secret=secret).getOne(None)
     if not user:
         logger.warning('IP %s tried to access password reset page with invalid secret', flask.request.remote_addr)
         if 'user' in self.session:
             logger.warning('User %s is currently connected', User.get(self.session['user']['id']).log_name)
         resp.seeother('/')
     return self.standalone_renderer.reset(user=user)
Beispiel #11
0
 def post(self, channel_id, channel):
     """ Handles channel creation, editing, deletion, configuration and user permissions. """
     form = self.form
     current_user = User.get(self.session['user']['id'])
     try:
         if form.action == 'reset-config':
             if form.all == "true":
                 for param_id, param_attrs in channel.plugin.channels_params.items(
                 ):
                     read, write = channel.get_access_rights_for(
                         param_id, current_user)
                     if read and write:
                         channel.plugin_config.pop(param_id, None)
                         # Force SQLObject update
                         channel.plugin_config = channel.plugin_config
             else:
                 param_id = form["reset-param-id"]
                 if param_id not in channel.plugin.channels_params.keys():
                     raise ImmediateFeedback(form.action,
                                             "invalid_param_id")
                 read, write = channel.get_access_rights_for(
                     param_id, current_user)
                 if read and write:
                     channel.plugin_config.pop(param_id, None)
                 else:
                     raise self.forbidden()
                 # Force SQLObject update
                 channel.plugin_config = channel.plugin_config
                 channel.syncUpdate()
             logger.info('params of channel ' + channel.name +
                         ' reset by ' + current_user.log_name)
         elif form.action == 'reset-cache-config':
             if not current_user.super_admin:
                 raise self.forbidden()
             form.name = channel.name
             channel.cache_activated = None
             channel.cache_validity = None
             add_feedback('general', 'channel_cache_reset')
             logger.info(
                 'the cache configuration of channel %s has been reset by user %s',
                 channel.name, current_user.log_name)
         elif form.action == 'reset-filtering-config':
             if not current_user.super_admin:
                 raise self.forbidden()
             form.name = channel.name
             channel.keep_noncomplying_capsules = None
             add_feedback('general', 'channel_filtering_reset')
             logger.info(
                 'the capsule filtering configuration of channel %s has been reset by user %s',
                 channel.name, current_user.log_name)
         add_feedback('general', 'channel_edited')
         add_feedback(form.action, 'ok')
         form.name = channel.name
     except ImmediateFeedback:
         if channel is not None and channel.enabled:
             form.enabled = 'on'
     store_form(form)
     resp.seeother('/channels/config/%d' % channel.id)
Beispiel #12
0
    def post(self):
        """ Handles plugin editing and activation. """
        form = self.form
        try:
            if form.action == 'check_dependencies':
                self.plugin_manager.check_all_plugins_dependencies()
            else:
                plugin_id = int(form.id)
                p = Plugin.get(plugin_id)
                current_user = User.get(self.session['user']['id'])
                if form.action == 'edit':
                    state = 'yes' if 'state' in form and form.state == 'on' else 'no'
                    try:
                        form.name = p.name
                        if p.activated == 'notfound':
                            raise ImmediateFeedback('general', 'plugin_activate_not_found')
                        p.set(activated=state)
                        if p.activated == 'yes':
                            if self.plugin_manager.instantiate_plugin(self.app, p):
                                add_feedback('general', 'plugin_activated')
                            else:
                                raise ImmediateFeedback('general', 'plugin_activation_error')
                        else:
                            add_feedback('general', 'plugin_disabled')
                    except (SQLObjectNotFound, ValueError):
                        raise ImmediateFeedback(form.action, 'invalid_id')
                elif form.action == 'configure':
                    try:
                        for param in p.params_access_rights:
                            param.channel_contributor_read = form.get(param.name + '-cc-r') == 'on'
                            param.channel_contributor_write = form.get(param.name + '-cc-w') == 'on'
                            param.channel_administrator_read = form.get(param.name + '-ca-r') == 'on'
                            param.channel_administrator_write = form.get(param.name + '-ca-w') == 'on'
                            param.administrator_write = form.get(param.name + '-a-r') == 'on'
                            param.administrator_write = form.get(param.name + '-a-w') == 'on'

                        p.cache_activated_default = form.get('cache-activated') == 'on'
                        if 'cache-validity' in form:
                            p.cache_validity_default = int(form['cache-validity'])
                        p.keep_noncomplying_capsules_default = form.get('keep-capsules') == 'on'
                        p.drop_silently_non_complying_slides_default = form.get('drop-silently') == 'on'
                        form.name = p.name
                        add_feedback('general', 'plugin_configured')
                    except (SQLObjectNotFound, ValueError):
                        raise ImmediateFeedback(form.action, 'invalid_id')
                elif form.action == 'delete':
                    if p.channels.count() > 0 and 'confirm-delete' not in form:
                        raise ImmediateFeedback(form.action, 'plugin_has_channels', {'plugin': p.to_dictionary(['id', 'name', 'channels_number', 'screens_number']),
                                                                        'channels': [(c.id, c.name, c.enabled) for c in p.channels]})
                    plugin_name = p.name
                    form.name = plugin_name
                    p.destroySelf()
                    logger.info('The plugin %s has been deleted by %s', plugin_name, current_user.log_name)
                    add_feedback('general', 'plugin_deleted')
        except ImmediateFeedback:
            pass
        store_form(form)
        return self.render_page()
Beispiel #13
0
 def get(self, screen_id):
     try:
         screen = Screen.get(screen_id)
         u = User.get(self.session['user']['id'])
         if not (UserPermissions.administrator in u.highest_permission_level or screen in u.screens):
             resp.forbidden()
     except SQLObjectNotFound:
         resp.notfound()
     return self.render_page(screen, u)
Beispiel #14
0
 def wrapper(*args, **kwargs):
     app = flask.current_app
     if len(flask.g.homepath)>0: # we are in a sub-app
         channelid = re.findall(r'\d+', flask.g.homepath)[0]
     else:
         channelid = re.findall(r'\d+', flask.request.path)[0]
     channel = PluginChannel.get(channelid)
     u = User.get(app.session['user']['id'])
     if 'real_user' in app.session:
         real_user = User.get(app.session['real_user']['id'])
         # if the real user has at least the same right as the "logged as" user
         if u.highest_permission_level not in real_user.highest_permission_level:
             resp.seeother('/logas/nobody')
     if UserPermissions.administrator in u.highest_permission_level or permission_level in channel.get_channel_permissions_of(u):
         kwargs['channel'] = channel
         return func(*args, **kwargs)
     else:
         resp.forbidden()
Beispiel #15
0
 def wrapper(*args, **kwargs):
     app = web.ctx.app_stack[0]
     if len(web.ctx.homepath) > 0:  # We are in a sub-app
         channelid = re.findall(r'\d+', web.ctx.homepath)[0]
     else:  # We are in the core app
         channelid = re.findall(r'\d+', web.ctx.path)[0]
     channel = PluginChannel.get(channelid)
     u = User.get(app.session['user']['id'])
     if 'real_user' in app.session:
         real_user = User.get(app.session['real_user']['id'])
         # if the real user has at least the same right as the "logged as" user
         if u.highest_permission_level not in real_user.highest_permission_level:
             raise web.seeother('/logas/nobody')
     if UserPermissions.administrator in u.highest_permission_level or permission_level in channel.get_channel_permissions_of(
             u):
         kwargs['channel'] = channel
         return func(*args, **kwargs)
     else:
         raise web.forbidden()
Beispiel #16
0
 def GET(self, secret):
     user = User.selectBy(reset_secret=secret).getOne(None)
     if not user:
         logger.warning(
             'IP %s tried to access password reset page with invalid secret',
             web.ctx.ip)
         if 'user' in self.session:
             logger.warning('User %s is currently connected',
                            User.get(self.session['user']['id']).log_name)
         raise web.redirect('/')
     return self.standalone_renderer.reset(user=user)
Beispiel #17
0
    def decorated_function(*args, **kwargs):
        app = flask.current_app
        app.session = flask.session

        if 'user' in app.session and 'sidebar' not in app.session:
            try:
                u = User.get(app.session['user']['id'])
                if 'real_user' in app.session:
                    real_user = User.get(app.session['real_user']['id'])
                    # if the real user has at least the same right as the "logged as" user
                    if u.highest_permission_level not in real_user.highest_permission_level:
                        resp.seeother('/logas/nobody')
                user_sidebar = {}
                for class_name in get_classes_from_user(u):
                    e = sidebar_elements[class_name]
                    user_sidebar[e['name']] = {'url': urls[urls.index(class_name) - 1], 'icon': e['icon']}
                    app.session['sidebar'] = sorted(user_sidebar.items())
            except SQLObjectNotFound:
                return f(*args, **kwargs)
        return f(*args, **kwargs)
Beispiel #18
0
 def render_page(self):
     u = User.get(self.session['user']['id'])
     screen_status_validity = datetime.now() - timedelta(hours=1)
     return self.renderer.screens(
         screens=Screen.get_visible_screens_of(u),
         buildings=Building.select(),
         user=u,
         users=User.select(),
         channels=Channel.get_screens_channels_from(user=u),
         subscriptions=u.get_subscriptions_of_owned_screens(),
         screen_status_validity=screen_status_validity,
         max_inactivity_period=timedelta(weeks=4))
Beispiel #19
0
    def get(self, id, user_id):
        channel_id = int(id)
        chan = Channel.get(channel_id)
        user_id = int(user_id)
        user = User.get(user_id)

        st = "You just receive a request of subscription for channel " + chan.name + ". Could you please subscribe " + str(
            user.fullname) + " (" + user.email + ") to this channel."
        for admin in chan.get_admins():
            web.sendmail(web.config.smtp_sendername,
                         admin.email,
                         'Request for subscription to a channel',
                         st,
                         headers={'Content-Type': 'text/html;charset=utf-8'})
        resp.seeother('/channels')
Beispiel #20
0
 def get(self, channel_id):
     channel = Channel.get(channel_id)
     current_user = User.get(self.session['user']['id'])
     screens_of_current_user = Screen.get_visible_screens_of(current_user)
     subscriptions = current_user.get_subscriptions_of_owned_screens()
     last_by = {
         sub.screen.id: {
             'user': sub.created_by.readable_name,
             'channel_name': sub.channel.name,
             'plugin_channel': hasattr(sub.channel, 'plugin')
         }
         for sub in subscriptions if sub.channel.id == channel.id
     }
     screen_names = {s.id: s.name for s in screens_of_current_user}
     return self.renderer.channel_subscriptions(
         channel=channel,
         possible_screens=screens_of_current_user,
         user=current_user,
         subscriptions=subscriptions,
         last_by=last_by,
         screen_names=screen_names)
Beispiel #21
0
    def GET(self, channel):
        current_user = User.get(self.session['user']['id'])
        readable_params, writable_params = ChannelPage.get_params(
            channel, current_user)

        rss = '<\s*div\s+class\s*=\s*\"\s*box-body\s*\"\s*>((.|\n)*)<\s*hr\s*\/>\s*<\s*\/div\s*>\s*<\s*div\s+class\s*=\s*\"\s*box-footer\s*\"\s*>'
        config_page = self.renderer.channel(channel=channel,
                                            templates=sorted([
                                                (template,
                                                 Templates[template]['name'])
                                                for template in Templates
                                            ]),
                                            readable_params=readable_params,
                                            writable_params=writable_params,
                                            can_modify_cache=False,
                                            can_modify_capsule_filter=False)

        config_page = re.findall(rss, str(config_page))[0][0]

        return self.rss_renderer.index(channel=channel,
                                       config_content=config_page)
Beispiel #22
0
    def render_page(self):
        u = User.get(self.session['user']['id'])
        screen_status_validity = datetime.now() - timedelta(hours=1)

        def get_data_edit_object(screen):
            object = screen.to_dictionary(['name', 'comment', 'location'])
            object['screenid'] = screen.id
            object['mac'] = screen.get_macs_string(
            ) if screen.macs is not None else ''
            object['building-name'] = screen.building.name
            return json.dumps(object)

        return self.renderer.screens(
            screens=Screen.get_visible_screens_of(u),
            buildings=Building.select(),
            user=u,
            highest_permission_level=u.highest_permission_level,
            users=User.select(),
            channels=Channel.get_screens_channels_from(user=u),
            subscriptions=u.get_subscriptions_of_owned_screens(),
            screen_status_validity=screen_status_validity,
            max_inactivity_period=timedelta(weeks=4),
            get_data_edit_object=get_data_edit_object)
Beispiel #23
0
    def render_page(self, current_user=None, users=None):
        if current_user is None:
            current_user = User.get(self.session['user']['id'])
        if UserPermissions.channel_administrator in current_user.highest_permission_level:
            users = User.select()

        channels = list(Channel.get_visible_channels_of(current_user))

        plugin_channels = []
        bundles = []

        for channel in channels:
            if type(channel) is PluginChannel:
                plugin_channels.append(channel)
            elif type(channel) is ChannelBundle:
                bundles.append(channel)

        return self.renderer.channels(
            plugin_channels=plugin_channels,
            bundles=bundles,
            current_user=current_user,
            users=users,
            activated_plugins=Plugin.selectBy(activated='yes'),
            found_plugins=Plugin.select(NOT(Plugin.q.activated == 'notfound')))
Beispiel #24
0
    def runTest(self):
        """ Tests the Channel object. """
        try:
            PluginChannel(name='test',
                          plugin=Plugin(name='channel_plugin', activated='no'),
                          subscription_right='restricted')
            PluginChannel(
                name='test2',
                plugin=Plugin.selectBy(name='channel_plugin').getOne(),
                subscription_right='restricted')
            c = PluginChannel.selectBy(name="test").getOne()
            assert_not_equal(None, c)
            c.set(name="testNew")
            assert_equal(c.name, "testNew")
            u = User(username='******',
                     fullname='test test',
                     email='*****@*****.**',
                     super_admin=True,
                     disabled=False)
            up = UserPermissions.channel_contributor
            c.give_permission_to_user(u, up)
            role = Role.selectBy(user=u, channel=c).getOne(None)
            assert_true(role != None)
            c.give_permission_to_user(u, up)
            role = Role.selectBy(user=u, channel=c).getOne(None)
            assert_true(role != None)
            getup = c.get_channel_permissions_of(u)
            assert_equal(getup, up)
            getupnoperm = c.get_channel_permissions_of(User.get(1))
            assert_equal(getupnoperm, UserPermissions.no_permission)
            c.remove_permission_to_user(u)
            role = Role.selectBy(user=u, channel=c).getOne(None)
            assert_true(role == None)
            assert_false(c.has_admin(u))
            up = UserPermissions.channel_administrator
            c.give_permission_to_user(u, up)
            assert_true(c.has_admin(u))
            assert_true(c.has_contrib(u))
            assert_is_not_none(c.get_admins())
            assert_is_not_none(c.get_contribs())
            assert_in(str(u.id), c.get_users_as_json())
            c.remove_permission_to_user(u)
            role = Role.selectBy(user=u, channel=c).getOne(None)
            assert_true(role == None)
            c.give_permission_to_user(None, up)
            role = Role.selectBy(user=u).getOne(None)
            assert_true(role == None)
            tru = c.has_visible_params_for(u)
            assert_true(tru)
            u3 = User(username='******',
                      fullname='test3 test2',
                      email='*****@*****.**',
                      super_admin=False,
                      disabled=False)
            tru = c.has_visible_params_for(u3)
            assert_false(tru)
            t = PluginChannel.delete(c.id)
            assert_equal(t, None)
            # try to delete a channel used by a screen - Seems to work...
            sc = Screen(name='A', building=Building(name='A'))
            sc.subscribe_to(u, PluginChannel.get(2))
            # t2 = PluginChannel.delete(2)
            c4 = PluginChannel.get(2)
            nbSub = c4.subscriptions.count()
            c4.set(enabled=False)
            assert_equal(nbSub, c4.subscriptions.count())
            c4.set(enabled=True)
            c4.set(subscription_right="private")
            assert_equal(nbSub, c4.subscriptions.count())
            c4.set(subscription_right="public")
            # todo seems working by bypassing the webinterface
            c4.set(cache_validity=-10)
            assert_true(c4.cache_validity < 0)
            sc.unsubscribe_from(u, PluginChannel.get(2))
            u2 = User(username='******',
                      fullname='test2 test2',
                      email='*****@*****.**',
                      super_admin=False,
                      disabled=False)
            l = PluginChannel.get_screens_channels_from(u2)
            assert_is_not_none(l)
            temp = PluginChannel.get_visible_channels_of(u2)
            assert_is_not_none(temp)
            User.delete(u.id)
            User.delete(u2.id)
            User.delete(u3.id)
        except DuplicateEntryError:
            assert_true(False)

        return
Beispiel #25
0
 def post(self, status):
     User.get(self.session['user']['id']).has_toured = status == 'ended'
     resp.seeother(flask.request.environ.get('HTTP_REFERER', '/'))
Beispiel #26
0
 def post(self, screen_id):
     def wrong_channel(channel, subscribe, user):
         """ returns True if the the user wants to subscribe to the channel while its plugin is not activated or if
             the user tries to subscribe to the channel without being in its authorized subscribers"""
         return subscribe and (type(channel) is PluginChannel and channel.plugin.activated != "yes" or (subscribe and not channel.can_subscribe(user)))
     form = self.form
     try:
         screen = Screen.get(screen_id)
         u = User.get(self.session['user']['id'])
         # Forbid if not admin or does not own this screen
         if not (UserPermissions.administrator in u.highest_permission_level or screen in u.screens):
             logger.warning('user %s tried change subscriptions of screen %d without having the rights to do this',
                            u.log_name, screen.id)
             resp.forbidden()
         diff = json.loads(form.diff)
         if diff == {}:
             logger.info('user %s submitted empty diff for subscriptions of screen %s', u.log_name, screen.name)
             raise ImmediateFeedback("subscription", 'nothing_changed')
         # Do the subscription/unsubscription for every channel in the diff
         subscribed = []
         unsubscribed = []
         try:
             changes = [(Channel.get(channel_id), subscribe) for channel_id, subscribe in diff.items()]
         except SQLObjectNotFound:
             logger.warning('user %s tried to subscribe/unsubscribe screen %d to a channel which does not exist',
                            u.log_name, screen.id)
             resp.forbidden()
         # if somebody tries to subscribe to a channel with a disabled plugin
         wrong_channels = [(channel, subscribe) for channel, subscribe in changes if wrong_channel(channel, subscribe, u)]
         if wrong_channels:
             channel, subscribe = wrong_channels[0]
             if channel.plugin.activated != "yes":
                 logger.warning('user %s tried to %s screen %d to channel %d with disabled plugin',
                                u.log_name, 'subscribe' if subscribe else "unsubscribe", screen.id, channel.id)
                 raise ImmediateFeedback("subscription", "disabled_plugin")
             else:
                 logger.warning('user %s tried to subscribe screen %d to channel %d without having the right to do this',
                                u.log_name, screen.id, channel.id)
                 resp.forbidden()
         for channel, subscribe in changes:
             if subscribe:
                 screen.subscribe_to(u, channel)
                 subscribed.append(str(channel.id))
             else:
                 screen.unsubscribe_from(u, channel)
                 unsubscribed.append(str(channel.id))
         if subscribed and unsubscribed:
             message = "user %s has subscribed screen %d to channel(s) %s and unsubscribed from channel(s) %s" % \
                       (u.log_name, screen.id, ', '.join(subscribed), ', '.join(unsubscribed))
         else:
             message = "user %s has %s screen %d to channel(s) %s" % \
                       (u.log_name, "subscribed" if subscribed else "unsubscribed", screen.id,
                        ', '.join(subscribed if subscribed else unsubscribed))
         logger.info(message)
         add_feedback("subscription", 'ok')
     except SQLObjectNotFound:
         resp.notfound()
     except ImmediateFeedback:
         pass
     store_form(form)
     resp.seeother("/screens/%s/subscriptions" % screen.id)
Beispiel #27
0
 def local_login(self):
     self.testApp.get('/login')
     self.testApp.get('/reset', status=303)
     u = User.get(1)
     r = self.testApp.get('/reset/' + u.reset_secret, status=200)
     assert_not_equal(r.body, None)
Beispiel #28
0
 def get(self, channel_id):
     channel = Channel.get(int(channel_id))
     current_user = User.get(self.session['user']['id'])
     if channel in Channel.get_visible_channels_of(current_user):
         return self.render_page(channel)
     raise self.forbidden()
Beispiel #29
0
    def post(self, bundle_id):
        def wrong_channel(channel, bundle, add):
            """ returns True if the channel to add is the bundle itself
                or if the channel is a PluginChannel with disabled plugin """
            return bundle.id == channel.id or add and type(channel) is PluginChannel and channel.plugin.activated != "yes"
        form = self.form
        try:
            bundle = ChannelBundle.get(bundle_id)
            u = User.get(self.session['user']['id'])
            diff = json.loads(form.diff)
            if diff == {}:
                logger.info('user %s submitted empty diff for bundle management %s', u.log_name, bundle.name)
                raise ImmediateFeedback("manage_channels", 'nothing_changed')
            # Do the subscription/unsubscription for every channel in the diff
            contained = []
            not_contained = []
            try:
                changes = [(Channel.get(channel_id), add) for channel_id, add in diff.items()]
            except SQLObjectNotFound:
                logger.warning('user %s tried to add a channel which does not exist to bundle %d',
                               u.log_name, bundle.id)
                resp.forbidden()
            # if somebody tries to add a channel with a disabled plugin or to add a bundle to itself
            wrong_channels = [(channel, add) for channel, add in changes if wrong_channel(channel, bundle, add)]
            if wrong_channels:
                channel, add = wrong_channels[0]
                if channel.id == bundle.id:
                    logger.warning('user %s tried to %s bundle %d to itself',
                                   u.log_name, 'add' if add else "remove", bundle.id)
                    raise ImmediateFeedback("manage_channels", "added_to_itself")
                else:
                    logger.warning('user %s tried to %s channel %d with disabled plugin to bundle %d',
                                   u.log_name, 'add' if add else "remove", channel.id, bundle.id)
                    raise ImmediateFeedback("manage_channels", "disabled_plugin")
            for channel, add in changes:
                if add:
                    try:
                        bundle.add_channel(channel)
                    except ValueError:
                        logger.warning("user %s has made changes in channels management of bundle %d that created a "
                                       "cycle of bundles by adding channel %d (%s)", u.log_name, bundle.id, channel.id,
                                       channel.name)
                        form.channel_name = channel.name
                        raise ImmediateFeedback("manage_channels", "bundle_cycle")

                    contained.append(str(channel.id))
                else:
                    bundle.remove_channel(channel)
                    not_contained.append(str(channel.id))
            if contained and not_contained:
                message = "user %s has added to channel(s) %s and removed channel(s) %s to bundle %d" % \
                          (u.log_name, ', '.join(contained), ', '.join(not_contained), bundle.id)
            else:
                message = "user %s has %s channel(s) %s to bundle %d" % \
                          (u.log_name, "added" if contained else "removed",
                           ', '.join(contained if contained else not_contained), bundle.id)
            logger.info(message)
            add_feedback("manage_channels", 'ok')
        except SQLObjectNotFound:
            resp.notfound()
        except ImmediateFeedback:
            pass
        store_form(form)
        resp.seeother("/channels/config/%s/manage_bundle" % bundle.id)
Beispiel #30
0
    def post(self, channel_id):
        form = self.form
        u = User.get(self.session['user']['id'])
        subscribed = []
        unsubscribed = []
        if form.diff == 'diff':
            raise ImmediateFeedback(form.action, 'nothing_changed')
        try:
            diff = json.loads(form.diff)
        except (json.JSONDecodeError, ValueError):
            raise ImmediateFeedback(form.action, 'inconsistent_diff')
        try:
            channelid = int(channel_id)
        except ValueError:
            raise ImmediateFeedback(form.action, 'invalid_channel/screen_id')
        for k, v in diff.items():
            try:
                sub = bool(v)
            except ValueError:
                raise ImmediateFeedback(form.action,
                                        'invalid_channel/screen_id')
            try:
                screenid = int(k)
            except ValueError:
                raise ImmediateFeedback(form.action,
                                        'invalid_channel/screen_id')
            try:
                channel = Channel.get(channelid)
                if not channel.can_subscribe(u):
                    raise self.forbidden(message="You're not allow to do that")
                screen = Screen.get(screenid)
                if not u in screen.owners:
                    raise self.forbidden(message="You're not allow to do that")
                #sub true -> New subscription
                #sub false -> Remove subscription
                if sub:
                    screen.subscribe_to(u, channel)
                    subscribed.append(str(channel.id))
                else:
                    screen.unsubscribe_from(u, channel)
                    unsubscribed.append(str(channel.id))
                if subscribed and unsubscribed:
                    message = "user %s has subscribed screen %d to channel(s) %s and unsubscribed from channel(s) %s" % \
                              (u.log_name, screen.id, ', '.join(subscribed), ', '.join(unsubscribed))
                else:
                    message = "user %s has %s screen %d to channel(s) %s" % \
                              (u.log_name, "subscribed" if subscribed else "unsubscribed", screen.id,
                               ', '.join(subscribed if subscribed else unsubscribed))
                logger.info(message)
                add_feedback("subscription", 'ok')

            except SQLObjectNotFound:
                raise ImmediateFeedback(form.action,
                                        'invalid_channel/screen_id')
            except DuplicateEntryError:
                # if the user has checked + unchecked the same checkbox, it will appear on the diff,
                # we just need to do nothing.
                pass
            except SQLObjectIntegrityError:
                # when there id more than one subscription matching the pair channel/screen
                pass
        resp.seeother("/channels/config/%s/subscriptions" % channel_id)