Beispiel #1
0
 def make_remove_link(self, user):
     if user.removed is not None:
         return XML('<a class="btn" href="unremove?id=%s">'
                    '<i class="fa fa-plus"/> Re-Add</a>' % user.user_id)
     else:
         return XML('<a class="btn" href="remove?id=%s">'
                    '<i class="fa fa-times"/> Remove</a>' % user.user_id)
Beispiel #2
0
 def make_lc_remove_link(self, lc):
     if lc.removed is not None:
         return XML('<a class="btn" href="unremove?id=%s">'
                    '<i class="fa fa-plus"/> Re-Add</a>' % lc.id)
     else:
         return XML(
             '<a class="btn" href="#" onclick="has_watchdog(\'%s\')">'
             '<i class="fa fa-times"/> Remove</a>' % lc.id)
Beispiel #3
0
 def show_ownership_status(member):
     is_owner = member.is_owner
     if can_edit:
         if is_owner:
             return XML('<a class="btn change_ownership_remove" '
                        'href="revoke_owner?group_id=%s&amp;id=%s">'
                        '<i class="fa fa-times"/> Remove</a>' %
                        (group.group_id, member.user_id))
         else:
             return XML('<a class="btn change_ownership_add" '
                        'href="grant_owner?group_id=%s&amp;id=%s">'
                        '<i class="fa fa-plus"/> Add</a>' %
                        (group.group_id, member.user_id))
     else:
         is_owner = 'Yes' if is_owner else 'No'
         return is_owner
Beispiel #4
0
 def adapt_output(self, output, destination):
     # Handle rendering strings on Genshi so they're not escaped
     if isinstance(output, basestring) and destination == 'genshi':
         from genshi.input import HTML
         output = HTML(output)
     # Handle rendering strings on Kid so they're not escaped
     elif isinstance(output, basestring) and destination == 'kid':
         from kid import XML
         output = XML(output)
     return output
Beispiel #5
0
def markdown_first_paragraph(text):
    try:
        rendered = markdown(text, safe_mode='escape')
        # Extract the contents of the first <p>
        root = lxml.etree.fromstring('<div>' + rendered + '</div>')
        first_para = root.find('p')
        html_content = ''.join([xml_escape(first_para.text or '')] + [
            lxml.etree.tostring(child) for child in first_para.iterchildren()
        ] + [xml_escape(first_para.tail or '')])
        return XML(html_content)
    except Exception:
        return text
Beispiel #6
0
    def edit(self, group_id=None, group_name=None, **kw):
        # Not just for editing, also provides a read-only view
        if group_id is not None:
            try:
                group = Group.by_id(group_id)
            except DatabaseLookupError:
                log.exception('Group id %s is not a valid group id' % group_id)
                flash(_(u'Need a valid group to search on'))
                redirect('../groups/mine')
        elif group_name is not None:
            try:
                group = Group.by_name(group_name)
            except NoResultFound:
                log.exception('Group name %s is not a valid group name' %
                              group_name)
                flash(_(u'Need a valid group to search on'))
                redirect('../groups/mine')
        else:
            redirect('../groups/mine')

        usergrid = self.show_members(group)

        can_edit = False
        if identity.current.user:
            can_edit = group.can_edit(identity.current.user)

        permissions_fields = [('Permission', lambda x: x.permission_name)]
        if can_edit:
            permissions_fields.append((' ', lambda x: XML(
                '<a class="btn" href="#" id="remove_permission_%s">'
                '<i class="fa fa-times"/> Remove</a>' % x.permission_id)))
        group_permissions_grid = BeakerDataGrid(name='group_permission_grid',
                                                fields=permissions_fields)
        group_permissions = GroupPermissions()

        return dict(
            form=self.group_form,
            user_form=self.group_user_form,
            group_edit_js=LocalJSLink('bkr',
                                      '/static/javascript/group_users_v2.js'),
            action='./save',
            user_action='./save_user',
            options={},
            value=group,
            group_pw=group.root_password,
            usergrid=usergrid,
            disabled_fields=[],
            group_permissions=group_permissions,
            group_form=self.permissions_form,
            group_permissions_grid=group_permissions_grid,
        )
Beispiel #7
0
def make_remove_link(id):
    # make a remove link
    return XML('<a class="btn" href="remove?id=%s">'
               '<i class="fa fa-times"/> Remove</a>' % id)
Beispiel #8
0
class CSV(RPCRoot):
    # For XMLRPC methods in this class.
    exposed = False

    export_help_text = XML(
        u'<span>Refer to the <a href="http://beaker-project.org/docs/'
        'admin-guide/interface.html#export" target="_blank">'
        'documentation</a> to learn more about the exported data.</span>'
    ).expand()
    import_help_text = XML(
        u'<span>Refer to the <a href="http://beaker-project.org/docs/'
        'admin-guide/interface.html#import" target="_blank">'
        'documentation</a> for details about the supported CSV format.</span>'
    ).expand()

    upload     = widgets.FileField(name='csv_file', label='Import CSV', \
                                   help_text = import_help_text)
    download = RadioButtonList(name='csv_type',
                               label='CSV Type',
                               options=[
                                   ('system', 'Systems'),
                                   ('system_id', 'Systems (for modification)'),
                                   ('labinfo', 'System LabInfo'),
                                   ('power', 'System Power'),
                                   ('exclude', 'System Excluded Families'),
                                   ('install', 'System Install Options'),
                                   ('keyvalue', 'System Key/Values'),
                                   ('system_pool', 'System Pools'),
                                   ('user_group', 'User Groups')
                               ],
                               default='system',
                               help_text=export_help_text)

    importform = HorizontalForm(
        'import',
        fields=[upload],
        action='import data',
        submit_text=_(u'Import CSV'),
    )

    exportform = HorizontalForm(
        'export',
        fields=[download],
        action='export data',
        submit_text=_(u'Export CSV'),
    )

    @expose(template='bkr.server.templates.form')
    @identity.require(identity.not_anonymous())
    def index(self, **kw):
        return dict(
            form=self.exportform,
            title=_(u'CSV Export'),
            action='./action_export',
            options={},
            value=kw,
        )

    @expose(template='bkr.server.templates.form-post')
    @identity.require(identity.in_group('admin'))
    def csv_import(self, **kw):
        return dict(
            form=self.importform,
            title=_(u'CSV Import'),
            action='./action_import',
            options={},
            value=kw,
        )

    @expose()
    @identity.require(identity.not_anonymous())
    def action_export(self, csv_type, *args, **kw):
        file = NamedTemporaryFile()
        log = self.to_csv(file, csv_type)
        file.seek(0)

        return serve_file(file.name,
                          contentType="text/csv",
                          disposition="attachment",
                          name="%s.csv" % csv_type)

    def _import_row(self, data, log):
        if data['csv_type'] in system_types and ('fqdn' in data
                                                 or 'id' in data):
            if data.get('id', None):
                try:
                    system = System.query.filter(System.id == data['id']).one()
                except InvalidRequestError as e:
                    raise ValueError('Non-existent system id')
            else:
                try:
                    system = System.query.filter(
                        System.fqdn == data['fqdn']).one()
                except InvalidRequestError:
                    # Create new system with some defaults
                    # Assume the system is broken until proven otherwise.
                    # Also assumes its a machine.  we have to pick something
                    system = System(fqdn=data['fqdn'],
                                    owner=identity.current.user,
                                    type=SystemType.machine,
                                    status=SystemStatus.broken)
                    session.add(system)
                    # new systems are visible to everybody by default
                    system.custom_access_policy = SystemAccessPolicy()
                    system.custom_access_policy.add_rule(SystemPermission.view,
                                                         everybody=True)
            if not system.can_edit(identity.current.user):
                raise ValueError('You are not the owner of %s' % system.fqdn)
            # we change the FQDN only when a valid system id is supplied
            if not data.get('id', None):
                data.pop('fqdn')
            self.from_csv(system, data, log)
        elif data['csv_type'] == 'user_group' and 'user' in data:
            user = User.by_user_name(data['user'])
            if user is None:
                raise ValueError('%s is not a valid user' % data['user'])
            CSV_GroupUser.from_csv(user, data, log)
        else:
            raise ValueError('Invalid csv_type %s or missing required fields' %
                             data['csv_type'])

    @expose(template='bkr.server.templates.csv_import')
    @identity.require(identity.in_group('admin'))
    def action_import(self, csv_file, *args, **kw):
        """
        TurboGears method to import data from csv
        """

        log = []
        try:
            # ... process CSV file contents here ...
            missing = object()
            reader = UnicodeDictReader(csv_file.file,
                                       restkey=missing,
                                       restval=missing)
            is_empty = True

            for data in reader:

                is_empty = False

                if missing in data:
                    log.append('Too many fields on line %s (expecting %s)' %
                               (reader.line_num, len(reader.fieldnames)))
                    continue
                if any(value is missing for value in data.itervalues()):
                    missing_fields = [
                        field for field, value in data.iteritems()
                        if value is missing
                    ]
                    log.append('Missing fields on line %s: %s' %
                               (reader.line_num, ', '.join(missing_fields)))
                    continue
                if 'csv_type' not in data:
                    log.append('Missing csv_type on line %s' % reader.line_num)
                    continue
                try:
                    with session.begin_nested():
                        self._import_row(data, log)
                except Exception, e:
                    # log and continue processing more rows
                    log.append('Error importing line %s: %s' %
                               (reader.line_num, e))

            if is_empty:
                log.append('Empty CSV file supplied')

        except csv.Error, e:
            session.rollback()
            log.append('Error parsing CSV file: %s' % e)
Beispiel #9
0
 def show_delete(x):
     if x.can_delete():
         return XML('<a class="btn" href="./delete/%s">'
                 '<i class="fa fa-times"/> Delete</a>' % x.id)
     else:
         return None
Beispiel #10
0
 def remove_button(member):
     return XML(
         '<a class="btn" href="removeUser?group_id=%s&amp;id=%s">'
         '<i class="fa fa-times"/> Remove</a>' %
         (group.group_id, member.user_id))