Exemplo n.º 1
0
class SitePoweredForm(BaseForm):
    site_id = validators.Int(not_empty=True)
    projects = validators.Set(not_empty=True, use_set=True)
    powered_projects = validators.PlainText()

    def __after__(self):
        try:
            values = []
            del_values = []
            if self._values["powered_projects"] is not None:
                powered_projects = self._values["powered_projects"].split("-")
            else:
                powered_projects = []

            for project in self._values["projects"]:
                if project not in powered_projects:
                    values.append((self._values["site_id"], project))

            for project in powered_projects:
                if project not in self._values["projects"]:
                    del_values.append((self._values["site_id"], project))


            self._handler.db.executemany("INSERT INTO project_sites (site_id, project_id) "
                                         "VALUES (%s, %s)", values)
            if del_values:
                self._handler.db.executemany("DELETE from project_sites where site_id = %s and project_id = %s", del_values)

            if values or del_values:
                self._handler.db.execute("UPDATE site SET updated = UTC_TIMESTAMP() where id = %s", self._values["site_id"])

        except Exception, e:
            logging.error(str(e))
            self.add_error("projects", "Submit powered by information error, please try it later.")
Exemplo n.º 2
0
class ProfileSchema(Schema):
    allow_extra_fields = True
    filter_extra_fields = True

    if_key_missing = None

    profile = ProfileBaseSchema()
    descriptions = ciocvalidators.CultureDictSchema(ProfileDescriptionSchema())
    Views = All(validators.Set(use_set=True), ForEach(ciocvalidators.IDValidator()))
    Fields = ForEach(FieldOrderSchema())
Exemplo n.º 3
0
class CrimeSchema(Schema):
    """
    Crime Form schema
    """

    allow_extra_fields = True
    filter_extra_fields = True

    category_name = validators.UnicodeString()
    category_pretty_name = validators.UnicodeString()
    description = validators.UnicodeString()
    default_token = validators.UnicodeString()
    tokens = validators.Set()
    date = datetime.datetime.now()
    color = validators.UnicodeString()
Exemplo n.º 4
0
class UpdatePubsSchema(Schema):
    allow_extra_fields = True
    filter_extra_fields = True

    if_key_missing = None

    descriptions = ciocvalidators.CultureDictSchema(
        UpdatePubsDescriptionSchema(),
        pre_validators=[ciocvalidators.DeleteKeyIfEmpty()],
    )
    GHID = All(validators.Set(use_set=True),
               ForEach(ciocvalidators.IDValidator()))
    DeleteFeedback = validators.DictConverter({
        "Y": True,
        "N": False
    },
                                              if_empty=False,
                                              if_missing=False)
Exemplo n.º 5
0
 class CorrectSetTestPipeSchema(StrictSchema):
     field = compound.Pipe(validators.Set(not_empty=True),
         foreach.ForEach(validators.UnicodeString(not_empty=True)))
Exemplo n.º 6
0
 class CorrectSetTestSchema(StrictSchema):
     field = validators.Set(not_empty=True)
Exemplo n.º 7
0
class DefaultAdminController(BaseController, AdminControllerMixin):
    """Provides basic admin functionality for an :class:`Application`.

    To add more admin functionality for your Application, extend this
    class and then assign an instance of it to the ``admin`` attr of
    your Application::

        class MyApp(Application):
            def __init__(self, *args):
                super(MyApp, self).__init__(*args)
                self.admin = MyAdminController(self)

    """
    def __init__(self, app):
        """Instantiate this controller for an :class:`app <Application>`.

        """
        super(DefaultAdminController, self).__init__()
        self.app = app
        self.webhooks = WebhooksLookup(app)

    @expose()
    def index(self, **kw):
        """Home page for this controller.

        Redirects to the 'permissions' page by default.

        """
        permanent_redirect('permissions')

    @expose('json:')
    @require_post()
    def block_user(self, username, perm, reason=None, **kw):
        if not username or not perm:
            return dict(error='Enter username')
        user = model.User.by_username(username)
        if not user:
            return dict(error='User "%s" not found' % username)
        ace = model.ACE.deny(
            model.ProjectRole.by_user(user, upsert=True)._id, perm, reason)
        if not model.ACL.contains(ace, self.app.acl):
            self.app.acl.append(ace)
            return dict(user_id=str(user._id),
                        username=user.username,
                        reason=reason)
        return dict(error='User "%s" already blocked' % user.username)

    @validate(dict(user_id=V.Set(), perm=V.UnicodeString()))
    @expose('json:')
    @require_post()
    def unblock_user(self, user_id=None, perm=None, **kw):
        try:
            user_id = map(ObjectId, user_id)
        except InvalidId:
            user_id = []
        users = model.User.query.find({'_id': {'$in': user_id}}).all()
        if not users:
            return dict(error='Select user to unblock')
        unblocked = []
        for user in users:
            ace = model.ACE.deny(model.ProjectRole.by_user(user)._id, perm)
            ace = model.ACL.contains(ace, self.app.acl)
            if ace:
                self.app.acl.remove(ace)
                unblocked.append(str(user._id))
        return dict(unblocked=unblocked)

    @expose('jinja:allura:templates/app_admin_permissions.html')
    @without_trailing_slash
    def permissions(self):
        """Render the permissions management web page.

        """
        from ext.admin.widgets import PermissionCard, BlockUser, BlockList
        c.card = PermissionCard()
        c.block_user = BlockUser()
        c.block_list = BlockList()
        permissions = dict((p, []) for p in self.app.permissions)
        block_list = defaultdict(list)
        for ace in self.app.config.acl:
            if ace.access == model.ACE.ALLOW:
                try:
                    permissions[ace.permission].append(ace.role_id)
                except KeyError:
                    # old, unknown permission
                    pass
            elif ace.access == model.ACE.DENY:
                role = model.ProjectRole.query.get(_id=ace.role_id)
                if role.name is None and role.user:
                    block_list[ace.permission].append((role.user, ace.reason))
        return dict(app=self.app,
                    allow_config=has_access(c.project, 'admin')(),
                    permissions=permissions,
                    block_list=block_list)

    @expose('jinja:allura:templates/app_admin_edit_label.html')
    def edit_label(self):
        """Renders form to update the Application's ``mount_label``.

        """
        return dict(app=self.app,
                    allow_config=has_access(self.app, 'configure')())

    @expose()
    @require_post()
    def update_label(self, mount_label):
        """Handles POST to update the Application's ``mount_label``.

        """
        require_access(self.app, 'configure')
        self.app.config.options['mount_label'] = mount_label
        g.post_event('project_menu_updated')
        redirect(request.referer)

    @expose('jinja:allura:templates/app_admin_options.html')
    def options(self):
        """Renders form to update the Application's ``config.options``.

        """
        return dict(app=self.app,
                    allow_config=has_access(self.app, 'configure')())

    @expose('jinja:allura:templates/app_admin_delete.html')
    def delete(self):
        return dict(app=self.app)

    @expose()
    @require_post()
    def configure(self, **kw):
        """Handle POST to delete the Application or update its
        ``config.options``.

        """
        with h.push_config(c, app=self.app):
            require_access(self.app, 'configure')
            is_admin = self.app.config.tool_name == 'admin'
            if kw.pop('delete', False):
                if is_admin:
                    flash('Cannot delete the admin tool, sorry....')
                    redirect('.')
                c.project.uninstall_app(self.app.config.options.mount_point)
                redirect('..')
            for opt in self.app.config_options:
                if opt in Application.config_options:
                    # skip base options (mount_point, mount_label, ordinal)
                    continue
                val = kw.get(opt.name, '')
                if opt.ming_type == bool:
                    val = asbool(val or False)
                elif opt.ming_type == int:
                    val = asint(val or 0)
                try:
                    val = opt.validate(val)
                except fev.Invalid as e:
                    flash(u'{}: {}'.format(opt.name, str(e)), 'error')
                    continue
                self.app.config.options[opt.name] = val
            if is_admin:
                # possibly moving admin mount point
                redirect('/' + c.project._id +
                         self.app.config.options.mount_point + '/' +
                         self.app.config.options.mount_point + '/')
            else:
                redirect(request.referer)

    @without_trailing_slash
    @expose()
    @h.vardec
    @require_post()
    def update(self, card=None, **kw):
        """Handle POST to update permissions for the Application.

        """
        old_acl = self.app.config.acl
        self.app.config.acl = []
        for args in card:
            perm = args['id']
            new_group_ids = args.get('new', [])
            del_group_ids = []
            group_ids = args.get('value', [])
            if isinstance(new_group_ids, basestring):
                new_group_ids = [new_group_ids]
            if isinstance(group_ids, basestring):
                group_ids = [group_ids]

            for acl in old_acl:
                if (acl['permission'] == perm
                        and str(acl['role_id']) not in group_ids
                        and acl['access'] != model.ACE.DENY):
                    del_group_ids.append(str(acl['role_id']))

            def get_role(_id):
                return model.ProjectRole.query.get(_id=ObjectId(_id))

            groups = map(get_role, group_ids)
            new_groups = map(get_role, new_group_ids)
            del_groups = map(get_role, del_group_ids)

            if new_groups or del_groups:
                model.AuditLog.log(
                    'updated "%s" permission: "%s" => "%s" for %s' %
                    (perm, ', '.join(
                        map(lambda role: role.name,
                            filter(None, groups + del_groups))), ', '.join(
                                map(lambda role: role.name,
                                    filter(None, groups + new_groups))),
                     self.app.config.options['mount_point']))

            role_ids = map(ObjectId, group_ids + new_group_ids)
            self.app.config.acl += [model.ACE.allow(r, perm) for r in role_ids]

            # Add all ACEs for user roles back
            for ace in old_acl:
                if (ace.permission == perm) and (ace.access == model.ACE.DENY):
                    self.app.config.acl.append(ace)
        redirect(request.referer)
Exemplo n.º 8
0
class AdminViewBase(ViewBase):
    def __init__(self, request, require_login=True):
        ViewBase.__init__(self, request, require_login)


domain_validator = validators.DictConverter(
    {
        str(const.DMT_CIC.id): const.DMT_CIC,
        str(const.DMT_VOL.id): const.DMT_VOL
    },
    if_invalid=None,
    if_empty=None,
)

ShowCultures = All(
    validators.Set(use_set=True),
    ForEach(ciocvalidators.ActiveCulture(record_cultures=True)),
    if_invalid=None,
    if_empty=None,
)

ShowCulturesOnlyActive = All(
    validators.Set(use_set=True),
    ForEach(ciocvalidators.ActiveCulture(record_cultures=False)),
    if_invalid=None,
    if_empty=None,
)


def cull_extra_cultures(desc_key,
                        multi_key=None,