class ScreenSubscriptionsTestCase(FakePluginTestCase):
    n_elements = 5  # must be >= 3
    plugin_channel_name = "test_channel"
    bundle_channel_name = "test_bundle"
    plugin_name = "test_plugin"
    user_nothing_email = "*****@*****.**"
    user_screen_owner_email = "*****@*****.**"
    user_other_screen_owner_email = "*****@*****.**"
    user_contributor_email = "*****@*****.**"
    user_contributor_of_other_channel_email = "*****@*****.**"
    user_administrator_of_other_channel_email = "*****@*****.**"
    user_channel_admin_email = "*****@*****.**"
    user_administrator_email = "*****@*****.**"
    user_super_administrator_email = "*****@*****.**"

    def run_as(self, users, f):
        """ Runs f as each user in the users list """
        for user in users:
            self.ictv_app.test_user = {"email": user}
            f()

    def setUp(self, fake_plugin_middleware=lambda: None, ictv_middleware=lambda: None):
        super().setUp(fake_plugin_middleware, ictv_middleware)
        building = Building(name="mytestbuilding")
        self.screen = Screen(name="mytestscreen", building=building, secret="secret")
        self.other_screen = Screen(name="myothertestscreen", building=building, secret="secret")
        self.plugins = [Plugin(name="%s%d" % (self.plugin_name, i), activated="yes") for i in
                        range(self.n_elements - 1)]
        self.plugins.append(Plugin.selectBy(name="fake_plugin").getOne())

        self.plugin_channels = [PluginChannel(name="%s%d" % (self.plugin_channel_name, i), plugin=self.plugins[i],
                                              subscription_right="public") for i in range(self.n_elements)]
        self.bundle_channels = [ChannelBundle(name="%s%d" % (self.bundle_channel_name, i), subscription_right="public")
                                for i in range(self.n_elements)]
        other_channel = PluginChannel(name="other_channel", plugin=self.plugins[0], subscription_right="public")
        User(email=self.user_nothing_email, disabled=False)
        User(email=self.user_administrator_email, disabled=False, admin=True)
        User(email=self.user_super_administrator_email, disabled=False, admin=True, super_admin=True)
        screen_owner = User(email=self.user_screen_owner_email, disabled=False)
        self.screen.safe_add_user(screen_owner)
        other_screen_owner = User(email=self.user_other_screen_owner_email, disabled=False)
        self.other_screen.safe_add_user(other_screen_owner)
        contributor = User(email=self.user_contributor_email, disabled=False)
        [plugin_channel.give_permission_to_user(contributor) for plugin_channel in self.plugin_channels]
        contributor_other_channel = User(email=self.user_contributor_of_other_channel_email, disabled=False)
        other_channel.give_permission_to_user(contributor_other_channel)
        administrator_other_channel = User(email=self.user_administrator_of_other_channel_email, disabled=False)
        other_channel.give_permission_to_user(administrator_other_channel, UserPermissions.channel_administrator)
        channel_admin = User(email=self.user_channel_admin_email, disabled=False)
        [plugin_channel.give_permission_to_user(channel_admin, UserPermissions.channel_administrator) for plugin_channel
         in self.plugin_channels]

    def tearDown(self):
        [plugin_channel.destroySelf() for plugin_channel in self.plugin_channels]
        [bundle_channel.destroySelf() for bundle_channel in self.bundle_channels]
        for email in [self.user_nothing_email, self.user_contributor_email, self.user_channel_admin_email,
                      self.user_administrator_email, self.user_super_administrator_email]:
            User.deleteBy(email=email)
        Plugin.deleteBy(name=self.plugin_name)
        super().tearDown()
    def setUp(self, fake_plugin_middleware=lambda: None, ictv_middleware=lambda: None):
        super().setUp(fake_plugin_middleware, ictv_middleware)
        building = Building(name="mytestbuilding")
        self.screen = Screen(name="mytestscreen", building=building, secret="secret")
        self.other_screen = Screen(name="myothertestscreen", building=building, secret="secret")
        self.plugins = [Plugin(name="%s%d" % (self.plugin_name, i), activated="yes") for i in
                        range(self.n_elements - 1)]
        self.plugins.append(Plugin.selectBy(name="fake_plugin").getOne())

        self.plugin_channels = [PluginChannel(name="%s%d" % (self.plugin_channel_name, i), plugin=self.plugins[i],
                                              subscription_right="public") for i in range(self.n_elements)]
        self.bundle_channels = [ChannelBundle(name="%s%d" % (self.bundle_channel_name, i), subscription_right="public")
                                for i in range(self.n_elements)]
        other_channel = PluginChannel(name="other_channel", plugin=self.plugins[0], subscription_right="public")
        User(email=self.user_nothing_email, disabled=False)
        User(email=self.user_administrator_email, disabled=False, admin=True)
        User(email=self.user_super_administrator_email, disabled=False, admin=True, super_admin=True)
        screen_owner = User(email=self.user_screen_owner_email, disabled=False)
        self.screen.safe_add_user(screen_owner)
        other_screen_owner = User(email=self.user_other_screen_owner_email, disabled=False)
        self.other_screen.safe_add_user(other_screen_owner)
        contributor = User(email=self.user_contributor_email, disabled=False)
        [plugin_channel.give_permission_to_user(contributor) for plugin_channel in self.plugin_channels]
        contributor_other_channel = User(email=self.user_contributor_of_other_channel_email, disabled=False)
        other_channel.give_permission_to_user(contributor_other_channel)
        administrator_other_channel = User(email=self.user_administrator_of_other_channel_email, disabled=False)
        other_channel.give_permission_to_user(administrator_other_channel, UserPermissions.channel_administrator)
        channel_admin = User(email=self.user_channel_admin_email, disabled=False)
        [plugin_channel.give_permission_to_user(channel_admin, UserPermissions.channel_administrator) for plugin_channel
         in self.plugin_channels]
Exemplo n.º 3
0
 def runTest(self):
     """ Tests the Screen object. """
     try:
         b = Building(name="test")
         s = Screen(name='News Réaumur', building=b)
         assert_not_equal(None, s)
         s.set(name="testNew")
         assert_equal(s.name, "testNew")
         t = Screen.delete(s.id)
         Building.delete((b.id))
         assert_equal(t, None)
     except DuplicateEntryError:
         assert_true(False)
     return
Exemplo n.º 4
0
    def runTest(self):
        """ Checks that we cannot delete a building with screens attached to it, and checks that the
        error is correctly handler for the user """
        building_to_test = Building.get(self.building2_id)
        s = Screen(name="mytestscreen",
                   building=building_to_test,
                   secret="secret")

        def f():
            post_params = {"action": "delete", "id": building_to_test.id}
            # Use a wrong ID and see if nothing changed and the error has been handled properly for the user
            r = self.testApp.post('/buildings', params=post_params, status=200)
            assert r.body is not None

        check_table_did_not_change(f)
        s.destroySelf()
    def runTest(self):
        """ Tries to subscribe to a PluginChannel with a non-activated plugin and to restricted/private channel
            without being in the authorized subscribers and verifies that the subscription has not been done"""
        screen = self.screen
        plugin_channel = self.plugin_channels[0]
        plugin_channel.plugin.activated = "no"
        diff = {plugin_channel.id: True}
        post_params = {"diff": json.dumps(diff)}
        before = {repr(s) for s in screen.subscribed_channels}
        assert self.testApp.post("/screens/%s/subscriptions" % screen.id, post_params, status=303).body is not None
        after = {repr(s) for s in Screen.get(screen.id).subscribed_channels}
        assert after == before

        # Now try to subscribe to restricted channel without having the right to do this
        plugin_channel.plugin.activated = "yes"

        def try_sub_fail():
            for right in "restricted", "private":
                plugin_channel.subscription_right = right
                diff = {plugin_channel.id: True}
                post_params = {"diff": json.dumps(diff)}
                before = {repr(s) for s in screen.subscribed_channels}
                assert self.testApp.post("/screens/%s/subscriptions" % screen.id, post_params, status=403).body is not None
                after = {repr(s) for s in Screen.get(screen.id).subscribed_channels}
                assert after == before
        # Nobody (excepted the admin and super_admin) can succeed to do this, even the owner of the screen
        self.run_as([self.user_nothing_email, self.user_contributor_email, self.user_channel_admin_email,
                     self.user_contributor_of_other_channel_email, self.user_administrator_of_other_channel_email,
                     self.user_screen_owner_email, self.user_other_screen_owner_email], try_sub_fail)
Exemplo n.º 6
0
 def get(self, id):
     try:
         id = int(id)
         sc = Screen.get(id)
         return self.render_page(sc)
     except (SQLObjectNotFound, ValueError):
         resp.seeother('/screens')
Exemplo n.º 7
0
 def screens_config_1(self):
     # basic test
     Screen(name='A', building=Building(name='A'))
     r = self.testApp.get('/screens/1/config')
     print(r.body, r.headers)
     assert_equal(r.status, 200)
     assert_not_equal(r.body, None)
Exemplo n.º 8
0
 def POST(self):
     form = web.input()
     subject = form['subject']
     email_body = form['body']
     to = form['to']
     receivers = []
     if to=="admins":
         receivers =[u for u in User.selectBy(admin=True, disabled=False)]
     elif to=="supadmins":
         receivers=[u for u in User.selectBy(super_admin=True).distinct()]
     elif to == 'contrib':
         id_channel=form['select_channel']
         c = PluginChannel.get(id_channel)
         receivers = [u for u in c.get_contribs()]
     elif to=="channel_editor_users":
         pc = PluginChannel.select()
         for elem in pc:
             if elem.plugin.name=="editor":
                 l1=[u1 for u1 in elem.get_admins()]
                 l2=[u2 for u2 in elem.get_contribs()]
                 list_users = l1+l2
                 receivers=[u for u in list_users]
     else:
       for s in Screen.select():
           receivers=[u for u in s.owners]
     try:
         for u in receivers:
             web.sendmail(web.config.smtp_sendername, u.email, subject, email_body,
                          headers={'Content-Type': 'text/html;charset=utf-8'})
     except smtplib.SMTPException:
         logger.error('An error occured when sending email ', exc_info=True)
     return web.seeother("/")
Exemplo n.º 9
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()
 def runTest(self):
     """ Submits an empty diff to the page and ensures that nothing has changed """
     screen = self.screen
     before = {repr(s) for s in screen.subscribed_channels}
     post_params = {"diff": json.dumps({})}
     assert self.testApp.post("/screens/%s/subscriptions" % screen.id, post_params, status=303).body is not None
     after = {repr(s) for s in Screen.get(screen.id).subscribed_channels}
     assert after == before
 def try_sub_fail():
     for right in "restricted", "private":
         plugin_channel.subscription_right = right
         diff = {plugin_channel.id: True}
         post_params = {"diff": json.dumps(diff)}
         before = {repr(s) for s in screen.subscribed_channels}
         assert self.testApp.post("/screens/%s/subscriptions" % screen.id, post_params, status=403).body is not None
         after = {repr(s) for s in Screen.get(screen.id).subscribed_channels}
         assert after == before
Exemplo n.º 12
0
 def GET(self, screen_id, secret):
     """ Serves the pure web-based client for this screen. """
     try:
         screen = Screen.get(screen_id)
         if screen.secret != secret:
             raise web.forbidden()
     except SQLObjectNotFound:
         raise web.notfound()
     return self.ictv_renderer.render_screen_client(screen)
Exemplo n.º 13
0
def create_database():
    Building.createTable()
    Channel.createTable()
    Plugin.createTable()
    User.createTable()
    PluginChannel.createTable()
    ChannelBundle.createTable()
    Role.createTable()
    Screen.createTable()
    ScreenMac.createTable()
    Subscription.createTable()
    Template.createTable()
    Asset.createTable()
    PluginParamAccessRights.createTable()
    LogStat.createTable()
    DBVersion.createTable()
    DBVersion(version=database_version)
    User(username="******", fullname="ICTV Admin", email="admin@ictv", super_admin=True, disabled=False)
Exemplo n.º 14
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)
Exemplo n.º 15
0
class ChannelsPageTestCase(FakePluginTestCase):
    def setUp(self):
        super(ChannelsPageTestCase, self).setUp()
        Channel.deleteMany(None)
        self.fake_plugin = Plugin.byName('fake_plugin')
        self.pc1 = PluginChannel(plugin=self.fake_plugin,
                                 name='PC 1',
                                 subscription_right='public')
        self.pc2 = PluginChannel(plugin=self.fake_plugin,
                                 name='PC 2',
                                 subscription_right='public')
        self.pc3 = PluginChannel(plugin=self.fake_plugin,
                                 name='PC 3',
                                 subscription_right='public')
        self.bundle = ChannelBundle(name='Bundle', subscription_right='public')
        self.building = Building(name='Building')
        self.screen = Screen(name='Screen', building=self.building)
        self.user_nothing = User(email='nothing@localhost', disabled=False)
        self.user_contrib = User(email='contrib@localhost', disabled=False)
        self.pc1.give_permission_to_user(self.user_contrib,
                                         UserPermissions.channel_contributor)
        self.user_chan_admin = User(email='chan_admin@localhost',
                                    disabled=False)
        self.user_chan_admin2 = User(email='chan_admin2@localhost',
                                     disabled=False)
        self.pc1.give_permission_to_user(self.user_chan_admin,
                                         UserPermissions.channel_administrator)
        self.pc2.give_permission_to_user(self.user_chan_admin2,
                                         UserPermissions.channel_administrator)
        self.user_screen_admin = User(email='screen_admin@locahost',
                                      disabled=False)
        self.screen.safe_add_user(self.user_screen_admin)
        self.user_admin = User(email='admin@localhost',
                               disabled=False,
                               admin=True)
        self.user_super_admin = User(email='super_admin@localhost',
                                     disabled=False,
                                     admin=True,
                                     super_admin=True)
        self.users = [
            self.user_nothing, self.user_contrib, self.user_chan_admin,
            self.user_chan_admin2, self.user_screen_admin, self.user_admin,
            self.user_super_admin
        ]
Exemplo n.º 16
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))
 def runTest(self):
     """ Tries to subscribe the screen to a non-existing channel and verifies that it is forbidden by the app and
         nothing has been done """
     screen = self.screen
     plugin_channel = self.plugin_channels[0]
     plugin_channel.plugin.activated = "no"
     diff = {plugin_channel.id: True, -1: True}
     post_params = {"diff": json.dumps(diff)}
     before = {repr(s) for s in screen.subscribed_channels}
     assert self.testApp.post("/screens/%s/subscriptions" % screen.id, post_params, status=403).body is not None
     after = {repr(s) for s in Screen.get(screen.id).subscribed_channels}
     assert after == before
Exemplo n.º 18
0
 def get(self, screen_id, secret):
     """ Render the channels of this screen. """
     try:
         screen = Screen.get(screen_id)
     except SQLObjectNotFound:
         return migration_adapter.notfound()
     if screen.secret != secret:
         return migration_adapter.forbidden()
     if flask.request.remote_addr is None:
         pass
     else:
         screens_logger.info("Request to the screen " + str(screen_id) + " has been done from:" + flask.request.remote_addr)
     if flask.request.headers.get('User-Agent') == 'cache_daemon.py':
         screen.last_ip = flask.g.ip
         screen.last_access = datetime.now()
     return render_screen(screen, self.app)
Exemplo n.º 19
0
 def GET(self, screen_id, secret):
     """ Render the channels of this screen. """
     try:
         screen = Screen.get(screen_id)
     except SQLObjectNotFound:
         raise web.notfound()
     if screen.secret != secret:
         raise web.forbidden()
     if web.ctx.env.get('REMOTE_ADDR') is None:
         pass
     else:
         screens_logger.info("Request to the screen " + str(screen_id) +
                             " has been done from:" +
                             web.ctx.env.get('REMOTE_ADDR'))
     if web.ctx.env.get('HTTP_USER_AGENT') == 'cache_daemon.py':
         screen.last_ip = web.ctx.ip
         screen.last_access = datetime.now()
     return render_screen(screen, self.app)
Exemplo n.º 20
0
    def runTest(self):
        """ Tests the User object """
        try:
            User(username='******',
                 fullname='test test',
                 email='*****@*****.**',
                 super_admin=True,
                 disabled=False)
        except DuplicateEntryError:
            assert_true(False)
        b = User.selectBy(username="******").getOne()

        assert_not_equal(b, None)
        assert_equal(b.username, "test")
        try:
            b.set(username="******")
        except DuplicateEntryError:
            assert_true(False)
        assert_equal(b.username, "newName")
        b.set(username="******")
        l = b.get_subscriptions_of_owned_screens()
        assert_true(l.count() >= 0)
        una = User(username='******',
                   fullname='testnoadmin test',
                   email='*****@*****.**',
                   super_admin=False,
                   disabled=False)
        l = una.get_subscriptions_of_owned_screens()
        assert_true(l.count() >= 0)
        User.delete(una.id)
        b.set(disabled=True)
        assert_equal(b.disabled, True)
        t = b.owns_screen()
        assert_equal(t, False)
        b = User.selectBy(username="******").getOne()
        b.addScreen(Screen(name='A', building=Building(name='A')))
        t = b.owns_screen()
        assert_equal(t, True)
        b = User.selectBy(username="******").getOne()
        t = User.delete(b.id)
        assert_equal(t, None)
        b = User.selectBy(username="******").getOne(None)
        assert_true(None == b)
Exemplo n.º 21
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)
Exemplo n.º 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)
Exemplo n.º 23
0
 def post(self):
     form = self.form
     subject = form['subject']
     email_body = form['body']
     to = form['to']
     receivers = []
     if to == "admins":
         receivers = [u for u in User.selectBy(admin=True, disabled=False)]
     elif to == "supadmins":
         receivers = [u for u in User.selectBy(super_admin=True).distinct()]
     elif to == 'contrib':
         id_channel = form['select_channel']
         c = PluginChannel.get(id_channel)
         receivers = [u for u in c.get_contribs()]
     elif to == "channel_editor_users":
         pc = PluginChannel.select()
         for elem in pc:
             if elem.plugin.name == "editor":
                 l1 = [u1 for u1 in elem.get_admins()]
                 l2 = [u2 for u2 in elem.get_contribs()]
                 list_users = l1 + l2
                 receivers = [u for u in list_users]
     else:
         for s in Screen.select():
             receivers = [u for u in s.owners]
     try:
         mail = Mail(self.app)
         msg = Message(
             recipients=[u.email for u in receivers],
             subject=subject,
             body=email_body,
             extra_headers={'Content-Type': 'text/html;charset=utf-8'})
         mail.send(msg)
     except smtplib.SMTPException:
         logger.error('An error occured when sending email ', exc_info=True)
     resp.seeother("/")
Exemplo n.º 24
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)
Exemplo n.º 25
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)
Exemplo n.º 26
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
Exemplo n.º 27
0
 def runTest(self):
     """ Tests the screen routing based on encoded MAC addresses. """
     sc = Screen(name='A', building=Building(name='A'))
     sm = ScreenMac(screen=sc, mac='000000000000')
     self.testApp.get('/screens/redirect/' + sm.mac, status=303)
Exemplo n.º 28
0
 def screen_client_1(self):
     sc = Screen.get(1)
     r = self.testApp.get('/screens/1/client/' + sc.secret, status=200)
     assert_not_equal(r.body, None)
Exemplo n.º 29
0
 def screen_view_1(self):
     sc = Screen(name='A', building=Building(name='A'))
     r = self.testApp.get('/screens/1/view/' + sc.secret, status=200)
     assert_not_equal(r.body, None)
Exemplo n.º 30
0
 def screens_1(self):
     # basic test
     Screen(name='A', building=Building(name='A'))
     r = self.testApp.get('/screens/1', status=200)
     assert_not_equal(r.body, None)