Пример #1
0
    def update_password(self, request):
        """ Updates the password using the form data (if permitted to do so).

        Returns True if successful, False if not successful.
        """
        data = request.load_url_safe_token(self.token.data, max_age=86400)

        if not data:
            return False

        if not data.get('username') == self.email.data:
            return False

        users = UserCollection(request.app.session())
        user = users.by_username(self.email.data)

        if not user:
            return False

        modified = user.modified.isoformat() if user.modified else ''

        if modified != data['modified']:
            return False

        user.password = self.password.data

        return True
Пример #2
0
def test_notice_collection_own_user_id(session):
    users = UserCollection(session)
    user_a = users.add(username='******', password='******', role='admin')
    user_b = users.add(username='******', password='******', role='admin')
    user_c = users.add(username='******', password='******', role='admin')

    collection = GazetteNoticeCollection(session)
    for title, user, annotators in (
        ('A', user_a, []),
        ('B', user_b, [user_a]),
        ('C', user_c, [user_a, user_b]),
    ):
        notice = collection.add(title=title,
                                text='Text',
                                organization_id='100',
                                category_id='11',
                                issues=['2017-46'],
                                user=user)
        for annotator in annotators:
            notice.changes.append(
                GazetteNoticeChange(
                    channel_id=str(notice.id),
                    owner=str(annotator.id),
                ))

    assert collection.query().count() == 3

    collection.own_user_id = str(user_a.id)
    assert collection.query().count() == 3

    collection.own_user_id = str(user_b.id)
    assert collection.query().count() == 2

    collection.own_user_id = str(user_c.id)
    assert collection.query().count() == 1
Пример #3
0
def handle_user_profile(self, request, form):
    """ Handles the GET and POST login requests. """

    layout = DefaultLayout(self, request)

    collection = UserCollection(request.app.session())
    user = collection.by_username(request.identity.userid)

    if form.submitted(request):
        form.update_model(user)
        request.success(_("Your changes were saved"))
    else:
        form.apply_model(user)

    layout.breadcrumbs = [
        Link(_("Homepage"), layout.homepage_url),
        Link(_("User Profile"), request.link(self))
    ]

    return {
        'layout': layout,
        'title': _("User Profile"),
        'form': form,
        'username': user.username,
        'role': user.role
    }
Пример #4
0
    def import_editors_and_groups(request, app):
        request.locale = locale
        headers = {
            'group': request.translate(_("Group")),
            'name': request.translate(_("Name")),
            'email': request.translate(_("E-Mail"))
        }

        session = app.session()
        users = UserCollection(session)
        groups = UserGroupCollection(session)

        if clear:
            click.secho("Deleting all editors", fg='yellow')
            for user in users.query().filter(User.role == 'member'):
                session.delete(user)

            click.secho("Deleting all groups", fg='yellow')
            for group in groups.query():
                session.delete(group)

        csvfile = convert_xls_to_csv(
            file, sheet_name=request.translate(_("Editors"))
        )
        csv = CSVFile(csvfile, expected_headers=headers.values())
        lines = list(csv.lines)
        columns = {
            key: csv.as_valid_identifier(value)
            for key, value in headers.items()
        }

        added_groups = {}
        for group in set([line.gruppe for line in lines]):
            added_groups[group] = groups.add(name=group)
        count = len(added_groups)
        click.secho(f"{count} group(s) imported", fg='green')

        count = 0
        for line in lines:
            count += 1
            email = getattr(line, columns['email'])
            realname = getattr(line, columns['name'])
            group = getattr(line, columns['group'])
            group = added_groups[group] if group else None
            users.add(
                username=email,
                realname=realname,
                group=group,
                password=random_password(),
                role='member',
            )

        click.secho(f"{count} editor(s) imported", fg='green')

        if dry_run:
            transaction.abort()
            click.secho("Aborting transaction", fg='yellow')
Пример #5
0
def test_notice_change(session):
    users = UserCollection(session)

    session.add(GazetteNoticeChange(text='text', channel_id='channel'))
    session.flush()

    change = session.query(GazetteNoticeChange).one()
    assert change.text == 'text'
    assert change.channel_id == 'channel'
    assert change.user is None
    assert change.user_name is None
    assert change._user_name is None
    assert change.notice is None
    assert change.event is None

    # Add user
    change.event = 'event'
    user = users.add('*****@*****.**', 'test', 'editor')
    change.user = user
    session.flush()
    session.refresh(change)

    assert change.text == 'text'
    assert change.channel_id == 'channel'
    assert change.user == user
    assert change.user_name == '*****@*****.**'
    assert change._user_name == '*****@*****.**'
    assert change.notice is None
    assert change.event == 'event'
    assert user.changes == [change]

    # Add to notice
    session.add(GazetteNotice(state='drafted', title='title', name='notice'))
    session.flush()
    notice = session.query(GazetteNotice).one()
    change.notice = notice

    assert notice.changes.one() == change

    # Rename user
    user.realname = 'Peter'
    session.flush()
    session.refresh(change)

    assert change.user == user
    assert change.user_name == 'Peter'
    assert change._user_name == 'Peter'
    assert user.changes == [change]

    # Delete user
    users.delete(user.username)
    session.flush()
    session.refresh(change)

    assert change.user is None
    assert change.user_name == '(Peter)'
    assert change._user_name == 'Peter'
Пример #6
0
def handle_password_reset_request(self, request, form):

    """ Handles the password reset requests. """

    show_form = True
    callout = None

    if form.submitted(request):
        users = UserCollection(request.session)
        user = users.by_username(form.email.data)
        if user:
            url = password_reset_url(
                user,
                request,
                request.link(self, name='reset-password')
            )

            request.app.send_transactional_email(
                subject=request.translate(_("Password reset")),
                receivers=(user.username, ),
                reply_to=request.app.mail['transactional']['sender'],
                content=render_template(
                    'mail_password_reset.pt',
                    request,
                    {
                        'title': request.translate(_("Password reset")),
                        'model': None,
                        'url': url,
                        'layout': MailLayout(self, request)
                    }
                )
            )
        else:
            log.info(
                "Failed password reset attempt by {}".format(
                    request.client_addr
                )
            )

        show_form = False
        callout = _(
            (
                'A password reset link has been sent to ${email}, provided an '
                'account exists for this email address.'
            ),
            mapping={'email': form.email.data}
        )

    return {
        'layout': DefaultLayout(self, request),
        'title': _('Reset password'),
        'form': form,
        'show_form': show_form,
        'callout': callout
    }
    def recipients_by_role(self, roles):
        if not roles:
            return set()

        users = UserCollection(self.request.session)

        q = users.by_roles(*roles)
        q = q.filter(User.active == True)
        q = q.with_entities(User.username)

        return {u.username for u in q}
Пример #8
0
def handle_password_reset_request(self, request, form):
    """ Handles the password reset requests. """

    show_form = True
    callout = None

    if form.submitted(request):
        users = UserCollection(request.session)
        user = users.by_username(form.email.data)
        if user:
            url = password_reset_url(
                user,
                request,
                request.link(self, name='reset-password')
            )

            request.app.send_transactional_email(
                subject=request.translate(_("Password reset")),
                receivers=(user.username, ),
                reply_to=request.app.mail['transactional']['sender'],
                content=render_template(
                    'mail_password_reset.pt',
                    request,
                    {
                        'title': request.translate(_("Password reset")),
                        'model': None,
                        'url': url,
                        'layout': MailLayout(self, request)
                    }
                )
            )
        else:
            log.info(
                "Failed password reset attempt by {}".format(
                    request.client_addr
                )
            )

        show_form = False
        callout = _(
            (
                'A password reset link has been sent to ${email}, provided an '
                'account exists for this email address.'
            ),
            mapping={'email': form.email.data}
        )

    return {
        'layout': Layout(self, request),
        'title': _('Reset password'),
        'form': form,
        'show_form': show_form,
        'callout': callout
    }
Пример #9
0
    def get_token(self, request):
        """ Returns the user and a token for the given username to reset the
        password. If the username is not found, (None, None) is returned.

        """
        users = UserCollection(request.app.session())
        user = users.by_username(self.email.data)
        token = None

        if user is not None:
            modified = user.modified.isoformat() if user.modified else ""
            token = request.new_url_safe_token({"username": user.username, "modified": modified})
        return user, token
Пример #10
0
    def add_town(self, name, user, color, request):
        current_schema = self.app.session_manager.current_schema
        password = random_password(16)

        try:
            schema = self.get_schema(name)
            custom_config = self.config['configuration']

            self.app.session_manager.set_current_schema(schema)
            session = self.app.session_manager.session()

            if session.query(Organisation).first():
                raise AlreadyExistsError

            with self.app.temporary_depot(schema, **custom_config):
                create_new_organisation(self.app, name=name, reply_to=user)

            org = session.query(Organisation).first()
            org.theme_options['primary-color'] = color

            users = UserCollection(self.app.session_manager.session())
            assert not users.query().first()

            users.add(user, password, 'admin')

            title = request.translate(_("Welcome to OneGov Cloud"))
            welcome_mail = render_template(
                'mail_welcome.pt', request, {
                    'url': 'https://{}'.format(self.get_domain(name)),
                    'mail': user,
                    'layout': MailLayout(self, request),
                    'title': title,
                    'org': name
                })

            self.app.es_perform_reindex()
            self.app.send_transactional_email(subject=title,
                                              receivers=(user, ),
                                              content=welcome_mail,
                                              reply_to='*****@*****.**')

        finally:
            self.app.session_manager.set_current_schema(current_schema)

        return {
            'info': [
                (_("Username"), user),
                (_("Password"), password),
            ],
            'url': 'https://{}'.format(self.get_domain(name))
        }
Пример #11
0
    def username_choices(self):
        assert self.request.is_admin  # safety net

        users = UserCollection(self.request.session)
        users = users.by_roles('admin', 'editor')
        users = users.with_entities(User.username, User.title)

        def choice(row):
            return row[0], row[1]

        def by_title(choice):
            return normalize_for_url(choice[1])

        return sorted([choice(r) for r in users.all()], key=by_title)
Пример #12
0
def test_vacation_activity_form(session, test_password):
    users = UserCollection(session)
    users.add(username='******',
              realname='Robert Baratheon',
              password='******',
              role='admin')
    users.add(username='******',
              realname=None,
              password='******',
              role='editor')
    users.add(username='******',
              realname=None,
              password='******',
              role='member')

    form = VacationActivityForm()
    form.request = Bunch(is_admin=True,
                         current_username='******',
                         session=session)

    form.on_request()

    assert form.username.data == '*****@*****.**'
    assert form.username.choices == [('*****@*****.**',
                                      '*****@*****.**'),
                                     ('*****@*****.**', 'Robert Baratheon')]

    form.request.is_admin = False
    form.on_request()

    assert form.username is None
Пример #13
0
def remove_extra_space_from_user(context):
    org = context.session.query(Organisation).first()

    if org is None:
        return

    # not a feriennet
    if '<registration />' not in org.meta['homepage_structure']:
        return

    users = UserCollection(context.session).query()
    users = users.filter(User.realname.like('%{}%'.format(NAME_SEPARATOR)))

    for user in users:
        user.realname = NAME_SEPARATOR.join(
            p.strip() for p in user.realname.split(NAME_SEPARATOR))
Пример #14
0
def delete_user(self, request):
    """ Delete a user. """

    request.assert_valid_csrf_token()
    self.logout_all_sessions(request)
    UserCollection(request.session).delete(self.username)
    request.message(_("User deleted."), 'success')
Пример #15
0
    def user(self):
        username = self.request.identity.userid
        if username:
            return UserCollection(self.session,
                                  username=username).query().first()

        return None
Пример #16
0
    def add_town(self, name, user, color, request):
        current_schema = self.app.session_manager.current_schema
        password = random_password(16)

        try:
            self.app.session_manager.set_current_schema(self.get_schema(name))
            session = self.app.session_manager.session()

            if session.query(Organisation).first():
                raise AlreadyExistsError

            create_new_organisation(self.app, name=name, reply_to=user)

            org = session.query(Organisation).first()
            org.theme_options['primary-color'] = color

            users = UserCollection(self.app.session_manager.session())
            assert not users.query().first()

            users.add(user, password, 'admin')

            title = request.translate(_("Welcome to OneGov Cloud"))
            welcome_mail = render_template('mail_welcome.pt', request, {
                'url': 'https://{}'.format(self.get_domain(name)),
                'mail': user,
                'layout': MailLayout(self, request),
                'title': title,
                'org': name
            })

            self.app.send_email(
                subject=title,
                receivers=(user, ),
                content=welcome_mail,
                reply_to='*****@*****.**'
            )

        finally:
            self.app.session_manager.set_current_schema(current_schema)

        return {
            'info': [
                (_("Username"), user),
                (_("Password"), password),
            ],
            'url': 'https://{}'.format(self.get_domain(name))
        }
Пример #17
0
    def get_identity(self, request):
        """ Returns the given user by username, token and the new password.
        If the username is not found or the token invalid, None is returned.

        """
        data = request.load_url_safe_token(self.token.data, max_age=86400)
        if data and data["username"] == self.email.data:
            users = UserCollection(request.app.session())
            user = users.by_username(self.email.data)
            if user:
                modified = user.modified.isoformat() if user.modified else ""
                if modified == data["modified"]:
                    user.password = self.password.data
                    return morepath.Identity(
                        userid=user.username, role=user.role, application_id=request.app.application_id
                    )

        return None
Пример #18
0
def delete_user(self, request, form):
    """ Delete a user.

    Publishers may only edit members. Admins can not be deleted.

    """

    layout = Layout(self, request)

    if self.role != 'member' and not request.is_secret(self):
        raise HTTPForbidden()

    if self.official_notices or self.changes:
        request.message(_("There are official notices linked to this user!"),
                        'warning')

    if form.submitted(request):
        collection = UserCollection(request.session)
        user = collection.by_username(self.username)
        if user.role != 'admin':
            self.logout_all_sessions(request)
            collection.delete(self.username)
            request.message(_("User deleted."), 'success')
        return redirect(layout.manage_users_link)

    return {
        'message':
        _('Do you really want to delete "${item}"?',
          mapping={'item': self.title}),
        'layout':
        layout,
        'form':
        form,
        'title':
        self.title,
        'subtitle':
        _("Delete User"),
        'button_text':
        _("Delete User"),
        'button_class':
        'alert',
        'cancel':
        layout.manage_users_link
    }
Пример #19
0
def test_notice_collection_on_request(session):
    collection = GazetteNoticeCollection(session)

    collection.on_request(DummyRequest(None))
    assert collection.own_user_id is None

    collection.own = True
    collection.on_request(DummyRequest(None))
    assert collection.own_user_id is None

    collection.on_request(DummyRequest(None, DummyIdentity(None)))
    assert collection.own_user_id is None

    collection.on_request(DummyRequest(None, DummyIdentity('[email protected]')))
    assert collection.own_user_id is None

    users = UserCollection(session)
    user = users.add(username='******', password='******', role='admin')

    collection.on_request(DummyRequest(None, DummyIdentity('[email protected]')))
    assert collection.own_user_id == str(user.id)
Пример #20
0
def test_notice_ownership(session):
    users = UserCollection(session)
    groups = UserGroupCollection(session)
    user = users.add('[email protected]', '1234', 'admin', realname='user')
    group = groups.add(name='group')

    notice = OfficialNotice(
        title='title',
        state='drafted',
        text='Text',
    )
    notice.user = user
    notice.group = group
    session.add(notice)
    session.flush()

    notice = session.query(OfficialNotice).one()
    notice.user == user
    notice.user.realname == 'user'
    notice.group == group
    notice.group.name == 'group'
Пример #21
0
def reinstate_daily_ticket_status_email(context):
    org = context.session.query(Organisation).first()

    if org is None:
        return

    # not a feriennet
    if '<registration />' not in org.meta['homepage_structure']:
        return

    for user in UserCollection(context.session).by_roles('admin'):
        user.data = user.data or {}
        user.data['daily_ticket_statistics'] = True
Пример #22
0
    def add_change(self, request, event, text=None):
        """ Adds en entry to the changelog. """

        session = object_session(self)
        try:
            username = request.identity.userid
            owner = str(UserCollection(session).by_username(username).id)
        except Exception:
            owner = None

        self.changes.append(
            GazetteNoticeChange(channel_id=str(self.id),
                                owner=owner,
                                text=text or '',
                                meta={'event': event}))
Пример #23
0
    def is_complete_userprofile(request, username, user=None):
        user = user or UserCollection(
            request.session).by_username(username)

        form = UserProfileForm()
        form.request = request
        form.model = user
        form.on_request()

        form.process(obj=user)

        for field_id, field in form._fields.items():
            field.raw_data = field.data

        return form.validate()
Пример #24
0
def test_notice_collection(session, organizations, categories, issues):
    user = UserCollection(session).add(username='******',
                                       password='******',
                                       role='admin')

    collection = GazetteNoticeCollection(session)
    collection.add(title='Notice A',
                   text='An <strong>important</strong> Notice!',
                   organization_id='100',
                   category_id='11',
                   issues=['2017-46', '2017-47'],
                   user=user)
    collection.add(title='Notice B',
                   text='Another Notice',
                   organization_id='200',
                   category_id='13',
                   issues={'2017-47', '2017-48'},
                   user=user)

    notice = collection.for_term('Notice A').query().one()
    assert notice.title == 'Notice A'
    assert notice.text == 'An <strong>important</strong> Notice!'
    assert notice.organization_id == '100'
    assert notice.organization == 'State Chancellery'
    assert notice.category_id == '11'
    assert notice.category == 'Education'
    assert notice.issues == {'2017-46': None, '2017-47': None}
    assert notice.first_issue == standardize_date(datetime(2017, 11, 17),
                                                  'UTC')
    assert notice.user == user
    assert notice.changes.one().event == 'created'
    assert notice.changes.one().user == user

    notice = collection.for_term('Notice B').query().one()
    assert notice.title == 'Notice B'
    assert notice.text == 'Another Notice'
    assert notice.organization_id == '200'
    assert notice.organization == 'Civic Community'
    assert notice.category_id == '13'
    assert notice.category == 'Commercial Register'
    assert notice.issues == {'2017-47': None, '2017-48': None}
    assert notice.first_issue == standardize_date(datetime(2017, 11, 24),
                                                  'UTC')
    assert notice.user == user
    assert notice.changes.one().event == 'created'
    assert notice.changes.one().user == user
    def recipients_pool(self):
        users = UserCollection(self.request.session)
        users = users.query()

        if self.state.data == ['active']:
            users = users.filter(User.active == True)
        elif self.state.data == ['inactive']:
            users = users.filter(User.active == False)
        elif self.state.data != ['active', 'inactive']:
            return set()

        return {u.username for u in users.with_entities(User.username)}
Пример #26
0
def test_notice_collection_count_by_group(session):
    collection = GazetteNoticeCollection(session)
    assert collection.count_by_group() == []

    groups = UserGroupCollection(session)
    group_a = groups.add(name='A')
    group_b = groups.add(name='B')
    groups.add(name='C')

    users = UserCollection(session)
    user_a = users.add('*****@*****.**', 'pw', 'editor', group=group_a)
    user_b = users.add('*****@*****.**', 'pw', 'editor', group=group_a)
    user_c = users.add('*****@*****.**', 'pw', 'admin')
    user_d = users.add('*****@*****.**', 'pw', 'publisher')
    user_e = users.add('*****@*****.**', 'pw', 'publisher', group=group_b)
    user_f = users.add('*****@*****.**', 'pw', 'publisher')
    user_g = users.add('*****@*****.**', 'pw', 'publisher')
    user_h = users.add('*****@*****.**', 'pw', 'publisher')

    for user, count in (
        (user_a, 2),
        (user_b, 4),
        (user_c, 1),
        (user_d, 7),
        (user_e, 2),
        (user_f, 3),
        (user_g, 6),
        (user_h, 2),
    ):
        for x in range(count):
            collection.add(title='',
                           text='',
                           organization_id='',
                           category_id='',
                           issues=['2017-{}'.format(y) for y in range(x)],
                           user=user)
    assert collection.count_by_group() == [('A', 7), ('B', 1)]

    assert collection.count_by_group() == \
        collection.for_state('drafted').count_by_group()

    collection.issues = ['2017-2', '2017-4']
    assert collection.count_by_group() == [('A', 1)]
Пример #27
0
    def generate(request, app):
        owners = [
            u.username
            for u in UserCollection(app.session()).by_roles('admin', 'editor')
        ]

        session = app.session()

        bound_generate_activity = partial(
            generate_activity,
            request=request,
            app=app,
            activities=VacationActivityCollection(session, identity=None),
            occasions=OccasionCollection(session),
        )

        for n in range(0, count):
            bound_generate_activity(owner=random.choice(owners))
Пример #28
0
    def top_navigation(self):
        has_permission = self.request.has_permission
        session = self.request.session
        result = []
        if has_permission(ScanJobCollection(session), ViewModel):
            result.append(Link(_("Scan jobs"), self.scan_jobs_url))
        if has_permission(DailyList(), ViewModel):
            result.append(Link(_("Daily list"), self.daily_list_url))
        if has_permission(Report(session), ViewModel):
            result.append(Link(_("Report"), self.report_url))
        if has_permission(Invoice(session), ViewModel):
            result.append(Link(_("Invoices"), self.invoices_url))
        if has_permission(UserCollection(session), ViewModel):
            result.append(Link(_("Users"), self.users_url))
        if has_permission(MunicipalityCollection(session), ViewModel):
            result.append(Link(_("Municipalities"), self.municipalities_url))
        if has_permission(NotificationCollection(session), ViewModel):
            result.append(Link(_("Notifications"), self.notifications_url))
        if has_permission(UserManual(self.app), ViewModel):
            result.append(Link(_("User manual"), self.user_manual_url))

        return result
Пример #29
0
def clear_user_sessions(self, request, form):
    """ Closes all open browser sessions.

    This view is only visible by an admin.

    """

    layout = Layout(self, request)
    cancel = request.link(UserCollection(request.session), name='sessions')

    if form.submitted(request):
        self.logout_all_sessions(request)
        return redirect(cancel)

    return {
        'message': _("Do you really clear all active sessions?"),
        'layout': layout,
        'form': form,
        'title': self.title,
        'subtitle': _("Clear Sessions"),
        'button_text': _("Clear Sessions"),
        'button_class': 'alert',
        'cancel': cancel
    }
Пример #30
0
def get_user(request):
    session = request.session
    return UserCollection(session).by_username(request.identity.userid)
Пример #31
0
 def users_url(self):
     return self.request.link(UserCollection(self.request.session))
Пример #32
0
def test_notice_collection_search(session):
    groups = UserGroupCollection(session)
    group_a = groups.add(name='GroupA')
    group_b = groups.add(name='GroupB1')

    users = UserCollection(session)
    user_a = users.add('*****@*****.**', 'password', 'editor', realname='Hans')
    user_b = users.add('*****@*****.**', 'password', 'editor')

    notices = OfficialNoticeCollection(session)

    notice = notices.add(title='First',
                         text='Lorem Ipsum',
                         category='Cat1',
                         group=group_a)
    notice.state = 'drafted'

    notice = notices.add(title='Second',
                         text='A text',
                         category='Cat1',
                         organization='Org1',
                         user=user_a,
                         group=group_b)
    notice.state = 'submitted'

    notice = notices.add(title='Third', text='Anöther text', category='Cat2')
    notice.state = 'drafted'

    notice = notices.add(title='Fourth',
                         text='A fourth text',
                         organization='Org2')
    notice.state = 'published'

    notice = notices.add(title='Fifth', text='Lorem Ipsum', user=user_a)
    notice.state = 'rejected'

    notice = notices.add(title='Sixt',
                         text='<p>Six</p>',
                         author_name='Cysat',
                         note='Papanikolaou',
                         user=user_b,
                         group=group_a)
    notice.state = 'published'

    notice = notices.add(title='Sübent',
                         text='Sübent',
                         author_place='Wynmärkt')
    notice.state = 'drafted'

    assert notices.query().count() == 7

    assert notices.for_term('Third').query().count() == 1

    assert notices.for_term('ourth').query().count() == 1

    assert notices.for_term('ipsum').query().count() == 2
    assert notices.for_term('ipsum').for_state('rejected').query().count() == 1

    assert notices.for_term('six').query().count() == 1
    assert notices.for_term('six').for_state('rejected').query().count() == 0

    assert notices.for_term('üb').query().count() == 1

    assert notices.for_term('Cat1').query().count() == 2
    assert notices.for_term('Cat2').query().count() == 1
    assert notices.for_term('Cat').query().count() == 3

    assert notices.for_term('Org1').query().count() == 1
    assert notices.for_term('Org').query().count() == 4

    assert notices.for_term('@example.org').query().count() == 3
    assert notices.for_term('ans').query().count() == 2

    assert notices.for_term('group').query().count() == 3
    assert notices.for_term('groupb').query().count() == 1

    assert notices.for_term('Cysat').query().count() == 1

    assert notices.for_term('Wynmärkt').query().count() == 1

    assert notices.for_term('Papanikolaou').query().count() == 1

    assert notices.for_term(str(notice.id).split('-')[0]).query().count() == 1
Пример #33
0
def test_notice_collection_users_and_groups(session):
    groups = UserGroupCollection(session)
    group_ab = groups.add(name='AB')
    group_c = groups.add(name='C')
    group_d = groups.add(name='D')

    users = UserCollection(session)
    user_a = users.add('*****@*****.**', 'password', 'editor', group=group_ab)
    user_b = users.add('*****@*****.**', 'password', 'editor', group=group_ab)
    user_c = users.add('*****@*****.**', 'password', 'editor', group=group_c)
    user_d = users.add('*****@*****.**', 'password', 'editor', group=group_d)
    user_e = users.add('*****@*****.**', 'password', 'editor')

    notices = OfficialNoticeCollection(session)
    for title, user in (
        ('A1', user_a),
        ('A2', user_a),
        ('A3', user_a),
        ('B1', user_b),
        ('B2', user_b),
        ('C1', user_c),
        ('C2', user_c),
        ('D1', user_d),
        ('D2', user_d),
        ('D3', user_d),
    ):
        notices.add(title=title,
                    text='text',
                    user_id=user.id,
                    group_id=user.group.id if user.group else None)

    assert notices.query().count() == 10

    # test users
    notices.user_ids = [user_a.id]
    assert sorted([n.title for n in notices.query()]) == ['A1', 'A2', 'A3']

    notices.user_ids = [user_b.id]
    assert sorted([n.title for n in notices.query()]) == ['B1', 'B2']

    notices.user_ids = [user_c.id]
    assert sorted([n.title for n in notices.query()]) == ['C1', 'C2']

    notices.user_ids = [user_d.id]
    assert sorted([n.title for n in notices.query()]) == ['D1', 'D2', 'D3']

    notices.user_ids = [user_e.id]
    assert sorted([n.title for n in notices.query()]) == []

    notices.user_ids = [user_b.id, user_c.id]
    assert sorted([n.title
                   for n in notices.query()]) == ['B1', 'B2', 'C1', 'C2']

    # test groups
    notices.user_ids = []

    notices.group_ids = [group_ab.id]
    assert sorted([n.title for n in notices.query()
                   ]) == ['A1', 'A2', 'A3', 'B1', 'B2']

    notices.group_ids = [group_c.id]
    assert sorted([n.title for n in notices.query()]) == ['C1', 'C2']

    notices.group_ids = [group_d.id]
    assert sorted([n.title for n in notices.query()]) == ['D1', 'D2', 'D3']

    notices.group_ids = [group_ab.id, group_d.id]
    assert sorted([n.title for n in notices.query()
                   ]) == ['A1', 'A2', 'A3', 'B1', 'B2', 'D1', 'D2', 'D3']

    # test users and groups
    notices.group_ids = [group_ab.id, group_d.id]
    notices.user_ids = [user_b.id, user_d.id]
    assert sorted([n.title for n in notices.query()
                   ]) == ['B1', 'B2', 'D1', 'D2', 'D3']
Пример #34
0
def get_user(request, username):
    return UserCollection(request.session).by_username(username)
Пример #35
0
def send_daily_ticket_statistics(request):

    today = replace_timezone(datetime.utcnow(), 'UTC')
    today = to_timezone(today, 'Europe/Zurich')

    if today.weekday() in (SAT, SUN):
        return

    args = {}

    # get the current ticket count
    collection = TicketCollection(request.app.session())
    count = collection.get_count()
    args['currently_open'] = count.open
    args['currently_pending'] = count.pending
    args['currently_closed'] = count.closed

    # get tickets created yesterday or on the weekend
    end = datetime(today.year, today.month, today.day, tzinfo=today.tzinfo)
    if today.weekday() == MON:
        start = end - timedelta(days=2)
    else:
        start = end - timedelta(days=1)

    query = collection.query()
    query = query.filter(Ticket.created >= start)
    query = query.filter(Ticket.created <= end)
    args['opened'] = query.count()

    query = collection.query()
    query = query.filter(Ticket.modified >= start)
    query = query.filter(Ticket.modified <= end)
    query = query.filter(Ticket.state == 'pending')
    args['pending'] = query.count()

    query = collection.query()
    query = query.filter(Ticket.modified >= start)
    query = query.filter(Ticket.modified <= end)
    query = query.filter(Ticket.state == 'closed')
    args['closed'] = query.count()

    # render the email
    args['title'] = request.translate(
        _("${town} OneGov Cloud Status", mapping={
            'town': request.app.town.name
        })
    )
    args['layout'] = DefaultMailLayout(object(), request)
    args['is_monday'] = today.weekday() == MON
    args['town'] = request.app.town.name
    content = render_template('mail_daily_ticket_statistics.pt', request, args)

    # send one e-mail per user
    users = UserCollection(request.app.session()).query()
    users = users.options(undefer('data'))
    users = users.all()

    for user in users:

        if user.data and not user.data.get('daily_ticket_statistics'):
            continue

        request.app.send_email(
            subject=args['title'],
            receivers=(user.username, ),
            content=content
        )
Пример #36
0
def test_permissions(wtfs_app, wtfs_password):
    session = wtfs_app.session()

    def permits(user, model, permission):
        return permits_by_app(wtfs_app, user, model, permission)

    # Remove existing users and group
    session.query(User).filter_by(realname='Editor').one().group_id = None
    session.query(User).filter_by(realname='Member').one().group_id = None
    session.query(Municipality).delete()

    # Add new
    municipality_a_id = uuid4()
    session.add(Municipality(
        id=municipality_a_id,
        name='Municipality A',
        bfs_number=10,
    ))
    session.add(PickupDate(
        date=date.today(),
        municipality_id=municipality_a_id,
    ))
    session.add(ScanJob(
        type='normal',
        municipality_id=municipality_a_id,
        delivery_number=1,
        dispatch_date=date(2019, 1, 1))
    )
    session.add(User(
        realname='Admin A',
        username='******',
        password_hash=wtfs_password,
        role='admin',
        group_id=municipality_a_id
    ))
    session.add(User(
        realname='Editor A',
        username='******',
        password_hash=wtfs_password,
        role='editor',
        group_id=municipality_a_id
    ))
    session.add(User(
        realname='Member A',
        username='******',
        password_hash=wtfs_password,
        role='member',
        group_id=municipality_a_id
    ))

    municipality_b_id = uuid4()
    session.add(Municipality(
        id=municipality_b_id,
        name='Municipality B',
        bfs_number=20,
    ))
    session.add(User(
        realname='Admin B',
        username='******',
        password_hash=wtfs_password,
        role='admin',
        group_id=municipality_b_id
    ))
    session.add(User(
        realname='Editor B',
        username='******',
        password_hash=wtfs_password,
        role='editor',
        group_id=municipality_b_id
    ))
    session.add(User(
        realname='Member B',
        username='******',
        password_hash=wtfs_password,
        role='member',
        group_id=municipality_b_id
    ))

    query = session.query
    admin = query(User).filter_by(realname='Admin').one()
    admin_a = query(User).filter_by(realname='Admin A').one()
    admin_b = query(User).filter_by(realname='Admin B').one()
    editor = query(User).filter_by(realname='Editor').one()
    editor_a = query(User).filter_by(realname='Editor A').one()
    editor_b = query(User).filter_by(realname='Editor B').one()
    member = query(User).filter_by(realname='Member').one()
    member_a = query(User).filter_by(realname='Member A').one()
    member_b = query(User).filter_by(realname='Member B').one()
    group = UserGroup()
    group_a = query(UserGroup).filter_by(name='Municipality A').one()
    group_b = query(UserGroup).filter_by(name='Municipality B').one()
    municipality = Municipality()
    municipality_a = query(Municipality).filter_by(name='Municipality A').one()
    municipality_b = query(Municipality).filter_by(name='Municipality B').one()
    scan_job = query(ScanJob).one()

    # General
    model = object()
    for user in (admin, admin_a, admin_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert permits(user, model, EditModelUnrestricted)
        assert permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, editor_a, editor_b, member, member_a, member_b):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert not permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)

    # UserGroupCollection / MunicipalityCollection
    # MunicipalityCollection
    for model in (
        MunicipalityCollection(session),
        UserGroupCollection(session)
    ):
        for user in (admin, admin_a, admin_b):
            assert permits(user, model, Public)
            assert permits(user, model, AddModel)
            assert permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert permits(user, model, EditModelUnrestricted)
            assert permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert permits(user, model, ViewModelUnrestricted)
        for user in (editor, editor_a, editor_b, member, member_a, member_b):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert not permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)

    # UserGroup / Municipality
    for user in (admin, admin_a, admin_b):
        for model in (group_a, group_b, municipality_a, municipality_b):
            assert permits(user, model, Public)
            assert permits(user, model, AddModel)
            assert permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert permits(user, model, ViewModelUnrestricted)
        for model in (group, municipality):
            assert permits(user, model, Public)
            assert permits(user, model, AddModel)
            assert permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert permits(user, model, EditModelUnrestricted)
            assert permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, editor_a, editor_b, member, member_a, member_b):
        for model in (
            group_a, group_b, group,
            municipality_a, municipality_b, municipality
        ):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert not permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)

    # UserCollection
    model = UserCollection(session)
    for user in (admin, admin_a, admin_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert permits(user, model, EditModelUnrestricted)
        assert permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, editor_a, editor_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)
    for user in (member, member_a, member_b):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert not permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)

    # User
    for user in (admin, admin_a, admin_b):
        for model in (admin, admin_a, admin_b):
            assert permits(user, model, Public)
            assert permits(user, model, AddModel)
            assert permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert permits(user, model, EditModelUnrestricted)
            if user == model:
                assert not permits(user, model, DeleteModel)
            else:
                assert permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert permits(user, model, ViewModelUnrestricted)
        for model in (editor, editor_a, editor_b, member, member_a, member_b):
            assert permits(user, model, Public)
            assert permits(user, model, AddModel)
            assert permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert permits(user, model, EditModelUnrestricted)
            assert permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, ):
        for model in (admin, admin_a, admin_b, editor_a, editor_b,
                      member, member_a, member_b):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert not permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
    for user in (editor, ):
        for model in (editor, ):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
    for user in (editor_a, ):
        for model in (admin, admin_a, admin_b, editor, editor_b,
                      member, member_b):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert not permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
        for model in (editor_a, ):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
        for model in (member_a,):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
    for user in (editor_b, ):
        for model in (admin, admin_a, admin_b, editor, editor_a,
                      member, member_a):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert not permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
        for model in (editor_b, ):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
        for model in (member_b,):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
    for user in (member, member_a, member_b):
        for model in (admin, admin_a, admin_b, editor, editor_a, editor_b,
                      member, member_a, member_b):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert not permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)

    # ScanJobCollection
    model = ScanJobCollection(session)
    for user in (admin, admin_a, admin_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert permits(user, model, EditModelUnrestricted)
        assert permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert permits(user, model, ViewModelUnrestricted)
    for user in (editor_a, editor_b, member_a, member_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)
    for user in (editor, member):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert not permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)

    # ScanJob
    model = scan_job
    for user in (admin, admin_a, admin_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert permits(user, model, EditModelUnrestricted)
        assert permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, editor_b, member, member_b):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert not permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)
    for user in (editor_a, member_a):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)

    # DailyList
    for model in (DailyList(), DailyListBoxes(session)):
        for user in (admin, admin_a, admin_b):
            assert permits(user, model, Public)
            assert permits(user, model, AddModel)
            assert permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert permits(user, model, EditModelUnrestricted)
            assert permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert permits(user, model, ViewModelUnrestricted)
        for user in (editor, editor_a, editor_b, member_a, member_b):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert not permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
        for user in (member,):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)
    for model in (DailyListBoxesAndForms(session), ):
        for user in (admin, admin_a, admin_b):
            assert permits(user, model, Public)
            assert permits(user, model, AddModel)
            assert permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert permits(user, model, EditModelUnrestricted)
            assert permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert permits(user, model, ViewModelUnrestricted)
        for user in (editor, editor_a, editor_b, member, member_a, member_b):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert not permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)

    # Report
    for model in (
        Report(session),
        ReportBoxes(session),
        ReportBoxesAndForms(session),
        ReportFormsByMunicipality(session)
    ):
        for user in (admin, admin_a, admin_b):
            assert permits(user, model, Public)
            assert permits(user, model, AddModel)
            assert permits(user, model, AddModelUnrestricted)
            assert permits(user, model, EditModel)
            assert permits(user, model, EditModelUnrestricted)
            assert permits(user, model, DeleteModel)
            assert permits(user, model, ViewModel)
            assert permits(user, model, ViewModelUnrestricted)
        for user in (editor, editor_a, editor_b, member, member_a, member_b):
            assert permits(user, model, Public)
            assert not permits(user, model, AddModel)
            assert not permits(user, model, AddModelUnrestricted)
            assert not permits(user, model, EditModel)
            assert not permits(user, model, EditModelUnrestricted)
            assert not permits(user, model, DeleteModel)
            assert not permits(user, model, ViewModel)
            assert not permits(user, model, ViewModelUnrestricted)

    # Notification
    model = Notification()
    for user in (admin, admin_a, admin_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert permits(user, model, EditModelUnrestricted)
        assert permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, editor_a, editor_b, member, member_a, member_b):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)

    # Invoice
    model = Invoice(session)
    for user in (admin, admin_a, admin_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert permits(user, model, EditModelUnrestricted)
        assert permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, editor_a, editor_b, member, member_a, member_b):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert not permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)

    # PaymentType
    model = PaymentType()
    for user in (admin, admin_a, admin_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert permits(user, model, EditModelUnrestricted)
        assert permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, editor_a, editor_b, member, member_a, member_b):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert not permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)

    # PaymentTypeCollection
    model = PaymentTypeCollection(session)
    for user in (admin, admin_a, admin_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert permits(user, model, EditModelUnrestricted)
        assert permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, editor_a, editor_b, member, member_a, member_b):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert not permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)

    # UserManual
    model = UserManual(wtfs_app)
    for user in (admin, admin_a, admin_b):
        assert permits(user, model, Public)
        assert permits(user, model, AddModel)
        assert permits(user, model, AddModelUnrestricted)
        assert permits(user, model, EditModel)
        assert permits(user, model, EditModelUnrestricted)
        assert permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert permits(user, model, ViewModelUnrestricted)
    for user in (editor, editor_a, editor_b, member, member_a, member_b):
        assert permits(user, model, Public)
        assert not permits(user, model, AddModel)
        assert not permits(user, model, AddModelUnrestricted)
        assert not permits(user, model, EditModel)
        assert not permits(user, model, EditModelUnrestricted)
        assert not permits(user, model, DeleteModel)
        assert permits(user, model, ViewModel)
        assert not permits(user, model, ViewModelUnrestricted)
Пример #37
0
def test_notice_collection_order(session):
    groups = UserGroupCollection(session)
    group_c = groups.add(name='C').id
    group_d = groups.add(name='D').id

    users = UserCollection(session)
    user_a = users.add('*****@*****.**', 'password', 'editor', realname='o').id
    user_b = users.add('*****@*****.**', 'password', 'editor', realname='p').id
    user_c = users.add('*****@*****.**', 'password', 'editor').id

    date_1 = datetime(2007, 10, 10, tzinfo=timezone.utc)
    date_2 = datetime(2007, 11, 11, tzinfo=timezone.utc)
    date_3 = datetime(2007, 12, 12, tzinfo=timezone.utc)

    notices = OfficialNoticeCollection(session)
    for title, text, user, group, organization, category, first_issue in (
        ('A', 'g', user_a, group_c, 'p', 'X', date_1),
        ('B', 'g', user_b, group_d, 'q', 'X', date_1),
        ('B', 'h', None, None, 'p', 'X', date_2),
        ('C', 'h', user_a, None, 'q', 'X', date_1),
        ('D', 'i', user_b, group_d, 'p', 'Y', date_1),
        ('E', 'j', user_c, group_c, 'q', 'Y', date_3),
    ):
        notices.add(
            title=title,
            text=text,
            user_id=user,
            group_id=group,
            organization=organization,
            category=category,
            first_issue=first_issue,
        )

    # Default ordering by issue date
    result = [n.first_issue for n in notices.query()]
    assert result == [date_1, date_1, date_1, date_1, date_2, date_3]

    # Explicit direction
    result = [n.title for n in notices.for_order('title', 'asc').query()]
    assert result == ['A', 'B', 'B', 'C', 'D', 'E']

    result = [n.title for n in notices.for_order('title', 'desc').query()]
    assert result == ['E', 'D', 'C', 'B', 'B', 'A']

    result = [n.title for n in notices.for_order('title', '').query()]
    assert result == ['A', 'B', 'B', 'C', 'D', 'E']

    result = [n.title for n in notices.for_order('title', 'xxx').query()]
    assert result == ['A', 'B', 'B', 'C', 'D', 'E']

    # Default direction
    # ... default
    result = [
        n.title
        for n in notices.for_order('text', 'desc').for_order('title').query()
    ]
    assert result == ['A', 'B', 'B', 'C', 'D', 'E']

    # ... flip direction
    result = [
        n.title
        for n in notices.for_order('title', 'asc').for_order('title').query()
    ]
    assert result == ['E', 'D', 'C', 'B', 'B', 'A']

    # Invalid
    result = [n.first_issue for n in notices.for_order('result').query()]
    assert result == [date_1, date_1, date_1, date_1, date_2, date_3]

    result = [n.first_issue for n in notices.for_order('users').query()]
    assert result == [date_1, date_1, date_1, date_1, date_2, date_3]

    result = [n.first_issue for n in notices.for_order(None).query()]
    assert result == [date_1, date_1, date_1, date_1, date_2, date_3]

    # Valid
    result = [n.text for n in notices.for_order('text').query()]
    assert result == ['g', 'g', 'h', 'h', 'i', 'j']

    # ... user_id
    result = [n.user_id for n in notices.for_order('user_id').query()]
    assert result == sorted(2 * [user_a] + 2 * [user_b] + [user_c]) + [None]

    # ... organization
    result = [
        n.organization for n in notices.for_order('organization').query()
    ]
    assert result == ['p', 'p', 'p', 'q', 'q', 'q']

    # ... category
    result = [n.category for n in notices.for_order('category').query()]
    assert result == ['X', 'X', 'X', 'X', 'Y', 'Y']

    # ... name
    result = [n.name for n in notices.for_order('name').query()]
    assert result == ['a', 'b', 'b-1', 'c', 'd', 'e']

    # ... group.name
    result = [
        n.group.name if n.group else None
        for n in notices.for_order('group.name').query()
    ]
    assert result == [None, None, 'C', 'C', 'D', 'D']

    # ... user.name(s)
    result = [
        n.user.realname if n.user else None
        for n in notices.for_order('user.realname').query()
    ]
    assert result == [None, None, 'o', 'o', 'p', 'p']

    result = [
        n.user.username if n.user else None
        for n in notices.for_order('user.username').query()
    ]
    assert result == [
        None, '*****@*****.**', '*****@*****.**', '*****@*****.**',
        '*****@*****.**', '*****@*****.**'
    ]

    result = [
        n.user.realname or n.user.username if n.user else None
        for n in notices.for_order('user.name').query()
    ]
    assert result == [None, '*****@*****.**', 'o', 'o', 'p', 'p']