Пример #1
0
def get_admin_users(sort: List[Tuple[str, int]] = None,
                    active_only: bool = True) -> Iterator[_model.AbstractUser]:
    """Get admin users
    """
    if sort is None:
        sort = [('created', 1)]

    q = query.Query(query.Eq('roles', get_role('admin')))
    if active_only:
        q.add(query.Eq('status', 'active'))

    return find_users(q, sort)
    def _get_query(self) -> query.Query:
        q = query.Query()

        if not auth.get_current_user().is_admin:
            q.add(query.Eq('status', 'active'))
            q.add(query.Eq('is_public', True))

        search = self.arg('q')
        if search:
            q.add(query.Or([
                query.Regex('first_name', search, True),
                query.Regex('last_name', search, True),
            ]))

        return q
Пример #3
0
    def exec(self):
        reporter = auth.get_current_user()
        if reporter.is_anonymous:
            raise self.forbidden()

        model = self.arg('model')

        try:
            entity = _api.dispense(model, self.arg('uid'))
        except odm.error.EntityNotFound:
            raise self.not_found()

        tpl_name = 'content@mail/{}/abuse'.format(lang.get_current())
        subject = lang.t('content@mail_subject_abuse')
        for recipient in auth.find_users(
                query.Query(query.Eq('status', 'active'))):
            if not entity.odm_auth_check_entity_permissions(
                [PERM_MODIFY, PERM_DELETE], recipient):
                continue

            body = tpl.render(tpl_name, {
                'reporter': reporter,
                'recipient': recipient,
                'entity': entity
            })
            mail.Message(entity.author.login, subject, body).send()

        return {'message': lang.t('content@abuse_receipt_confirm')}
Пример #4
0
    def delete(self):
        from . import _api

        # Check if the role is used by users
        user = _api.find_user(query.Query(query.Eq('roles', self)))
        if user:
            raise errors.ForbidDeletion(lang.t('role_used_by_user', {'role': self, 'user': user.login}))

        events.fire('auth@role_pre_delete', user=self)
        self.do_delete()
        events.fire('auth@role_delete', user=self)

        return self
Пример #5
0
    def _do_validate(self):
        self._q.add(query.Eq(self._field_name, self.value))

        if self._e_type == 'role':
            if _api.find_role(self._q):
                raise validation.RuleError(
                    'auth@{}_{}_already_taken'.format(self._e_type,
                                                      self._field_name),
                    {'value': self.value})
        elif self._e_type == 'user':
            if _api.find_user(self._q):
                raise validation.RuleError(
                    'auth@{}_{}_already_taken'.format(self._e_type,
                                                      self._field_name),
                    {'value': self.value})
Пример #6
0
def comments_report_comment(uid: str):
    try:
        comment = comments.get_comment(uid, 'pytsite')
    except comments.error.CommentNotExist:
        return

    tpl_name = 'comments_odm@mail/{}/report'.format(lang.get_current())
    m_subject = lang.t('comments_odm@mail_subject_report_comment')

    for user in auth.find_users(query.Query(query.Eq('status', 'active'))):
        if not user.has_permission('*****@*****.**'):
            continue

        m_body = tpl.render(tpl_name, {'comment': comment, 'recipient': user})
        mail.Message(user.login, m_subject, m_body).send()
Пример #7
0
    def exec(self) -> list:
        uids = self.arg('uids')
        exclude = self.arg('exclude')
        search = self.arg('search') or self.arg('q')

        r = []

        if uids:
            for uid in self.arg('uids'):
                try:
                    user = auth.get_user(uid=uid)
                    json = user.as_jsonable()
                    events.fire('auth_http_api@get_user', user=user, json=json)
                    r.append(json)

                except Exception as e:
                    # Any exception is ignored due to safety reasons
                    logger.warn(e)
        elif search and reg.get('auth_http_api.search', False):
            q = query.Query()
            q.add(
                query.Or([
                    query.Regex('first_name', '^{}'.format(search), True),
                    query.Regex('last_name', '^{}'.format(search), True),
                ]))

            if not auth.get_current_user().is_admin:
                q.add(query.Eq('is_public', True))

            if exclude:
                q.add(query.Nin('uid', exclude))

            for user in auth.find_users(q,
                                        limit=self.arg('limit'),
                                        skip=self.arg('skip')):
                r.append(user.as_jsonable())

        return r
Пример #8
0
    def exec(self):
        try:
            # Search for user
            user = next(
                auth.find_users(
                    query.Query(query.Eq('confirmation_hash',
                                         self.arg('code')))))
        except StopIteration:
            # No user found, redirect to sign in URL
            return self.redirect(_api.sign_in_url(redirect=router.base_url()))

        try:
            auth.switch_user_to_system()
            user.confirmation_hash = None
            if user.status == auth.USER_STATUS_WAITING:
                user.status = auth.get_new_user_status()
            user.save()
        finally:
            auth.restore_user()

        router.session().add_success_message(
            lang.t('auth_ui@registration_confirm_success'))

        return self.redirect(_api.sign_in_url(redirect=router.base_url()))
Пример #9
0
 def or_eq(self, field: str, arg):
     """Shortcut
     """
     return self.add(qu.Or(qu.Eq(field, arg)))
Пример #10
0
    def exec(self):
        """Execute teh command
        """
        model = self.arg(0)

        # Checking if the content model registered
        if not _api.is_model_registered(model):
            raise console.error.CommandExecutionError("'{}' is not a registered content model".format(model))

        author_login = self.opt('author')
        num = self.opt('num')
        images_num = self.opt('images')
        language = self.opt('lang')
        no_html = self.opt('no-html')
        short = self.opt('short')
        title_len = self.opt('title-len')
        description_len = self.opt('description-len')

        if no_html:
            self.lorem_txt_args['format'] = 'text'

        if short:
            self.lorem_txt_args['paras'] = 1

        users = list(auth.find_users(query.Query(query.Eq('status', 'active')), limit=10))

        # Generate content entities
        for m in range(0, num):
            entity = _api.dispense(model)

            # Author
            if entity.has_field('author'):
                if author_login:
                    author = auth.get_user(author_login)
                    if not author:
                        raise console.error.CommandExecutionError("'{}' is not a registered user".format(author_login))
                else:
                    if not users:
                        raise console.error.CommandExecutionError(lang.t('content@no_users_found'))
                    rand = randint(0, len(users) - 1)
                    author = users[rand:rand + 1][0]

                entity.f_set('author', author.uid)

            # Title
            if entity.has_field('title'):
                entity.f_set('title', self._generate_title(title_len))

            # Description
            if entity.has_field('description'):
                entity.f_set('description', self._generate_title(description_len))

            # Body
            if entity.has_field('body'):
                body = []
                for n in range(1, (images_num or 1) + 1):
                    body.append(requests.get(self.lorem_txt_url, self.lorem_txt_args).content.decode('utf-8'))
                    if not no_html and n > 1:
                        body.append('\n<p>[img:{}]</p>\n'.format(n))

                entity.f_set('body', ''.join(body))

            # Images
            if entity.has_field('images') and images_num:
                for n in range(0, images_num):
                    entity.f_add('images', file.create(self.lorem_img_url.format(randint(0, 1000))))

            # Language
            if entity.has_field('language'):
                entity.f_set('language', language)

            # Status
            if entity.has_field('status'):
                entity.f_set('status', CONTENT_STATUS_PUBLISHED)

            events.fire('content@generate', entity=entity)

            entity.save()

            console.print_info(lang.t('content@new_content_created', {'model': entity.model, 'title': entity.title}))