Exemplo n.º 1
0
 def index(self, trans, deleted='False', **kwd):
     """
     GET /api/users
     GET /api/users/deleted
     Displays a collection (list) of users.
     """
     rval = []
     query = trans.sa_session.query(trans.app.model.User)
     deleted = util.string_as_bool(deleted)
     if deleted:
         route = 'deleted_user'
         query = query.filter(trans.app.model.User.table.c.deleted == True)
         # only admins can see deleted users
         if not trans.user_is_admin():
             return []
     else:
         route = 'user'
         query = query.filter(trans.app.model.User.table.c.deleted == False)
         # special case: user can see only their own user
         if not trans.user_is_admin():
             item = trans.user.get_api_value(
                 value_mapper={'id': trans.security.encode_id})
             item['url'] = url_for(route, id=item['id'])
             return item
     for user in query:
         item = user.get_api_value(
             value_mapper={'id': trans.security.encode_id})
         item['url'] = url_for(route, id=item['id'])
         rval.append(item)
     return rval
Exemplo n.º 2
0
    def index(self, trans, **kwd):
        """
        GET /api/workflows

        Displays a collection of workflows.
        """
        rval = []
        for wf in trans.sa_session.query(
                trans.app.model.StoredWorkflow).filter_by(
                    user=trans.user, deleted=False).order_by(
                        desc(trans.app.model.StoredWorkflow.table.c.update_time
                             )).all():
            item = wf.get_api_value(
                value_mapper={'id': trans.security.encode_id})
            encoded_id = trans.security.encode_id(wf.id)
            item['url'] = url_for('workflow', id=encoded_id)
            rval.append(item)
        for wf_sa in trans.sa_session.query(
                trans.app.model.StoredWorkflowUserShareAssociation
        ).filter_by(user=trans.user).join('stored_workflow').filter(
                trans.app.model.StoredWorkflow.deleted == False).order_by(
                    desc(trans.app.model.StoredWorkflow.update_time)).all():
            item = wf_sa.stored_workflow.get_api_value(
                value_mapper={'id': trans.security.encode_id})
            encoded_id = trans.security.encode_id(wf_sa.stored_workflow.id)
            item['url'] = url_for('workflow', id=encoded_id)
            rval.append(item)
        return rval
Exemplo n.º 3
0
    def index(self, trans, **kwd):
        """
        GET /api/workflows

        Displays a collection of workflows.

        :param  show_published:      if True, show also published workflows
        :type   show_published:      boolean
        """
        show_published = util.string_as_bool( kwd.get( 'show_published', 'False' ) )
        rval = []
        filter1 = ( trans.app.model.StoredWorkflow.user == trans.user )
        if show_published:
            filter1 = or_( filter1, ( trans.app.model.StoredWorkflow.published == True ) ) #noqa -- sqlalchemy comparison
        for wf in trans.sa_session.query( trans.app.model.StoredWorkflow ).filter(
                filter1, trans.app.model.StoredWorkflow.table.c.deleted == False ).order_by( #noqa -- sqlalchemy comparison
                desc( trans.app.model.StoredWorkflow.table.c.update_time ) ).all():
            item = wf.to_dict( value_mapper={ 'id': trans.security.encode_id } )
            encoded_id = trans.security.encode_id(wf.id)
            item['url'] = url_for('workflow', id=encoded_id)
            item['owner'] = wf.user.username
            rval.append(item)
        for wf_sa in trans.sa_session.query( trans.app.model.StoredWorkflowUserShareAssociation ).filter_by(
                user=trans.user ).join( 'stored_workflow' ).filter(
                trans.app.model.StoredWorkflow.deleted == False ).order_by( #noqa -- sqlalchemy comparison
                desc( trans.app.model.StoredWorkflow.update_time ) ).all():
            item = wf_sa.stored_workflow.to_dict( value_mapper={ 'id': trans.security.encode_id } )
            encoded_id = trans.security.encode_id(wf_sa.stored_workflow.id)
            item['url'] = url_for( 'workflow', id=encoded_id )
            item['owner'] = wf_sa.stored_workflow.user.username
            rval.append(item)
        return rval
Exemplo n.º 4
0
    def index(self, trans, **kwd):
        """
        GET /api/workflows

        Displays a collection of workflows.

        :param  show_published:      if True, show also published workflows
        :type   show_published:      boolean
        """
        show_published = util.string_as_bool( kwd.get( 'show_published', 'False' ) )
        rval = []
        filter1 = ( trans.app.model.StoredWorkflow.user == trans.user )
        if show_published:
            filter1 = or_( filter1, ( trans.app.model.StoredWorkflow.published == true() ) )
        for wf in trans.sa_session.query( trans.app.model.StoredWorkflow ).filter(
                filter1, trans.app.model.StoredWorkflow.table.c.deleted == false() ).order_by(
                desc( trans.app.model.StoredWorkflow.table.c.update_time ) ).all():
            item = wf.to_dict( value_mapper={ 'id': trans.security.encode_id } )
            encoded_id = trans.security.encode_id(wf.id)
            item['url'] = url_for('workflow', id=encoded_id)
            item['owner'] = wf.user.username
            rval.append(item)
        for wf_sa in trans.sa_session.query( trans.app.model.StoredWorkflowUserShareAssociation ).filter_by(
                user=trans.user ).join( 'stored_workflow' ).filter(
                trans.app.model.StoredWorkflow.deleted == false() ).order_by(
                desc( trans.app.model.StoredWorkflow.update_time ) ).all():
            item = wf_sa.stored_workflow.to_dict( value_mapper={ 'id': trans.security.encode_id } )
            encoded_id = trans.security.encode_id(wf_sa.stored_workflow.id)
            item['url'] = url_for( 'workflow', id=encoded_id )
            item['owner'] = wf_sa.stored_workflow.user.username
            rval.append(item)
        return rval
Exemplo n.º 5
0
 def show(self, trans, id, **kwd):
     """
     GET /api/groups/{encoded_group_id}
     Displays information about a group.
     """
     group_id = id
     try:
         decoded_group_id = trans.security.decode_id(group_id)
     except TypeError:
         trans.response.status = 400
         return "Malformed group id ( %s ) specified, unable to decode." % str(
             group_id)
     try:
         group = trans.sa_session.query(
             trans.app.model.Group).get(decoded_group_id)
     except:
         group = None
     if not group:
         trans.response.status = 400
         return "Invalid group id ( %s ) specified." % str(group_id)
     item = group.to_dict(view='element',
                          value_mapper={'id': trans.security.encode_id})
     item['url'] = url_for('group', id=group_id)
     item['users_url'] = url_for('group_users', group_id=group_id)
     item['roles_url'] = url_for('group_roles', group_id=group_id)
     return item
Exemplo n.º 6
0
 def update(self, trans, id, group_id, **kwd):
     """
     PUT /api/groups/{encoded_group_id}/roles/{encoded_role_id}
     Adds a role to a group
     """
     role_id = id
     decoded_group_id = trans.security.decode_id(group_id)
     decoded_role_id = trans.security.decode_id(role_id)
     item = None
     try:
         group = trans.sa_session.query(
             trans.app.model.Group).get(decoded_group_id)
         role = trans.sa_session.query(
             trans.app.model.Role).get(decoded_role_id)
         for gra in group.roles:
             if gra.role == role:
                 item = dict(id=role_id,
                             name=role.name,
                             url=url_for('group_role',
                                         group_id=group_id,
                                         id=role_id))
         if not item:
             gra = trans.app.model.GroupRoleAssociation(group, role)
             # Add GroupRoleAssociation
             trans.sa_session.add(gra)
             trans.sa_session.flush()
             item = dict(id=role_id,
                         name=role.name,
                         url=url_for('group_role',
                                     group_id=group_id,
                                     id=role_id))
     except Exception, e:
         item = "Error in group_role API Adding role %s to group %s" % (
             role.name, group.name)
         log.error(item + ": %s" % str(e))
Exemplo n.º 7
0
    def index(self, trans, **kwd):
        """
        GET /api/workflows

        Displays a collection of workflows.
        """
        rval = []
        for wf in (
            trans.sa_session.query(trans.app.model.StoredWorkflow)
            .filter_by(user=trans.user, deleted=False)
            .order_by(desc(trans.app.model.StoredWorkflow.table.c.update_time))
            .all()
        ):
            item = wf.to_dict(value_mapper={"id": trans.security.encode_id})
            encoded_id = trans.security.encode_id(wf.id)
            item["url"] = url_for("workflow", id=encoded_id)
            rval.append(item)
        for wf_sa in (
            trans.sa_session.query(trans.app.model.StoredWorkflowUserShareAssociation)
            .filter_by(user=trans.user)
            .join("stored_workflow")
            .filter(trans.app.model.StoredWorkflow.deleted == False)
            .order_by(desc(trans.app.model.StoredWorkflow.update_time))
            .all()
        ):
            item = wf_sa.stored_workflow.to_dict(value_mapper={"id": trans.security.encode_id})
            encoded_id = trans.security.encode_id(wf_sa.stored_workflow.id)
            item["url"] = url_for("workflow", id=encoded_id)
            rval.append(item)
        return rval
Exemplo n.º 8
0
 def update(self, trans, id, group_id, **kwd):
     """
     PUT /api/groups/{encoded_group_id}/roles/{encoded_role_id}
     Adds a role to a group
     """
     role_id = id
     decoded_group_id = trans.security.decode_id(group_id)
     decoded_role_id = trans.security.decode_id(role_id)
     item = None
     try:
         group = trans.sa_session.query(trans.app.model.Group).get(decoded_group_id)
         role = trans.sa_session.query(trans.app.model.Role).get(decoded_role_id)
         for gra in group.roles:
             if gra.role == role:
                 item = dict(id=role_id,
                             name=role.name,
                             url=url_for('group_role', group_id=group_id, id=role_id))
         if not item:
             gra = trans.app.model.GroupRoleAssociation(group, role)
             # Add GroupRoleAssociation
             trans.sa_session.add(gra)
             trans.sa_session.flush()
             item = dict(id=role_id,
                         name=role.name,
                         url=url_for('group_role', group_id=group_id, id=role_id))
     except Exception as e:
         item = "Error in group_role API Adding role %s to group %s" % (role.name, group.name)
         log.error(item + ": %s" % str(e))
     return item
Exemplo n.º 9
0
 def update(self, trans, id, group_id, **kwd):
     """
     PUT /api/groups/{encoded_group_id}/users/{encoded_user_id}
     Adds a user to a group
     """
     user_id = id
     decoded_group_id = trans.security.decode_id(group_id)
     decoded_user_id = trans.security.decode_id(user_id)
     item = None
     try:
         group = trans.sa_session.query(trans.app.model.Group).get(decoded_group_id)
         user = trans.sa_session.query(trans.app.model.User).get(decoded_user_id)
         for uga in group.users:
             if uga.user == user:
                 item = dict(id=user_id,
                             email=user.email,
                             url=url_for('group_user', group_id=group_id, id=user_id))
         if not item:
             uga = trans.app.model.UserGroupAssociation(user, group)
             # Add UserGroupAssociations
             trans.sa_session.add(uga)
             trans.sa_session.flush()
             item = dict(id=user_id,
                         email=user.email,
                         url=url_for('group_user', group_id=group_id, id=user_id))
     except Exception as e:
         item = "Error in group_user API Adding user %s to group %s" % (user.email, group.name)
         log.error(item + ": %s" % str(e))
     return item
Exemplo n.º 10
0
 def update(self, trans, id, group_id, **kwd):
     """
     PUT /api/groups/{encoded_group_id}/users/{encoded_user_id}
     Adds a user to a group
     """
     user_id = id
     decoded_group_id = trans.security.decode_id(group_id)
     decoded_user_id = trans.security.decode_id(user_id)
     item = None
     try:
         group = trans.sa_session.query(
             trans.app.model.Group).get(decoded_group_id)
         user = trans.sa_session.query(
             trans.app.model.User).get(decoded_user_id)
         for uga in group.users:
             if uga.user == user:
                 item = dict(id=user_id,
                             email=user.email,
                             url=url_for('group_user',
                                         group_id=group_id,
                                         id=user_id))
         if not item:
             uga = trans.app.model.UserGroupAssociation(user, group)
             # Add UserGroupAssociations
             trans.sa_session.add(uga)
             trans.sa_session.flush()
             item = dict(id=user_id,
                         email=user.email,
                         url=url_for('group_user',
                                     group_id=group_id,
                                     id=user_id))
     except Exception, e:
         item = "Error in group_user API Adding user %s to group %s" % (
             user.email, group.name)
         log.error(item + ": %s" % str(e))
Exemplo n.º 11
0
    def index( self, trans, deleted='False', **kwd ):
        """
        GET /api/users
        GET /api/users/deleted
        Displays a collection (list) of users.
        """
        rval = []
        query = trans.sa_session.query( trans.app.model.User )
        deleted = util.string_as_bool( deleted )
        if deleted:
            route = 'deleted_user'
            query = query.filter( trans.app.model.User.table.c.deleted == True )
            # only admins can see deleted users
            if not trans.user_is_admin():
                return []

        else:
            route = 'user'
            query = query.filter( trans.app.model.User.table.c.deleted == False )
            # special case: user can see only their own user
            if not trans.user_is_admin():
                item = trans.user.get_api_value( value_mapper={ 'id': trans.security.encode_id } )
                item['url'] = url_for( route, id=item['id'] )
                item['quota_percent'] = trans.app.quota_agent.get_percent( trans=trans )
                return [item]

        for user in query:
            item = user.get_api_value( value_mapper={ 'id': trans.security.encode_id } )
            #TODO: move into api_values
            item['quota_percent'] = trans.app.quota_agent.get_percent( trans=trans )
            item['url'] = url_for( route, id=item['id'] )
            rval.append( item )
        return rval
Exemplo n.º 12
0
 def index( self, trans, library_id, **kwd ):
     """
     GET /api/libraries/{encoded_library_id}/contents
     Displays a collection (list) of library contents (files and folders).
     """
     rval = []
     current_user_roles = trans.get_current_user_roles()
     def traverse( folder ):
         admin = trans.user_is_admin()
         rval = []
         for subfolder in folder.active_folders:
             if not admin:
                 can_access, folder_ids = trans.app.security_agent.check_folder_contents( trans.user, current_user_roles, subfolder )
             if (admin or can_access) and not subfolder.deleted:
                 subfolder.api_path = folder.api_path + '/' + subfolder.name
                 subfolder.api_type = 'folder'
                 rval.append( subfolder )
                 rval.extend( traverse( subfolder ) )
         for ld in folder.datasets:
             if not admin:
                 can_access = trans.app.security_agent.can_access_dataset(
                     current_user_roles, ld.library_dataset_dataset_association.dataset )
             if (admin or can_access) and not ld.deleted:
                 log.debug( "type(folder): %s" % type( folder ) )
                 log.debug( "type(api_path): %s; folder.api_path: %s" % ( type(folder.api_path), folder.api_path ) )
                 #log.debug( "attributes of folder: %s" % str(dir(folder)) )
                 ld.api_path = folder.api_path + '/' + ld.name
                 ld.api_type = 'file'
                 rval.append( ld )
         return rval
     try:
         decoded_library_id = trans.security.decode_id( library_id )
     except TypeError:
         trans.response.status = 400
         return "Malformed library id ( %s ) specified, unable to decode." % str( library_id )
     try:
         library = trans.sa_session.query( trans.app.model.Library ).get( decoded_library_id )
     except:
         library = None
     if not library or not ( trans.user_is_admin() or trans.app.security_agent.can_access_library( current_user_roles, library ) ):
         trans.response.status = 400
         return "Invalid library id ( %s ) specified." % str( library_id )
     log.debug( "Root folder type: %s" % type( library.root_folder ) )
     encoded_id = 'F' + trans.security.encode_id( library.root_folder.id )
     rval.append( dict( id = encoded_id,
                        type = 'folder',
                        name = '/',
                        url = url_for( 'library_content', library_id=library_id, id=encoded_id ) ) )
     log.debug( "Root folder attributes: %s" % str(dir(library.root_folder)) )
     library.root_folder.api_path = ''
     for content in traverse( library.root_folder ):
         encoded_id = trans.security.encode_id( content.id )
         if content.api_type == 'folder':
             encoded_id = 'F' + encoded_id
         rval.append( dict( id = encoded_id,
                            type = content.api_type,
                            name = content.api_path,
                            url = url_for( 'library_content', library_id=library_id, id=encoded_id, ) ) )
     return rval
Exemplo n.º 13
0
 def show(self, trans, id, **kwd):
     """
     GET /api/forms/{encoded_form_id}
     Displays information about a form.
     """
     form_definition_id = id
     try:
         decoded_form_definition_id = trans.security.decode_id(
             form_definition_id)
     except TypeError:
         trans.response.status = 400
         return "Malformed form definition id ( %s ) specified, unable to decode." % str(
             form_definition_id)
     try:
         form_definition = trans.sa_session.query(
             trans.app.model.FormDefinition).get(decoded_form_definition_id)
     except Exception:
         form_definition = None
     if not form_definition or not trans.user_is_admin:
         trans.response.status = 400
         return "Invalid form definition id ( %s ) specified." % str(
             form_definition_id)
     item = form_definition.to_dict(view='element',
                                    value_mapper={
                                        'id':
                                        trans.security.encode_id,
                                        'form_definition_current_id':
                                        trans.security.encode_id
                                    })
     item['url'] = url_for('form', id=form_definition_id)
     return item
Exemplo n.º 14
0
    def show( self, trans, id, deleted='False', **kwd ):
        """
        show( self, trans, id, deleted='False', **kwd )
        * GET /api/libraries/{id}:
            returns detailed information about a library
        * GET /api/libraries/deleted/{id}:
            returns detailed information about a deleted library

        :type   id:      an encoded id string
        :param  id:      the encoded id of the library
        :type   deleted: boolean
        :param  deleted: if True, allow information on a deleted library

        :rtype:     dictionary
        :returns:   detailed library information
        .. seealso:: :attr:`galaxy.model.Library.dict_element_visible_keys`
        """
#         log.debug( "LibraryContentsController.show: enter" )
        library_id = id
        deleted = util.string_as_bool( deleted )
        try:
            decoded_library_id = trans.security.decode_id( library_id )
        except TypeError:
            raise HTTPBadRequest( detail='Malformed library id ( %s ) specified, unable to decode.' % id )
        try:
            library = trans.sa_session.query( trans.app.model.Library ).get( decoded_library_id )
            assert library.deleted == deleted
        except:
            library = None
        if not library or not ( trans.user_is_admin() or trans.app.security_agent.can_access_library( trans.get_current_user_roles(), library ) ):
            raise HTTPBadRequest( detail='Invalid library id ( %s ) specified.' % id )
        item = library.to_dict( view='element' )
        #item['contents_url'] = url_for( 'contents', library_id=library_id )
        item['contents_url'] = url_for( 'library_contents', library_id=library_id )
        return item
Exemplo n.º 15
0
 def index(self, trans, group_id, **kwd):
     """
     GET /api/groups/{encoded_group_id}/users
     Displays a collection (list) of groups.
     """
     decoded_group_id = trans.security.decode_id(group_id)
     try:
         group = trans.sa_session.query(trans.app.model.Group).get(decoded_group_id)
     except Exception:
         group = None
     if not group:
         trans.response.status = 400
         return "Invalid group id ( %s ) specified." % str(group_id)
     rval = []
     try:
         for uga in group.users:
             user = uga.user
             encoded_id = trans.security.encode_id(user.id)
             rval.append(dict(id=encoded_id,
                              email=user.email,
                              url=url_for('group_user', group_id=group_id, id=encoded_id, )))
     except Exception as e:
         rval = "Error in group API at listing users"
         log.error(rval + ": %s" % str(e))
         trans.response.status = 500
     return rval
Exemplo n.º 16
0
 def biostar_redirect(self, trans, payload={}, biostar_action=None):
     """
     Generate a redirect to a Biostar site using external authentication to
     pass Galaxy user information and information about a specific tool.
     """
     # Ensure biostar integration is enabled
     if not trans.app.config.biostar_url:
         return error("Biostar integration is not enabled")
     # Start building up the payload
     payload = dict(DEFAULT_PAYLOAD, **payload)
     # Do the best we can of providing user information for the payload
     if trans.user:
         payload['username'] = "******" + trans.security.encode_id(
             trans.user.id)
         payload['email'] = trans.user.email
         if trans.user.username:
             payload['display_name'] = trans.user.username
         else:
             payload['display_name'] = trans.user.email.split("@")[0]
     else:
         encoded = trans.security.encode_id(trans.galaxy_session.id)
         payload['username'] = "******" + encoded
         payload['display_name'] = "Anonymous Galaxy User"
     data, digest = encode_data(trans.app.config.biostar_key, payload)
     return trans.response.send_redirect(
         url_for(trans.app.config.biostar_url,
                 data=data,
                 digest=digest,
                 name=trans.app.config.biostar_key_name,
                 action=biostar_action))
Exemplo n.º 17
0
 def _summary_hda_dict(self, trans, history_id, hda):
     """
     Returns a dictionary based on the HDA in .. _summary form::
     {
         'id'    : < the encoded dataset id >,
         'name'  : < currently only returns 'file' >,
         'type'  : < name of the dataset >,
         'url'   : < api url to retrieve this datasets full data >,
     }
     """
     api_type = "file"
     encoded_id = trans.security.encode_id(hda.id)
     return {
         'id':
         encoded_id,
         'name':
         hda.name,
         'type':
         api_type,
         'url':
         url_for(
             'history_content',
             history_id=history_id,
             id=encoded_id,
         ),
     }
Exemplo n.º 18
0
    def __api_import_new_workflow(self, trans, payload, **kwd):
        data = payload["workflow"]

        publish = util.string_as_bool(payload.get("publish", False))
        # If 'publish' set, default to importable.
        importable = util.string_as_bool(payload.get("importable", publish))

        if publish and not importable:
            raise exceptions.RequestParameterInvalidException("Published workflow must be importable.")

        from_dict_kwds = dict(source="API", publish=publish)
        workflow, missing_tool_tups = self._workflow_from_dict(trans, data, **from_dict_kwds)

        if importable:
            self._make_item_accessible(trans.sa_session, workflow)
            trans.sa_session.flush()

        # galaxy workflow newly created id
        workflow_id = workflow.id
        # api encoded, id
        encoded_id = trans.security.encode_id(workflow_id)

        # return list
        rval = []

        item = workflow.to_dict(value_mapper={"id": trans.security.encode_id})
        item["url"] = url_for("workflow", id=encoded_id)

        rval.append(item)

        return item
Exemplo n.º 19
0
    def import_new_workflow(self, trans, payload, **kwd):
        """
        POST /api/workflows/upload
        Importing dynamic workflows from the api. Return newly generated workflow id.
        Author: rpark

        # currently assumes payload['workflow'] is a json representation of a workflow to be inserted into the database
        """

        data = payload["workflow"]
        workflow, missing_tool_tups = self._workflow_from_dict(trans, data, source="API")

        # galaxy workflow newly created id
        workflow_id = workflow.id
        # api encoded, id
        encoded_id = trans.security.encode_id(workflow_id)

        # return list
        rval = []

        item = workflow.to_dict(value_mapper={"id": trans.security.encode_id})
        item["url"] = url_for("workflow", id=encoded_id)

        rval.append(item)

        return item
Exemplo n.º 20
0
 def index(self, trans, group_id, **kwd):
     """
     GET /api/groups/{encoded_group_id}/roles
     Displays a collection (list) of groups.
     """
     decoded_group_id = trans.security.decode_id(group_id)
     try:
         group = trans.sa_session.query(
             trans.app.model.Group).get(decoded_group_id)
     except Exception:
         group = None
     if not group:
         trans.response.status = 400
         return "Invalid group id ( %s ) specified." % str(group_id)
     rval = []
     try:
         for gra in group.roles:
             role = gra.role
             encoded_id = trans.security.encode_id(role.id)
             rval.append(
                 dict(id=encoded_id,
                      name=role.name,
                      url=url_for(
                          'group_role',
                          group_id=group_id,
                          id=encoded_id,
                      )))
     except Exception as e:
         rval = "Error in group API at listing roles"
         log.error(rval + ": %s", unicodify(e))
         trans.response.status = 500
     return rval
Exemplo n.º 21
0
 def biostar_redirect( self, trans, payload=None, biostar_action=None ):
     """
     Generate a redirect to a Biostar site using external authentication to
     pass Galaxy user information and information about a specific tool.
     """
     payload = payload or {}
     # Ensure biostar integration is enabled
     if not trans.app.config.biostar_url:
         return error( "Biostar integration is not enabled" )
     # Start building up the payload
     payload = dict( DEFAULT_PAYLOAD, **payload )
     # Do the best we can of providing user information for the payload
     if trans.user:
         payload['username'] = "******" + trans.security.encode_id( trans.user.id )
         payload['email'] = trans.user.email
         if trans.user.username:
             payload['display_name'] = trans.user.username
         else:
             payload['display_name'] = trans.user.email.split( "@" )[0]
     else:
         encoded = trans.security.encode_id( trans.galaxy_session.id )
         payload['username'] = "******" + encoded
         payload['display_name'] = "Anonymous Galaxy User"
     data, digest = encode_data( trans.app.config.biostar_key, payload )
     return trans.response.send_redirect( url_for( trans.app.config.biostar_url, data=data, digest=digest, name=trans.app.config.biostar_key_name, action=biostar_action ) )
Exemplo n.º 22
0
 def show(self, trans, id, **kwd):
     """
     GET /api/request_types/{encoded_request_type_id}
     Displays information about a request_type.
     """
     request_type_id = id
     try:
         decoded_request_type_id = trans.security.decode_id(request_type_id)
     except TypeError:
         trans.response.status = 400
         return "Malformed request type id ( %s ) specified, unable to decode." % str(request_type_id)
     try:
         request_type = trans.sa_session.query(trans.app.model.RequestType).get(decoded_request_type_id)
     except:
         request_type = None
     if not request_type:  # or not trans.user_is_admin():
         trans.response.status = 400
         return "Invalid request_type id ( %s ) specified." % str(request_type_id)
     if not trans.app.security_agent.can_access_request_type(trans.user.all_roles(), request_type):
         trans.response.status = 400
         return "No permission to access request_type ( %s )." % str(request_type_id)
     item = request_type.to_dict(
         view="element",
         value_mapper={
             "id": trans.security.encode_id,
             "request_form_id": trans.security.encode_id,
             "sample_form_id": trans.security.encode_id,
         },
     )
     item["url"] = url_for("request_type", id=request_type_id)
     return item
Exemplo n.º 23
0
 def show(self, trans, id, **kwd):
     """
     GET /api/roles/{encoded_role_id}
     Displays information about a role.
     """
     role_id = id
     try:
         decoded_role_id = trans.security.decode_id(role_id)
     except Exception:
         trans.response.status = 400
         return "Malformed role id ( %s ) specified, unable to decode." % str(
             role_id)
     try:
         role = trans.sa_session.query(
             trans.app.model.Role).get(decoded_role_id)
     except Exception:
         role = None
     if not role or not (trans.user_is_admin
                         or trans.app.security_agent.ok_to_display(
                             trans.user, role)):
         trans.response.status = 400
         return "Invalid role id ( %s ) specified." % str(role_id)
     item = role.to_dict(view='element',
                         value_mapper={'id': trans.security.encode_id})
     item['url'] = url_for('role', id=role_id)
     return item
Exemplo n.º 24
0
 def delete(self, trans, id, group_id, **kwd):
     """
     DELETE /api/groups/{encoded_group_id}/users/{encoded_user_id}
     Removes a user from a group
     """
     user_id = id
     decoded_group_id = trans.security.decode_id(group_id)
     decoded_user_id = trans.security.decode_id(user_id)
     try:
         group = trans.sa_session.query(
             trans.app.model.Group).get(decoded_group_id)
         user = trans.sa_session.query(
             trans.app.model.User).get(decoded_user_id)
         for uga in group.users:
             if uga.user == user:
                 trans.sa_session.delete(uga)
                 trans.sa_session.flush()
                 item = dict(id=user_id,
                             email=user.email,
                             url=url_for('group_user',
                                         group_id=group_id,
                                         id=user_id))
         if not item:
             item = "user %s not in group %s" % (user.email, group.name)
     except Exception as e:
         item = "Error in group_user API Removing user %s from group %s" % (
             user.email, group.name)
         log.error(item + ": %s" % str(e))
     return item
Exemplo n.º 25
0
    def import_new_workflow(self, trans, payload, **kwd):
        """
        POST /api/workflows/upload
        Importing dynamic workflows from the api. Return newly generated workflow id.
        Author: rpark

        # currently assumes payload['workflow'] is a json representation of a workflow to be inserted into the database
        """

        data = payload['workflow']

        workflow, missing_tool_tups = self._workflow_from_dict(trans,
                                                               data,
                                                               source="API")

        # galaxy workflow newly created id
        workflow_id = workflow.id
        # api encoded, id
        encoded_id = trans.security.encode_id(workflow_id)

        # return list
        rval = []

        item = workflow.to_dict(value_mapper={'id': trans.security.encode_id})
        item['url'] = url_for('workflow', id=encoded_id)

        rval.append(item)

        return item
Exemplo n.º 26
0
 def index(self, trans, group_id, **kwd):
     """
     GET /api/groups/{encoded_group_id}/users
     Displays a collection (list) of groups.
     """
     decoded_group_id = trans.security.decode_id(group_id)
     try:
         group = trans.sa_session.query(
             trans.app.model.Group).get(decoded_group_id)
     except Exception:
         group = None
     if not group:
         trans.response.status = 400
         return "Invalid group id ( %s ) specified." % str(group_id)
     rval = []
     try:
         for uga in group.users:
             user = uga.user
             encoded_id = trans.security.encode_id(user.id)
             rval.append(
                 dict(id=encoded_id,
                      email=user.email,
                      url=url_for(
                          'group_user',
                          group_id=group_id,
                          id=encoded_id,
                      )))
     except Exception as e:
         rval = "Error in group API at listing users"
         log.error(rval + ": %s" % str(e))
         trans.response.status = 500
     return rval
Exemplo n.º 27
0
 def show(self, trans, id, group_id, **kwd):
     """
     GET /api/groups/{encoded_group_id}/users/{encoded_user_id}
     Displays information about a group user.
     """
     user_id = id
     decoded_group_id = trans.security.decode_id(group_id)
     decoded_user_id = trans.security.decode_id(user_id)
     item = None
     try:
         group = trans.sa_session.query(
             trans.app.model.Group).get(decoded_group_id)
         user = trans.sa_session.query(
             trans.app.model.User).get(decoded_user_id)
         for uga in group.users:
             if uga.user == user:
                 item = dict(id=user_id,
                             email=user.email,
                             url=url_for('group_user',
                                         group_id=group_id,
                                         id=user_id))  # TODO Fix This
         if not item:
             item = "user %s not in group %s" % (user.email, group.name)
     except Exception as e:
         item = "Error in group_user API group %s user %s" % (group.name,
                                                              user.email)
         log.error(item + ": %s" % str(e))
     return item
Exemplo n.º 28
0
 def create( self, trans, payload, **kwd ):
     """
     POST /api/libraries
     Creates a new library.
     """
     if not trans.user_is_admin():
         raise HTTPForbidden( detail='You are not authorized to create a new library.' )
     params = util.Params( payload )
     name = util.restore_text( params.get( 'name', None ) )
     if not name:
         raise HTTPBadRequest( detail="Missing required parameter 'name'." )
     description = util.restore_text( params.get( 'description', '' ) )
     synopsis = util.restore_text( params.get( 'synopsis', '' ) )
     if synopsis in [ 'None', None ]:
         synopsis = ''
     library = trans.app.model.Library( name=name, description=description, synopsis=synopsis )
     root_folder = trans.app.model.LibraryFolder( name=name, description='' )
     library.root_folder = root_folder
     trans.sa_session.add_all( ( library, root_folder ) )
     trans.sa_session.flush()
     encoded_id = trans.security.encode_id( library.id )
     rval = {}
     rval['url'] = url_for( 'library', id=encoded_id )
     rval['name'] = name
     rval['id'] = encoded_id
     return rval
Exemplo n.º 29
0
    def show(self, trans, id, **kwd):
        """
        GET /api/workflows/{encoded_workflow_id}

        Displays information needed to run a workflow from the command line.
        """
        workflow_id = id
        try:
            decoded_workflow_id = trans.security.decode_id(workflow_id)
        except TypeError:
            trans.response.status = 400
            return "Malformed workflow id ( %s ) specified, unable to decode." % str(workflow_id)
        try:
            stored_workflow = trans.sa_session.query(trans.app.model.StoredWorkflow).get(decoded_workflow_id)
            if stored_workflow.user != trans.user and not trans.user_is_admin():
                if trans.sa_session.query(trans.app.model.StoredWorkflowUserShareAssociation).filter_by(user=trans.user, stored_workflow=stored_workflow).count() == 0:
                    trans.response.status = 400
                    return("Workflow is not owned by or shared with current user")
        except:
            trans.response.status = 400
            return "That workflow does not exist."
        item = stored_workflow.get_api_value(view='element', value_mapper={'id':trans.security.encode_id})
        item['url'] = url_for('workflow', id=workflow_id)
        latest_workflow = stored_workflow.latest_workflow
        inputs = {}
        for step in latest_workflow.steps:
            if step.type == 'data_input':
                inputs[step.id] = {'label':step.tool_inputs['name'], 'value':""}
            else:
                pass
                # Eventually, allow regular tool parameters to be inserted and modified at runtime.
                # p = step.get_required_parameters()
        item['inputs'] = inputs
        return item
Exemplo n.º 30
0
 def show(self, trans, id, deleted='False', **kwd):
     """
     GET /api/libraries/{encoded_library_id}
     GET /api/libraries/deleted/{encoded_library_id}
     Displays information about a library.
     """
     log.debug("LibraryContentsController.show: enter")
     library_id = id
     deleted = util.string_as_bool(deleted)
     try:
         decoded_library_id = trans.security.decode_id(library_id)
     except TypeError:
         raise HTTPBadRequest(
             detail=
             'Malformed library id ( %s ) specified, unable to decode.' %
             id)
     try:
         library = trans.sa_session.query(
             trans.app.model.Library).get(decoded_library_id)
         assert library.deleted == deleted
     except:
         library = None
     if not library or not (trans.user_is_admin()
                            or trans.app.security_agent.can_access_library(
                                trans.get_current_user_roles(), library)):
         raise HTTPBadRequest(
             detail='Invalid library id ( %s ) specified.' % id)
     item = library.get_api_value(view='element')
     #item['contents_url'] = url_for( 'contents', library_id=library_id )
     item['contents_url'] = url_for('library_contents',
                                    library_id=library_id)
     return item
Exemplo n.º 31
0
 def delete(self, trans, id, group_id, **kwd):
     """
     DELETE /api/groups/{encoded_group_id}/roles/{encoded_role_id}
     Removes a role from a group
     """
     role_id = id
     decoded_group_id = trans.security.decode_id(group_id)
     decoded_role_id = trans.security.decode_id(role_id)
     try:
         group = trans.sa_session.query(
             trans.app.model.Group).get(decoded_group_id)
         role = trans.sa_session.query(
             trans.app.model.Role).get(decoded_role_id)
         for gra in group.roles:
             if gra.role == role:
                 trans.sa_session.delete(gra)
                 trans.sa_session.flush()
                 item = dict(id=role_id,
                             name=role.name,
                             url=url_for('group_role',
                                         group_id=group_id,
                                         id=role_id))
         if not item:
             item = "role %s not in group %s" % (role.name, group.name)
     except Exception as e:
         item = "Error in group_role API Removing role %s from group %s" % (
             role.name, group.name)
         log.error(item + ": %s", unicodify(e))
     return item
Exemplo n.º 32
0
 def create(self, trans, payload, **kwd):
     """
     POST /api/libraries
     Creates a new library.
     """
     if not trans.user_is_admin():
         raise HTTPForbidden(
             detail='You are not authorized to create a new library.')
     params = util.Params(payload)
     name = util.restore_text(params.get('name', None))
     if not name:
         raise HTTPBadRequest(detail="Missing required parameter 'name'.")
     description = util.restore_text(params.get('description', ''))
     synopsis = util.restore_text(params.get('synopsis', ''))
     if synopsis in ['None', None]:
         synopsis = ''
     library = trans.app.model.Library(name=name,
                                       description=description,
                                       synopsis=synopsis)
     root_folder = trans.app.model.LibraryFolder(name=name, description='')
     library.root_folder = root_folder
     trans.sa_session.add_all((library, root_folder))
     trans.sa_session.flush()
     encoded_id = trans.security.encode_id(library.id)
     rval = {}
     rval['url'] = url_for('library', id=encoded_id)
     rval['name'] = name
     rval['id'] = encoded_id
     return rval
Exemplo n.º 33
0
 def show(self, trans, id, group_id, **kwd):
     """
     GET /api/groups/{encoded_group_id}/roles/{encoded_role_id}
     Displays information about a group role.
     """
     role_id = id
     decoded_group_id = trans.security.decode_id(group_id)
     decoded_role_id = trans.security.decode_id(role_id)
     item = None
     try:
         group = trans.sa_session.query(
             trans.app.model.Group).get(decoded_group_id)
         role = trans.sa_session.query(
             trans.app.model.Role).get(decoded_role_id)
         for gra in group.roles:
             if gra.role == role:
                 item = dict(id=role_id,
                             name=role.name,
                             url=url_for('group_role',
                                         group_id=group_id,
                                         id=role_id))  # TODO Fix This
         if not item:
             item = "role %s not in group %s" % (role.name, group.name)
     except Exception as e:
         item = "Error in group_role API group %s role %s" % (group.name,
                                                              role.name)
         log.error(item + ": %s", unicodify(e))
     return item
Exemplo n.º 34
0
 def index( self, trans, deleted='False', **kwd ):
     """
     GET /api/libraries
     GET /api/libraries/deleted
     Displays a collection (list) of libraries.
     """
     log.debug( "LibrariesController.index: enter" )
     query = trans.sa_session.query( trans.app.model.Library )
     deleted = util.string_as_bool( deleted )
     if deleted:
         route = 'deleted_library'
         query = query.filter( trans.app.model.Library.table.c.deleted == True )
     else:
         route = 'library'
         query = query.filter( trans.app.model.Library.table.c.deleted == False )
     current_user_role_ids = [ role.id for role in trans.get_current_user_roles() ]
     library_access_action = trans.app.security_agent.permitted_actions.LIBRARY_ACCESS.action
     restricted_library_ids = [ lp.library_id for lp in trans.sa_session.query( trans.model.LibraryPermissions ) \
                                                                        .filter( trans.model.LibraryPermissions.table.c.action == library_access_action ) \
                                                                        .distinct() ]
     accessible_restricted_library_ids = [ lp.library_id for lp in trans.sa_session.query( trans.model.LibraryPermissions ) \
                                                                                   .filter( and_( trans.model.LibraryPermissions.table.c.action == library_access_action,
                                                                                                  trans.model.LibraryPermissions.table.c.role_id.in_( current_user_role_ids ) ) ) ]
     query = query.filter( or_( not_( trans.model.Library.table.c.id.in_( restricted_library_ids ) ),
                        trans.model.Library.table.c.id.in_( accessible_restricted_library_ids ) ) )
     rval = []
     for library in query:
         item = library.get_api_value()
         item['url'] = url_for( route, id=trans.security.encode_id( library.id ) )
         item['id'] = trans.security.encode_id( item['id'] )
         rval.append( item )
     return rval
Exemplo n.º 35
0
 def index(self, trans, group_id, **kwd):
     """
     GET /api/groups/{encoded_group_id}/roles
     Displays a collection (list) of groups.
     """
     decoded_group_id = trans.security.decode_id(group_id)
     try:
         group = trans.sa_session.query(trans.app.model.Group).get(decoded_group_id)
     except:
         group = None
     if not group:
         trans.response.status = 400
         return "Invalid group id ( %s ) specified." % str(group_id)
     rval = []
     try:
         for gra in group.roles:
             role = gra.role
             encoded_id = trans.security.encode_id(role.id)
             rval.append(dict(id=encoded_id,
                              name=role.name,
                              url=url_for('group_role', group_id=group_id, id=encoded_id, )))
     except Exception as e:
         rval = "Error in group API at listing roles"
         log.error(rval + ": %s" % str(e))
         trans.response.status = 500
     return rval
Exemplo n.º 36
0
    def import_shared_workflow(self, trans, payload, **kwd):
        """
        POST /api/workflows/import
        Import a workflow shared by other users.

        :param  workflow_id:      the workflow id (required)
        :type   workflow_id:      str

        :raises: exceptions.MessageException, exceptions.ObjectNotFound
        """
        # Pull parameters out of payload.
        workflow_id = payload.get('workflow_id', None)
        if workflow_id == None:
            raise exceptions.ObjectAttributeMissingException( "Missing required parameter 'workflow_id'." )
        try:
            stored_workflow = self.get_stored_workflow( trans, workflow_id, check_ownership=False )
        except:
            raise exceptions.ObjectNotFound( "Malformed workflow id ( %s ) specified." % workflow_id )
        if stored_workflow.importable == False:
            raise exceptions.MessageException( 'The owner of this workflow has disabled imports via this link.' )
        elif stored_workflow.deleted:
            raise exceptions.MessageException( "You can't import this workflow because it has been deleted." )
        imported_workflow = self._import_shared_workflow( trans, stored_workflow )
        item = imported_workflow.to_dict( value_mapper={ 'id': trans.security.encode_id } )
        encoded_id = trans.security.encode_id(imported_workflow.id)
        item['url'] = url_for('workflow', id=encoded_id)
        return item
Exemplo n.º 37
0
    def submit_report(self, dataset, job, tool, **kwargs):
        """Doesn't do anything, just shows a link to submit on biostars.
        """
        # This class specifically does nothing special for compliance purposes
        # because the user is willingly posting their data on a public
        # first/third-party site. Maybe should do something about the dialog
        # linking to the biostars privacy policy during the "submit to
        # biostars" dialog?

        try:
            assert biostar.biostar_enabled(self.app), ValueError(
                "Biostar is not configured for this galaxy instance")
            assert self.app.config.biostar_enable_bug_reports, ValueError(
                "Biostar is not configured to allow bug reporting for this galaxy instance"
            )
            print(kwargs)

            url = url_for(controller='biostar',
                          action='biostar_tool_bug_report',
                          hda=self.app.security.encode_id(dataset.id),
                          email=kwargs['email'],
                          message=kwargs['message'])
            return ('Click <a href="%s">here</a> to submit to BioStars' % url,
                    'success')
        except Exception as e:
            return ("An error occurred submitting the report to biostars: %s" %
                    str(e), "danger")
Exemplo n.º 38
0
    def __api_import_new_workflow( self, trans, payload, **kwd ):
        data = payload['workflow']

        publish = util.string_as_bool( payload.get( "publish", False ) )
        # If 'publish' set, default to importable.
        importable = util.string_as_bool( payload.get( "importable", publish ) )

        if publish and not importable:
            raise exceptions.RequestParameterInvalidException( "Published workflow must be importable." )

        from_dict_kwds = dict(
            source="API",
            publish=publish,
        )
        workflow, missing_tool_tups = self._workflow_from_dict( trans, data, **from_dict_kwds )

        if importable:
            self._make_item_accessible( trans.sa_session, workflow )
            trans.sa_session.flush()

        # galaxy workflow newly created id
        workflow_id = workflow.id
        # api encoded, id
        encoded_id = trans.security.encode_id(workflow_id)

        # return list
        rval = []

        item = workflow.to_dict(value_mapper={'id': trans.security.encode_id})
        item['url'] = url_for('workflow', id=encoded_id)

        rval.append(item)

        return item
Exemplo n.º 39
0
def get_biostar_url(app, payload=None, biostar_action=None):
    # Ensure biostar integration is enabled
    if not biostar_enabled(app):
        raise Exception("Biostar integration is not enabled")
    if biostar_action not in BIOSTAR_ACTIONS:
        raise Exception("Invalid action specified (%s)." % (biostar_action))
    biostar_action = BIOSTAR_ACTIONS[biostar_action]
    # Start building up the payload
    payload = payload or {}
    payload = dict(DEFAULT_PAYLOAD, **payload)
    payload['name'] = app.config.biostar_key_name
    for hmac_value_name, hmac_parameter_name in biostar_action.get(
            'hmac_values', {}).items():
        #Biostar requires ascii only on HMAC'd things
        payload[hmac_value_name] = smart_str(payload.get(hmac_value_name, ''),
                                             encoding='ascii',
                                             errors='replace')
        payload[hmac_parameter_name] = hmac.new(
            app.config.biostar_key, payload[hmac_value_name]).hexdigest()
    #generate url, can parse payload info
    url = str(
        urlparse.urljoin(app.config.biostar_url,
                         biostar_action.get('url')(payload)))
    if not biostar_action.get('uses_payload'):
        payload = {}
    url = url_for(url)
    return url, payload
Exemplo n.º 40
0
 def create(self, trans, payload, **kwd):
     """
     POST /api/forms
     Creates a new form.
     """
     if not trans.user_is_admin:
         trans.response.status = 403
         return "You are not authorized to create a new form."
     xml_text = payload.get('xml_text', None)
     if xml_text is None:
         trans.response.status = 400
         return "Missing required parameter 'xml_text'."
         # enhance to allow creating from more than just xml
     form_definition = form_factory.from_elem(XML(xml_text))
     trans.sa_session.add(form_definition)
     trans.sa_session.flush()
     encoded_id = trans.security.encode_id(form_definition.id)
     item = form_definition.to_dict(view='element',
                                    value_mapper={
                                        'id':
                                        trans.security.encode_id,
                                        'form_definition_current_id':
                                        trans.security.encode_id
                                    })
     item['url'] = url_for('form', id=encoded_id)
     return [item]
Exemplo n.º 41
0
    def show(self, trans, id, **kwd):
        """
        GET /api/workflows/{encoded_workflow_id}

        Displays information needed to run a workflow from the command line.
        """
        workflow_id = id
        try:
            decoded_workflow_id = trans.security.decode_id(workflow_id)
        except TypeError:
            trans.response.status = 400
            return "Malformed workflow id ( %s ) specified, unable to decode." % str(
                workflow_id)
        try:
            stored_workflow = trans.sa_session.query(
                trans.app.model.StoredWorkflow).get(decoded_workflow_id)
            if stored_workflow.user != trans.user and not trans.user_is_admin(
            ):
                if trans.sa_session.query(
                        trans.app.model.StoredWorkflowUserShareAssociation
                ).filter_by(user=trans.user,
                            stored_workflow=stored_workflow).count() == 0:
                    trans.response.status = 400
                    return (
                        "Workflow is not owned by or shared with current user")
        except:
            trans.response.status = 400
            return "That workflow does not exist."
        item = stored_workflow.get_api_value(
            view='element', value_mapper={'id': trans.security.encode_id})
        item['url'] = url_for('workflow', id=workflow_id)
        latest_workflow = stored_workflow.latest_workflow
        inputs = {}
        for step in latest_workflow.steps:
            if step.type == 'data_input':
                inputs[step.id] = {
                    'label': step.tool_inputs['name'],
                    'value': ""
                }
            else:
                pass
                # Eventually, allow regular tool parameters to be inserted and modified at runtime.
                # p = step.get_required_parameters()
        item['inputs'] = inputs
        steps = {}
        for step in latest_workflow.steps:
            steps[step.id] = {
                'id': step.id,
                'type': step.type,
                'tool_id': step.tool_id,
                'input_steps': {}
            }
            for conn in step.input_connections:
                steps[step.id]['input_steps'][conn.input_name] = {
                    'source_step': conn.output_step_id,
                    'step_output': conn.output_name
                }
        item['steps'] = steps
        return item
Exemplo n.º 42
0
    def __api_import_new_workflow(self, trans, payload, **kwd):
        data = payload['workflow']
        raw_workflow_description = self.__normalize_workflow(trans, data)
        data = raw_workflow_description.as_dict
        import_tools = util.string_as_bool(payload.get("import_tools", False))
        if import_tools and not trans.user_is_admin:
            raise exceptions.AdminRequiredException()

        from_dict_kwds = self.__import_or_update_kwds(payload)

        publish = util.string_as_bool(payload.get("publish", False))
        # If 'publish' set, default to importable.
        importable = util.string_as_bool(payload.get("importable", publish))

        if publish and not importable:
            raise exceptions.RequestParameterInvalidException("Published workflow must be importable.")

        from_dict_kwds["publish"] = publish
        workflow, missing_tool_tups = self._workflow_from_dict(trans, raw_workflow_description, **from_dict_kwds)
        if importable:
            self._make_item_accessible(trans.sa_session, workflow)
            trans.sa_session.flush()
        # galaxy workflow newly created id
        workflow_id = workflow.id
        # api encoded, id
        encoded_id = trans.security.encode_id(workflow_id)
        item = workflow.to_dict(value_mapper={'id': trans.security.encode_id})
        item['url'] = url_for('workflow', id=encoded_id)
        item['owner'] = workflow.user.username
        item['number_of_steps'] = len(workflow.latest_workflow.steps)
        if import_tools:
            tools = {}
            for key in data['steps']:
                item = data['steps'][key]
                if item is not None:
                    if 'tool_shed_repository' in item:
                        tool_shed_repository = item['tool_shed_repository']
                        if 'owner' in tool_shed_repository and 'changeset_revision' in tool_shed_repository and 'name' in tool_shed_repository and 'tool_shed' in tool_shed_repository:
                            toolstr = tool_shed_repository['owner'] \
                                + tool_shed_repository['changeset_revision'] \
                                + tool_shed_repository['name'] \
                                + tool_shed_repository['tool_shed']
                            tools[toolstr] = tool_shed_repository
            irm = InstallRepositoryManager(self.app)
            for k in tools:
                item = tools[k]
                tool_shed_url = 'https://' + item['tool_shed'] + '/'
                name = item['name']
                owner = item['owner']
                changeset_revision = item['changeset_revision']
                irm.install(tool_shed_url,
                            name,
                            owner,
                            changeset_revision,
                            payload)
        return item
Exemplo n.º 43
0
    def __api_import_new_workflow(self, trans, payload, **kwd):
        data = payload['workflow']
        raw_workflow_description = self.__normalize_workflow(trans, data)
        data = raw_workflow_description.as_dict
        import_tools = util.string_as_bool(payload.get("import_tools", False))
        if import_tools and not trans.user_is_admin:
            raise exceptions.AdminRequiredException()

        from_dict_kwds = self.__import_or_update_kwds(payload)

        publish = util.string_as_bool(payload.get("publish", False))
        # If 'publish' set, default to importable.
        importable = util.string_as_bool(payload.get("importable", publish))

        if publish and not importable:
            raise exceptions.RequestParameterInvalidException("Published workflow must be importable.")

        from_dict_kwds["publish"] = publish
        workflow, missing_tool_tups = self._workflow_from_dict(trans, raw_workflow_description, **from_dict_kwds)
        if importable:
            self._make_item_accessible(trans.sa_session, workflow)
            trans.sa_session.flush()
        # galaxy workflow newly created id
        workflow_id = workflow.id
        # api encoded, id
        encoded_id = trans.security.encode_id(workflow_id)
        item = workflow.to_dict(value_mapper={'id': trans.security.encode_id})
        item['url'] = url_for('workflow', id=encoded_id)
        item['owner'] = workflow.user.username
        item['number_of_steps'] = len(workflow.latest_workflow.steps)
        if import_tools:
            tools = {}
            for key in data['steps']:
                item = data['steps'][key]
                if item is not None:
                    if 'tool_shed_repository' in item:
                        tool_shed_repository = item['tool_shed_repository']
                        if 'owner' in tool_shed_repository and 'changeset_revision' in tool_shed_repository and 'name' in tool_shed_repository and 'tool_shed' in tool_shed_repository:
                            toolstr = tool_shed_repository['owner'] \
                                + tool_shed_repository['changeset_revision'] \
                                + tool_shed_repository['name'] \
                                + tool_shed_repository['tool_shed']
                            tools[toolstr] = tool_shed_repository
            irm = InstallRepositoryManager(self.app)
            for k in tools:
                item = tools[k]
                tool_shed_url = 'https://' + item['tool_shed'] + '/'
                name = item['name']
                owner = item['owner']
                changeset_revision = item['changeset_revision']
                irm.install(tool_shed_url,
                            name,
                            owner,
                            changeset_revision,
                            payload)
        return item
Exemplo n.º 44
0
def create_cookie( trans, key_name, key, email, age=DEFAULT_BIOSTAR_COOKIE_AGE, override_never_authenticate=False ):
    if trans.app.config.biostar_never_authenticate and not override_never_authenticate:
        log.debug( 'A BioStar link was clicked, but never authenticate has been enabled, so we will not create the login cookie.' )
        return
    digest = hmac.new( key, email ).hexdigest()
    value = "%s:%s" % (email, digest)
    trans.set_cookie( value, name=key_name, path='/', age=age, version='1' )
    # We need to explicitly set the domain here, in order to allow for biostar in a subdomain to work
    galaxy_hostname = urlparse.urlsplit( url_for( '/', qualified=True ) ).hostname
    biostar_hostname = urlparse.urlsplit( trans.app.config.biostar_url ).hostname
    trans.response.cookies[ key_name ][ 'domain' ] = determine_cookie_domain( galaxy_hostname, biostar_hostname )
Exemplo n.º 45
0
def create_cookie( trans, key_name, key, email, age=DEFAULT_BIOSTAR_COOKIE_AGE, override_never_authenticate=False ):
    if trans.app.config.biostar_never_authenticate and not override_never_authenticate:
        log.debug( 'A BioStar link was clicked, but never authenticate has been enabled, so we will not create the login cookie.' )
        return
    digest = hmac.new( key, email ).hexdigest()
    value = "%s:%s" % (email, digest)
    trans.set_cookie( value, name=key_name, path='/', age=age, version='1' )
    # We need to explicitly set the domain here, in order to allow for biostar in a subdomain to work
    galaxy_hostname = urlparse.urlsplit( url_for( '/', qualified=True ) ).hostname
    biostar_hostname = urlparse.urlsplit( trans.app.config.biostar_url ).hostname
    trans.response.cookies[ key_name ][ 'domain' ] = determine_cookie_domain( galaxy_hostname, biostar_hostname )
Exemplo n.º 46
0
 def index( self, trans, **kwd ):
     """
     GET /api/request_types
     Displays a collection (list) of request_types.
     """
     rval = []
     for request_type in trans.app.security_agent.get_accessible_request_types( trans, trans.user ):
         item = request_type.to_dict( value_mapper={ 'id': trans.security.encode_id, 'request_form_id': trans.security.encode_id, 'sample_form_id': trans.security.encode_id } )
         encoded_id = trans.security.encode_id( request_type.id )
         item['url'] = url_for( 'request_type', id=encoded_id )
         rval.append( item )
     return rval
Exemplo n.º 47
0
 def index( self, trans, **kwd ):
     """
     GET /api/request_types
     Displays a collection (list) of request_types.
     """
     rval = []
     for request_type in trans.app.security_agent.get_accessible_request_types( trans, trans.user ):
         item = request_type.get_api_value( value_mapper={ 'id': trans.security.encode_id, 'request_form_id': trans.security.encode_id, 'sample_form_id': trans.security.encode_id } )
         encoded_id = trans.security.encode_id( request_type.id )
         item['url'] = url_for( 'request_type', id=encoded_id )
         rval.append( item )
     return rval
Exemplo n.º 48
0
 def index(self, trans, **kwd):
     """
     GET /api/groups
     Displays a collection (list) of groups.
     """
     rval = []
     for group in trans.sa_session.query(trans.app.model.Group).filter(trans.app.model.Group.table.c.deleted == false()):
         if trans.user_is_admin():
             item = group.to_dict(value_mapper={'id': trans.security.encode_id})
             encoded_id = trans.security.encode_id(group.id)
             item['url'] = url_for('group', id=encoded_id)
             rval.append(item)
     return rval
Exemplo n.º 49
0
 def index( self, trans, **kwd ):
     """
     GET /api/roles
     Displays a collection (list) of roles.
     """
     rval = []
     for role in trans.sa_session.query( trans.app.model.Role ).filter( trans.app.model.Role.table.c.deleted == False ):
         if trans.user_is_admin() or trans.app.security_agent.ok_to_display( trans.user, role ):
             item = role.get_api_value( value_mapper={ 'id': trans.security.encode_id } )
             encoded_id = trans.security.encode_id( role.id )
             item['url'] = url_for( 'role', id=encoded_id )
             rval.append( item )
     return rval
Exemplo n.º 50
0
    def index(self, trans, **kwd):
        """
        GET /api/workflows

        Displays a collection of workflows.

        :param  show_published:      if True, show also published workflows
        :type   show_published:      boolean
        """
        show_published = util.string_as_bool(kwd.get("show_published", "False"))
        rval = []
        filter1 = trans.app.model.StoredWorkflow.user == trans.user
        if show_published:
            filter1 = or_(filter1, (trans.app.model.StoredWorkflow.published == True))  # noqa -- sqlalchemy comparison
        for wf in (
            trans.sa_session.query(trans.app.model.StoredWorkflow)
            .filter(filter1, trans.app.model.StoredWorkflow.table.c.deleted == False)
            .order_by(desc(trans.app.model.StoredWorkflow.table.c.update_time))  # noqa -- sqlalchemy comparison
            .all()
        ):
            item = wf.to_dict(value_mapper={"id": trans.security.encode_id})
            encoded_id = trans.security.encode_id(wf.id)
            item["url"] = url_for("workflow", id=encoded_id)
            item["owner"] = wf.user.username
            rval.append(item)
        for wf_sa in (
            trans.sa_session.query(trans.app.model.StoredWorkflowUserShareAssociation)
            .filter_by(user=trans.user)
            .join("stored_workflow")
            .filter(trans.app.model.StoredWorkflow.deleted == False)
            .order_by(desc(trans.app.model.StoredWorkflow.update_time))  # noqa -- sqlalchemy comparison
            .all()
        ):
            item = wf_sa.stored_workflow.to_dict(value_mapper={"id": trans.security.encode_id})
            encoded_id = trans.security.encode_id(wf_sa.stored_workflow.id)
            item["url"] = url_for("workflow", id=encoded_id)
            item["owner"] = wf_sa.stored_workflow.user.username
            rval.append(item)
        return rval
Exemplo n.º 51
0
    def show(self, trans, id, **kwd):
        """
        GET /api/workflows/{encoded_workflow_id}

        Displays information needed to run a workflow from the command line.
        """
        workflow_id = id
        try:
            decoded_workflow_id = trans.security.decode_id(workflow_id)
        except TypeError:
            trans.response.status = 400
            return "Malformed workflow id ( %s ) specified, unable to decode." % str(workflow_id)
        try:
            stored_workflow = trans.sa_session.query(trans.app.model.StoredWorkflow).get(decoded_workflow_id)
            if stored_workflow.user != trans.user and not trans.user_is_admin():
                if (
                    trans.sa_session.query(trans.app.model.StoredWorkflowUserShareAssociation)
                    .filter_by(user=trans.user, stored_workflow=stored_workflow)
                    .count()
                    == 0
                ):
                    trans.response.status = 400
                    return "Workflow is not owned by or shared with current user"
        except:
            trans.response.status = 400
            return "That workflow does not exist."
        item = stored_workflow.to_dict(view="element", value_mapper={"id": trans.security.encode_id})
        item["url"] = url_for("workflow", id=workflow_id)
        latest_workflow = stored_workflow.latest_workflow
        inputs = {}
        for step in latest_workflow.steps:
            if step.type == "data_input":
                if step.tool_inputs and "name" in step.tool_inputs:
                    inputs[step.id] = {"label": step.tool_inputs["name"], "value": ""}
                else:
                    inputs[step.id] = {"label": "Input Dataset", "value": ""}
            else:
                pass
                # Eventually, allow regular tool parameters to be inserted and modified at runtime.
                # p = step.get_required_parameters()
        item["inputs"] = inputs
        steps = {}
        for step in latest_workflow.steps:
            steps[step.id] = {"id": step.id, "type": step.type, "tool_id": step.tool_id, "input_steps": {}}
            for conn in step.input_connections:
                steps[step.id]["input_steps"][conn.input_name] = {
                    "source_step": conn.output_step_id,
                    "step_output": conn.output_name,
                }
        item["steps"] = steps
        return item
Exemplo n.º 52
0
 def show(self, trans, id, **kwd):
     """
     GET /api/groups/{encoded_group_id}
     Displays information about a group.
     """
     group_id = id
     try:
         decoded_group_id = trans.security.decode_id(group_id)
     except TypeError:
         trans.response.status = 400
         return "Malformed group id ( %s ) specified, unable to decode." % str(group_id)
     try:
         group = trans.sa_session.query(trans.app.model.Group).get(decoded_group_id)
     except Exception:
         group = None
     if not group:
         trans.response.status = 400
         return "Invalid group id ( %s ) specified." % str(group_id)
     item = group.to_dict(view='element', value_mapper={'id': trans.security.encode_id})
     item['url'] = url_for('group', id=group_id)
     item['users_url'] = url_for('group_users', group_id=group_id)
     item['roles_url'] = url_for('group_roles', group_id=group_id)
     return item
Exemplo n.º 53
0
 def __api_import_shared_workflow(self, trans, workflow_id, payload, **kwd):
     try:
         stored_workflow = self.get_stored_workflow(trans, workflow_id, check_ownership=False)
     except Exception:
         raise exceptions.ObjectNotFound("Malformed workflow id ( %s ) specified." % workflow_id)
     if stored_workflow.importable is False:
         raise exceptions.ItemAccessibilityException('The owner of this workflow has disabled imports via this link.')
     elif stored_workflow.deleted:
         raise exceptions.ItemDeletionException("You can't import this workflow because it has been deleted.")
     imported_workflow = self._import_shared_workflow(trans, stored_workflow)
     item = imported_workflow.to_dict(value_mapper={'id': trans.security.encode_id})
     encoded_id = trans.security.encode_id(imported_workflow.id)
     item['url'] = url_for('workflow', id=encoded_id)
     return item
Exemplo n.º 54
0
    def show(self, trans, id, **kwd):
        """
        GET /api/workflows/{encoded_workflow_id}

        Displays information needed to run a workflow from the command line.
        """
        stored_workflow = self.__get_stored_workflow( trans, id )
        if stored_workflow.importable is False and stored_workflow.user != trans.user and not trans.user_is_admin():
            if trans.sa_session.query(trans.app.model.StoredWorkflowUserShareAssociation).filter_by(user=trans.user, stored_workflow=stored_workflow).count() == 0:
                message = "Workflow is neither importable, nor owned by or shared with current user"
                raise exceptions.ItemAccessibilityException( message )

        item = stored_workflow.to_dict( view='element', value_mapper={ 'id': trans.security.encode_id } )
        item['url'] = url_for('workflow', id=id)
        item['owner'] = stored_workflow.user.username
        latest_workflow = stored_workflow.latest_workflow
        inputs = {}
        for step in latest_workflow.steps:
            step_type = step.type
            if step_type in ['data_input', 'data_collection_input']:
                if step.tool_inputs and "name" in step.tool_inputs:
                    label = step.tool_inputs['name']
                elif step_type == "data_input":
                    label = "Input Dataset"
                elif step_type == "data_collection_input":
                    label = "Input Dataset Collection"
                else:
                    raise ValueError("Invalid step_type %s" % step_type)
                inputs[step.id] = {'label': label, 'value': ""}
            else:
                pass
                # Eventually, allow regular tool parameters to be inserted and modified at runtime.
                # p = step.get_required_parameters()
        item['inputs'] = inputs
        item['annotation'] = self.get_item_annotation_str( trans.sa_session, stored_workflow.user, stored_workflow )
        steps = {}
        for step in latest_workflow.steps:
            steps[step.id] = {'id': step.id,
                              'type': step.type,
                              'tool_id': step.tool_id,
                              'tool_version': step.tool_version,
                              'annotation': self.get_item_annotation_str( trans.sa_session, stored_workflow.user, step ),
                              'tool_inputs': step.tool_inputs,
                              'input_steps': {}}
            for conn in step.input_connections:
                steps[step.id]['input_steps'][conn.input_name] = {'source_step': conn.output_step_id,
                                                                  'step_output': conn.output_name}
        item['steps'] = steps
        return item
Exemplo n.º 55
0
    def submit_report(self, dataset, job, tool, **kwargs):
        """Doesn't do anything, just shows a link to submit on biostars.
        """
        try:
            assert biostar.biostar_enabled(self.app), ValueError("Biostar is not configured for this galaxy instance")
            assert self.app.config.biostar_enable_bug_reports, ValueError("Biostar is not configured to allow bug reporting for this galaxy instance")
            print(kwargs)

            url = url_for(controller='biostar',
                          action='biostar_tool_bug_report',
                          hda=self.app.security.encode_id(dataset.id),
                          email=kwargs['email'], message=kwargs['message'])
            return ('Click <a href="%s">here</a> to submit to BioStars' % url, 'success')
        except Exception as e:
            return ("An error occurred submitting the report to biostars: %s" % str(e), "danger")
Exemplo n.º 56
0
 def index(self, trans, **kwd):
     """
     GET /api/forms
     Displays a collection (list) of forms.
     """
     if not trans.user_is_admin():
         trans.response.status = 403
         return "You are not authorized to view the list of forms."
     query = trans.sa_session.query(trans.app.model.FormDefinition)
     rval = []
     for form_definition in query:
         item = form_definition.to_dict(value_mapper={'id': trans.security.encode_id, 'form_definition_current_id': trans.security.encode_id})
         item['url'] = url_for('form', id=trans.security.encode_id(form_definition.id))
         rval.append(item)
     return rval
Exemplo n.º 57
0
 def create( self, trans, payload, **kwd ):
     """
     POST /api/request_types
     Creates a new request type (external_service configuration).
     """
     if not trans.user_is_admin():
         trans.response.status = 403
         return "You are not authorized to create a new request type (external_service configuration)."
     xml_text = payload.get( 'xml_text', None )
     if xml_text is None:
         trans.response.status = 400
         return "Missing required parameter 'xml_text'."
     elem = XML( xml_text )
     request_form_id = payload.get( 'request_form_id', None )
     if request_form_id is None:
         trans.response.status = 400
         return "Missing required parameter 'request_form_id'."
     request_form = trans.sa_session.query( trans.app.model.FormDefinition ).get( trans.security.decode_id( request_form_id ) )
     sample_form_id = payload.get( 'sample_form_id', None )
     if sample_form_id is None:
         trans.response.status = 400
         return "Missing required parameter 'sample_form_id'."
     sample_form = trans.sa_session.query( trans.app.model.FormDefinition ).get( trans.security.decode_id( sample_form_id ) )
     external_service_id = payload.get( 'external_service_id', None )
     if external_service_id is None:
         trans.response.status = 400
         return "Missing required parameter 'external_service_id'."
     external_service = trans.sa_session.query( trans.app.model.ExternalService ).get( trans.security.decode_id( external_service_id ) )
     request_type = request_type_factory.from_elem( elem, request_form, sample_form, external_service )
     #FIXME: move permission building/setting to separate abstract method call and
     #allow setting individual permissions by role (currently only one action, so not strictly needed)
     role_ids = payload.get( 'role_ids', [] )
     roles = [ trans.sa_session.query( trans.model.Role ).get( trans.security.decode_id( i ) ) for i in role_ids ]# if trans.app.security_agent.ok_to_display( trans.user, i ) ]
     permissions = {}
     if roles:
         #yikes, there has to be a better way?
         for k, v in trans.model.RequestType.permitted_actions.items():
             permissions[ trans.app.security_agent.get_action( v.action ) ] = roles
     if permissions:
         trans.app.security_agent.set_request_type_permissions( request_type, permissions )
     
     #flush objects
     trans.sa_session.add( request_type )
     trans.sa_session.flush()
     encoded_id = trans.security.encode_id( request_type.id )
     item = request_type.get_api_value( view='element', value_mapper={ 'id': trans.security.encode_id, 'request_form_id': trans.security.encode_id, 'sample_form_id': trans.security.encode_id } )
     item['url'] = url_for( 'request_type', id=encoded_id )
     return [ item ]