示例#1
0
文件: plugin.py 项目: bbcf/pygdv
 def validation(*args, **kw):
     for arg in args_list:
         if arg not in kw:
             raise Exception('Missing args for the validation %s' % kw)
     user = DBSession.query(User).filter(User.email == str(kw['mail'])).first()
     if user.key != str(kw['key']):
         raise Exception('User not valid %s' % kw)
     project = DBSession.query(Project).filter(Project.id == int(kw['pid'])).first()
     if project.key != str(kw['pkey']):
         raise Exception('Project not valid %s' % kw)
     job = Job()
     job.user_id = user.id
     job.project_id = project.id
     job.status = 'PENDING'
     job.ext_task_id = kw['task_id']
     job.bioscript_url = handler.job.task_url(kw['task_id'])
     if 'plugin_info' in kw:
         info = json.loads(kw['plugin_info'])
         job.name = info['title']
         job.description = info['description']
     else:
         job.name = 'Job %s from bioscript' % kw['task_id']
         job.description = 'Description available at %s' % handler.job.task_url(kw['task_id'])
     DBSession.add(job)
     DBSession.flush()
     return {}
示例#2
0
def change_rights(project_id, circle_id, rights=None):
    '''
    Modify the right associated to a project to a group.
    If any right is added, automatically add read right.
    @param project_id : the project id
    @param circle_id : the circle id
    @param rights : the right to update
    '''
    project = DBSession.query(Project).filter(Project.id == project_id).first()
    rc_assocs = get_circle_right_assocs(circle_id, project_id)

    for rc in rc_assocs:
        if rc.circle.id == int(circle_id):
            project._circle_right.remove(rc)
            DBSession.delete(rc)
            DBSession.flush()

    if rights is not None:
        _add_read_right(project, circle_id)
        for right_name in rights:
            if right_name != constants.right_read:
                right = DBSession.query(Right).filter(
                    Right.name == right_name).first()
                cr_assoc = _get_circle_right_assoc(right, circle_id,
                                                   project_id)
                project._circle_right.append(cr_assoc)

    DBSession.add(project)
    DBSession.flush()
示例#3
0
def init(track, flush=False):
    p = {}
    doit = False
    if track.parameters is None:
        doit = True
    elif 'url' not in track.parameters:
        doit = True
        p = copy.deepcopy(track.parameters)

    if doit:
        p.update({
            'url':
            os.path.join(track.visualization, track.input.sha1, '{refseq}',
                         constants.track_data),
            'label':
            track.name,
            'type':
            track.visualization == 'signal' and 'ImageTrack' or 'FeatureTrack',
            'gdv_id':
            track.id,
            'key':
            track.name,
            'date':
            track.tiny_date
        })
        track.parameters = p
        if flush:
            DBSession.flush()
示例#4
0
文件: project.py 项目: bbcf/pygdv
def add_read_right(project, circle_id):    
    '''
    Add the ``read`` right to the project & circle specified. Flush the database
    '''
    _add_read_right(project, circle_id)
    DBSession.add(project)
    DBSession.flush()
示例#5
0
文件: sequence.py 项目: bbcf/pygdv
def add_new_sequence(sequence):
    '''
    Method called when a new sequence is created on GDV.
    It should import fast from JBrowse
    '''
    print 'add new sequence'
    file_url = Assembly(sequence).get_sqlite_url()
    print file_url
    out = os.path.join(filemanager.temporary_directory(), 'Genes.sql')
    fileinfo = filemanager.FileInfo(inputtype='url',
        inpath=file_url, trackname='Genes', extension='sql', outpath=out, admin=True)
    print fileinfo
    user = DBSession.query(User).filter(User.key == constants.admin_user_key()).first()
    user_info = {'id': user.id, 'name': user.name, 'email': user.email}
    sequence_info = {'id': sequence.id, 'name': sequence.name}

    # track
    t = Track()
    t.name = fileinfo.trackname
    t.sequence_id = sequence.id
    t.user_id = user.id
    DBSession.add(t)
    DBSession.flush()
    # send task
    async = tasks.new_input.delay(user_info, fileinfo, sequence_info, t.id)
    t.task_id = async.task_id
    DBSession.add(t)

    sequence.default_tracks.append(t)
    DBSession.add(sequence)
    DBSession.flush()
示例#6
0
def edit(project,
         name,
         user_id,
         sequence_id=None,
         tracks=None,
         isPublic=False,
         circles=None):
    '''
    Like create but edit an existing project.
    '''
    project.name = name
    if sequence_id is not None:
        project.sequence_id = sequence_id
    project.user_id = user_id
    project.is_public = isPublic
    DBSession.add(project)
    DBSession.flush()

    project.tracks = []
    if tracks is not None:
        for track_id in tracks:
            t = DBSession.query(Track).filter(Track.id == track_id).first()
            project.tracks.append(t)

    if circles is not None:  # adding circle with the read permission by default
        project._circle_right = []
        for circle in circles:
            _add_read_right(project, circle.id)

    DBSession.add(project)
    DBSession.flush()
    return project
示例#7
0
def add_user(circle=None, circle_id=None, user=None, user_id=None):
    if user is None:
        user = DBSession.query(User).filter(User.id == user_id).first()
    if circle is None:
        circle = DBSession.query(Circle).filter(Circle.id == circle_id).first()
    circle.users.append(user)
    DBSession.flush()
示例#8
0
def add_read_right(project, circle_id):
    '''
    Add the ``read`` right to the project & circle specified. Flush the database
    '''
    _add_read_right(project, circle_id)
    DBSession.add(project)
    DBSession.flush()
示例#9
0
文件: project.py 项目: bbcf/pygdv
def edit(project, name, user_id, sequence_id=None, tracks=None, isPublic=False, circles=None):
    '''
    Like create but edit an existing project.
    '''
    project.name=name
    if sequence_id is not None:
        project.sequence_id = sequence_id
    project.user_id = user_id
    project.is_public = isPublic
    DBSession.add(project)
    DBSession.flush()

    project.tracks = []
    if tracks is not None:
        for track_id in tracks :
            t = DBSession.query(Track).filter(Track.id == track_id).first()
            project.tracks.append(t)
    
   
    if circles is not None: # adding circle with the read permission by default
        project._circle_right = []
        for circle in circles : _add_read_right(project, circle.id)
    
    DBSession.add(project)
    DBSession.flush()
    return project
示例#10
0
def remove_sharing(project=None, project_id=None):
    if project is None:
        project = DBSession.query(Project).filter(
            Project.id == project_id).first()
    for rc in project._circle_right:
        DBSession.delete(rc)
    DBSession.flush()
示例#11
0
文件: plugin.py 项目: yjarosz/pygdv
 def validation(*args, **kw):
     for arg in args_list:
         if arg not in kw:
             raise Exception('Missing args for the validation %s' % kw)
     user = DBSession.query(User).filter(
         User.email == str(kw['mail'])).first()
     if user.key != str(kw['key']):
         raise Exception('User not valid %s' % kw)
     project = DBSession.query(Project).filter(
         Project.id == int(kw['pid'])).first()
     if project.key != str(kw['pkey']):
         raise Exception('Project not valid %s' % kw)
     job = Job()
     job.user_id = user.id
     job.project_id = project.id
     job.status = 'PENDING'
     job.ext_task_id = kw['task_id']
     job.bioscript_url = handler.job.task_url(kw['task_id'])
     if 'plugin_info' in kw:
         info = json.loads(kw['plugin_info'])
         job.name = info['title']
         job.description = info['description']
     else:
         job.name = 'Job %s from bioscript' % kw['task_id']
         job.description = 'Description available at %s' % handler.job.task_url(
             kw['task_id'])
     DBSession.add(job)
     DBSession.flush()
     return {}
示例#12
0
文件: sequence.py 项目: bbcf/pygdv
 def delete_track(self, sequence_id, track_id):
     user = handler.user.get_user_in_session(request)
     s = DBSession.query(Sequence).filter(Sequence.id == sequence_id).first()
     t = DBSession.query(Track).filter(Track.id == track_id).first()
     s.default_tracks.remove(t)
     DBSession.flush()
     raise redirect('/sequences/edit/%s' % sequence_id)
示例#13
0
文件: sequence.py 项目: bbcf/pygdv
 def delete_user(self, user_id, sequence_id):
     user = handler.user.get_user_in_session(request)
     s = DBSession.query(Sequence).filter(Sequence.id == sequence_id).first()
     u = DBSession.query(User).filter(User.id == user_id).first()
     s.users.remove(u)
     DBSession.flush()
     raise redirect('/sequences/edit/%s' % sequence_id)
示例#14
0
文件: project.py 项目: bbcf/pygdv
def change_rights(project_id, circle_id, rights=None):
    '''
    Modify the right associated to a project to a group.
    If any right is added, automatically add read right.
    @param project_id : the project id
    @param circle_id : the circle id
    @param rights : the right to update
    '''
    project = DBSession.query(Project).filter(Project.id == project_id).first()
    rc_assocs = get_circle_right_assocs(circle_id, project_id)
    
    
    for rc in rc_assocs:
        if rc.circle.id == int(circle_id) :
            project._circle_right.remove(rc)
            DBSession.delete(rc)
            DBSession.flush()

    if rights is not None:
        _add_read_right(project, circle_id)
        for right_name in rights:
            if right_name != constants.right_read :
                right = DBSession.query(Right).filter(Right.name == right_name).first()
                cr_assoc = _get_circle_right_assoc(right, circle_id, project_id)
                project._circle_right.append(cr_assoc)

    DBSession.add(project)
    DBSession.flush()
示例#15
0
def delete(project=None, project_id=None):
    if project is None:
        project = DBSession.query(Project).filter(
            Project.id == project_id).first()
    remove_sharing(project=project)
    DBSession.delete(project)
    DBSession.flush()
示例#16
0
文件: track.py 项目: yjarosz/pygdv
    def after_sha1(self, fname, sha1, force, callback_url, track_id, old_task_id, mail, key, sequence_id, extension, trackname):
        """
        Called after a sha1 where calculated on a file.
        If the sha1 already exist, only the databases operations are done.
        Else the input will go in the second part of the process.
        The input can be 'forced' to be recomputed
        """
        try:
            _input = DBSession.query(Input).filter(Input.sha1 == sha1).first()
            do_process = True
            if util.str2bool(force) and _input is not None:
                handler.track.delete_input(_input.sha1)
                DBSession.delete(_input)
                DBSession.flush()
            elif _input is not None:
                do_process = False
                handler.track.update(track_id=track_id,
                    params={'new_input_id': _input.id})
                handler.track.finalize_track_creation(track_id=track_id)

            if do_process:

                handler.track.update(track_id=track_id, params={'sha1': sha1})
                sequence = DBSession.query(Sequence).filter(Sequence.id == sequence_id).first()
                async = tasks.track_process.delay(mail, key, old_task_id, fname, sha1, callback_url, track_id, sequence.name, extension, trackname, callback_url)

                handler.track.update(track_id=track_id,
                    params={'new_task_id': async.task_id})
            return {'success': 'to second process'}
        except Exception as e:
            etype, value, tb = sys.exc_info()
            traceback.print_exception(etype, value, tb)


            return {'error': str(e)}
示例#17
0
文件: sequence.py 项目: yjarosz/pygdv
 def delete_user(self, user_id, sequence_id):
     user = handler.user.get_user_in_session(request)
     s = DBSession.query(Sequence).filter(
         Sequence.id == sequence_id).first()
     u = DBSession.query(User).filter(User.id == user_id).first()
     s.users.remove(u)
     DBSession.flush()
     raise redirect('/sequences/edit/%s' % sequence_id)
示例#18
0
文件: project.py 项目: bbcf/pygdv
def add_read_right_to_circles_ids(project, ids):
    '''
     Add the ``read`` right to the project & circles specified. Flush the database
    '''  
    for id in ids:
        _add_read_right(project, id)
    DBSession.add(project)
    DBSession.flush()
示例#19
0
def add_read_right_to_circles_ids(project, ids):
    '''
     Add the ``read`` right to the project & circles specified. Flush the database
    '''
    for id in ids:
        _add_read_right(project, id)
    DBSession.add(project)
    DBSession.flush()
示例#20
0
文件: sequence.py 项目: yjarosz/pygdv
 def delete_track(self, sequence_id, track_id):
     user = handler.user.get_user_in_session(request)
     s = DBSession.query(Sequence).filter(
         Sequence.id == sequence_id).first()
     t = DBSession.query(Track).filter(Track.id == track_id).first()
     s.default_tracks.remove(t)
     DBSession.flush()
     raise redirect('/sequences/edit/%s' % sequence_id)
示例#21
0
文件: sequence.py 项目: bbcf/pygdv
    def edit(self, *args, **kw):
        user = handler.user.get_user_in_session(request)

        # get circle id
        if request.method == 'GET':
            sequence_id = args[0]
        else :
            sequence_id = kw.get('cid')

        sequence_id=int(sequence_id)
        sequence = DBSession.query(Sequence).filter(Sequence.id == sequence_id).first()
        if not sequence:
            abort(404, 'Sequence with id %s not found' % sequence_id)

        if not sequence.public:
            add_user_widget = form.AddUser(action=url('/sequences/edit/%s' % sequence_id)).req()

            if request.method == 'POST':
                # add an user
                mail = kw.get('mail')
                try:
                    add_user_widget.validate({'cid' : sequence_id, 'mail' : mail})
                except twc.ValidationError as e:
                    users = ', '.join(['%s' % u.email for u in sequence.users])
                    default_tracks = ', '.join(['%s' % t.name for t in sequence.default_tracks])
                    kw['cid'] = sequence_id
                    users = sequence.users
                    for u in users:
                        u.__dict__['sid'] = sequence_id
                    widget = e.widget
                    widget.value = kw
                    return dict(page='sequences', users=users, add_user=add_user, add_user_widget=add_user_widget, default_tracks=default_tracks, au_error=True, seq_id=sequence_id)

                to_add = DBSession.query(User).filter(User.email == mail).first()
                if to_add is None:
                    to_add = handler.user.create_tmp_user(mail)
                sequence.users.append(to_add)
                DBSession.flush()

            kw['cid'] = sequence_id
            add_user_widget.value = kw

        else:
            add_user_widget = None

        users = sequence.users
        for u in users:
            u.__dict__['sid'] = sequence_id

        tracks = sequence.default_tracks
        for t in tracks:
            t.__dict__['sid'] = sequence_id

        add_user = util.to_datagrid(datagrid.sequence_user_grid, users, "Users", len(users)>0)

        def_tracks = util.to_datagrid(datagrid.sequence_default_tracks, tracks, "Default tracks", len(tracks)>0)

        return dict(page='sequences', users=users, add_user=add_user, add_user_widget=add_user_widget, default_tracks=def_tracks, au_error=False, seq_id=sequence_id)
示例#22
0
def add_tracks(project, track_ids):
    '''
    Add a list of track to the project specified.
    '''
    for track_id in track_ids:
        track_ = DBSession.query(Track).filter(Track.id == track_id).first()
        project.tracks.append(track_)
    DBSession.add(project)
    DBSession.flush()
示例#23
0
文件: project.py 项目: bbcf/pygdv
def add_tracks(project, track_ids):
    '''
    Add a list of track to the project specified.
    '''
    for track_id in track_ids:
        track_ = DBSession.query(Track).filter(Track.id == track_id).first()
        project.tracks.append(track_)
    DBSession.add(project)
    DBSession.flush()
示例#24
0
 def delete(self, circle_id, *args, **kw):
     user = handler.user.get_user_in_session(request)
     if not checker.user_own_circle(user.id, circle_id):
         flash('you have no right to delete this circle: you are not the creator of it')
         raise redirect('/circles')
     circle = DBSession.query(Circle).filter(Circle.id == circle_id).first()
     DBSession.delete(circle)
     DBSession.flush()
     raise redirect('/circles/')
示例#25
0
 def delete_user(self, id, user_id):
     user = handler.user.get_user_in_session(request)
     if not checker.user_own_circle(user.id, id):
         flash('you have no rights to delete users from this circle: you are not the creator of it')
         raise redirect('/circles')
     circle = DBSession.query(Circle).filter(Circle.id == id).first()
     to_delete = DBSession.query(User).filter(User.id == user_id).first()
     circle.users.remove(to_delete)
     DBSession.flush()
     raise redirect('/circles/edit/%s' % id)
示例#26
0
文件: user.py 项目: bbcf/pygdv
def create_tmp_user(mail):
    user = User()
    user.name = constants.tmp_user_name
    user.email = mail
    user.firstname = ''
    user_group = DBSession.query(Group).filter(Group.id == constants.group_users_id).first()
    user_group.users.append(user)
    DBSession.add(user)
    DBSession.flush()
    return user
示例#27
0
文件: track.py 项目: yjarosz/pygdv
 def after_process(self, mail, key, old_task_id, track_id, datatype):
     print '[x] after process [x] %s' % track_id
     task = DBSession.query(Task).filter(Task.task_id == old_task_id).first()
     if task is not None:
         DBSession.delete(task)
         DBSession.flush()
     if not track_id == 'None':
         handler.track.update(track_id=track_id, params={'datatype': datatype})
         handler.track.finalize_track_creation(track_id=track_id)
     return {'success': 'end'}
示例#28
0
文件: user.py 项目: yjarosz/pygdv
def create_tmp_user(mail):
    user = User()
    user.name = constants.tmp_user_name
    user.email = mail
    user.firstname = ''
    user_group = DBSession.query(Group).filter(
        Group.id == constants.group_users_id).first()
    user_group.users.append(user)
    DBSession.add(user)
    DBSession.flush()
    return user
示例#29
0
    def index(self, came_from='/'):
        '''
        Redirect user on tequila page in order to log him
        '''
        if tg.config.get('authentication.disable').lower() in ['t', 'true']:
            print constants.admin_user_email()

            environ = request.environ
            authentication_plugins = environ['repoze.who.plugins']
            identifier = authentication_plugins['ticket']
            secret = identifier.secret
            cookiename = identifier.cookie_name
            remote_addr = environ['REMOTE_ADDR']
            user = DBSession.query(User).filter(
                User.email == constants.admin_user_email()).first()
            admins = tg.config.get('admin.mails')
            group_admins = DBSession.query(Group).filter(
                Group.id == constants.group_admins_id).first()
            if user.email in admins:
                user not in group_admins.users and group_admins.users.append(
                    user)
            else:
                user in group_admins.users and group_admins.users.remove(user)
            DBSession.flush()
            userdata = "%s|%s" % (user.id, user in group_admins.users)

            ticket = auth_tkt.AuthTicket(secret,
                                         user.email,
                                         remote_addr,
                                         tokens=token,
                                         user_data=userdata,
                                         time=None,
                                         cookie_name=cookiename,
                                         secure=True)

            val = ticket.cookie_value()
            # set it in the cookies
            response.set_cookie(cookiename,
                                value=val,
                                max_age=None,
                                path='/',
                                domain=None,
                                secure=False,
                                httponly=False,
                                comment=None,
                                expires=None,
                                overwrite=False)
            raise redirect(came_from)

        u = resolve_relative_url(url(), request.environ)
        res = tequila.create_request(u + '/login/auth', 'tequila.epfl.ch')
        raise redirect(
            'https://tequila.epfl.ch/cgi-bin/tequila/requestauth?request' +
            res)
示例#30
0
def create_admin(name):
    '''
    Create a new admin circle.
    @param name : the name
    '''
    c = Circle()
    c.name = name
    c.description = 'Circle created with Tequila'
    c.admin = True
    DBSession.add(c)
    DBSession.flush()
    return c
示例#31
0
文件: selection.py 项目: bbcf/pygdv
 def delete(self, project_id, selection_id):
     user = handler.user.get_user_in_session(request)
     if not checker.check_permission(user=user, project_id=project_id, right_id=constants.right_upload_id):
         flash('You must have %s permission to delete the project.' % constants.right_upload, 'error')
         return {'delete': 'failed'}
     selection = DBSession.query(Selection).filter(Selection.id == selection_id).first()
     if not selection.project_id == project_id:
         flash('Bad project_id: %s' % project_id, 'error')
         return {'delete': 'failed'}
     DBSession.delete(selection)
     DBSession.flush()
     return {'delete': 'success'}
示例#32
0
def edit(track=None, track_id=None, name=None, color=None):
    if track is None:
        track = DBSession.query(Track).filter(Track.id == track_id).first()
    debug('edit track %s' % track)
    if name is not None:
        track.name = name
    if track.parameters is None:
        init(track)
    if color is not None:
        p = copy.deepcopy(track.parameters)
        p.update({'color': color})
        track.parameters = p
    DBSession.flush()
示例#33
0
def edit(c, name, description, creator, users=None):
    c.name = name
    c.description = description
    c.creator_id = creator.id
    c.users = []
    if users is not None:
        for user_id in users:
            if not int(user_id) == creator.id:
                u = DBSession.query(User).filter(User.id == user_id).first()
                c.users.append(u)
    c.users.append(creator)
    DBSession.add(c)
    DBSession.flush()
示例#34
0
文件: track.py 项目: bbcf/pygdv
def edit(track=None, track_id=None, name=None, color=None):
    if track is None:
        track = DBSession.query(Track).filter(Track.id == track_id).first()
    debug('edit track %s' % track)
    if name is not None:
        track.name = name
    if track.parameters is None:
        init(track)
    if color is not None:
        p = copy.deepcopy(track.parameters)
        p.update({'color': color})
        track.parameters = p
    DBSession.flush()
示例#35
0
文件: plugin.py 项目: bbcf/pygdv
    def callback(self, *args, **kw):
        print kw
        job = DBSession.query(Job).filter(Job.ext_task_id == kw['task_id']).first()
        project = DBSession.query(Project).filter(Project.id == int(kw['pid'])).first()
        if project is None or project.key != str(kw['pkey']):
            raise Exception('Project not valid')
        if job.project_id != project.id:
            raise Exception('Job not valid')

        status = str(kw['status'])
        job.status = status
        if status.lower() in ['error', 'failed']:
            job.traceback = kw['error']
        elif status == 'SUCCESS':
            results = json.loads(kw['results'])
            for result in results:
                bres = Bresults()
                bres.job_id = job.id
                bres.output_type = str(result.get('type', 'not defined'))
                bres.is_file = result.get('is_file', False)
                path = str(result.get('path', ''))
                bres.path = path
                bres.data = str(result.get('value', ''))

                is_track = result.get('type', '') == 'track'
                if is_track:
                    out = os.path.join(filemanager.temporary_directory(), os.path.split(path)[-1])
                    fileinfo = filemanager.FileInfo(inputtype='fsys', inpath=path, outpath=out, admin=False)
                    sequence = project.sequence
                    user = DBSession.query(User).filter(User.key == str(kw['key'])).first()
                    if user.email != str(kw['mail']):
                        raise Exception("Wrong user")
                    user_info = {'id': user.id, 'name': user.name, 'email': user.email}
                    sequence_info = {'id': sequence.id, 'name': sequence.name}

                    t = Track()
                    t.name = fileinfo.trackname
                    t.sequence_id = sequence.id
                    t.user_id = user.id
                    DBSession.add(t)
                    DBSession.flush()
                    async = tasks.new_input.delay(user_info, fileinfo, sequence_info, t.id, project.id)
                    t.task_id = async.task_id
                    bres.track_id = t.id

                bres.is_track = is_track
                DBSession.add(bres)
        DBSession.flush()
        return {}
示例#36
0
def delete_track(track=None, track_id=None):
    '''
    Delete the track and the input associated if this is the only track with this input.
    '''
    if track is None:
        track = DBSession.query(Track).filter(Track.id == track_id).first()
    if track is None:
        return
    _input = track.input
    if _input is not None:
        if len(_input.tracks) == 1:
            delete_input(_input.sha1)
            DBSession.delete(_input)
    DBSession.delete(track)
    DBSession.flush()
示例#37
0
文件: track.py 项目: bbcf/pygdv
def delete_track(track=None, track_id=None):
    '''
    Delete the track and the input associated if this is the only track with this input.
    '''
    if track is None:
        track = DBSession.query(Track).filter(Track.id == track_id).first()
    if track is None:
        return
    _input = track.input
    if _input is not None:
        if len(_input.tracks) == 1:
            delete_input(_input.sha1)
            DBSession.delete(_input)
    DBSession.delete(track)
    DBSession.flush()
示例#38
0
文件: login.py 项目: bbcf/pygdv
 def check_circles_with_user(self, user, principal):
     '''
     Check if the groups that are in tequila and add the user to it.
     This method is here because at first, circles was not created with `allunits` parameters but with `groups`
     one. So users that are logged already must be re-added to the right groups
     '''
     hash = dict(item.split('=') for item in principal.split('\n') if len(item.split('=')) > 1)
     if 'allunits' in hash:
         group_list = hash.get('allunits').split(',')
         for group_name in group_list:
             circle = handler.circle.get_tequila_circle(group_name)
             if circle is None:
                 circle = handler.circle.create_admin(group_name)
             circle.users.append(user)
             DBSession.flush()
示例#39
0
 def check_circles_with_user(self, user, principal):
     '''
     Check if the groups that are in tequila and add the user to it.
     This method is here because at first, circles was not created with `allunits` parameters but with `groups`
     one. So users that are logged already must be re-added to the right groups
     '''
     hash = dict(
         item.split('=') for item in principal.split('\n')
         if len(item.split('=')) > 1)
     if 'allunits' in hash:
         group_list = hash.get('allunits').split(',')
         for group_name in group_list:
             circle = handler.circle.get_tequila_circle(group_name)
             if circle is None:
                 circle = handler.circle.create_admin(group_name)
             circle.users.append(user)
             DBSession.flush()
示例#40
0
 def delete(self, project_id, selection_id):
     user = handler.user.get_user_in_session(request)
     if not checker.check_permission(user=user,
                                     project_id=project_id,
                                     right_id=constants.right_upload_id):
         flash(
             'You must have %s permission to delete the project.' %
             constants.right_upload, 'error')
         return {'delete': 'failed'}
     selection = DBSession.query(Selection).filter(
         Selection.id == selection_id).first()
     if not selection.project_id == project_id:
         flash('Bad project_id: %s' % project_id, 'error')
         return {'delete': 'failed'}
     DBSession.delete(selection)
     DBSession.flush()
     return {'delete': 'success'}
示例#41
0
文件: login.py 项目: bbcf/pygdv
 def build_circles_with_user(self, user, principal, u=None):
     '''
     Build the groups that are in tequila and add the user to it.
     Must use the ``fake user``
     '''
     hash = dict(item.split('=') for item in principal.split('\n') if len(item.split('=')) > 1)
     if 'allunits' in hash:
         group_list = hash.get('allunits').split(',')
         for group_name in group_list:
             circle = handler.circle.get_tequila_circle(group_name)
             if circle is None:
                 circle = handler.circle.create_admin(group_name)
             if u:
                 circle.users.append(u)
             else:
                 circle.users.append(user)
             DBSession.flush()
示例#42
0
 def build_circles_with_user(self, user, principal, u=None):
     '''
     Build the groups that are in tequila and add the user to it.
     Must use the ``fake user``
     '''
     hash = dict(
         item.split('=') for item in principal.split('\n')
         if len(item.split('=')) > 1)
     if 'allunits' in hash:
         group_list = hash.get('allunits').split(',')
         for group_name in group_list:
             circle = handler.circle.get_tequila_circle(group_name)
             if circle is None:
                 circle = handler.circle.create_admin(group_name)
             if u:
                 circle.users.append(u)
             else:
                 circle.users.append(user)
             DBSession.flush()
示例#43
0
文件: track.py 项目: bbcf/pygdv
def init(track, flush=False):
    p = {}
    doit = False
    if track.parameters is None:
        doit = True
    elif 'url' not in track.parameters:
        doit = True
        p = copy.deepcopy(track.parameters)

    if doit:
        p.update({
                'url': os.path.join(track.visualization, track.input.sha1, '{refseq}', constants.track_data),
                'label': track.name,
                'type': track.visualization == 'signal' and 'ImageTrack' or 'FeatureTrack',
                'gdv_id': track.id,
                'key': track.name,
                'date': track.tiny_date
                })
        track.parameters = p
        if flush:
            DBSession.flush()
示例#44
0
文件: project.py 项目: bbcf/pygdv
def e(project=None, project_id=None, name=None, track_ids=None, circle_ids=None):
    if project is None:
        project = DBSession.query(Project).filter(Project.id == project_id).first()

    if name is not None:
        project.name = name

    if track_ids is not None:
        project.tracks = []
        for tid in track_ids:
            t = DBSession.query(Track).filter(Track.id == tid).first()
            project.tracks.append(t)

    if circle_ids is not None:
        if not isinstance(circle_ids, list):
            circle_ids = [circle_ids]
        circle_ids = [int(i) for i in circle_ids]
        to_del = []
        for shared in project._circle_right:
            if shared.circle.id not in circle_ids:
                to_del.append(shared)
        for d in to_del:
            DBSession.delete(d)
            project._circle_right.remove(d)
        DBSession.flush()

        shared_ids = [c.id for c in project.shared_circles]
        read_right = DBSession.query(Right).filter(Right.id == constants.rights['read']['id']).first()
        for new_id in circle_ids:
            if new_id not in shared_ids:
                add_right(project=project, circle_id=new_id, right=read_right)
        DBSession.flush()
    DBSession.add(project)
    DBSession.flush()
    return project
示例#45
0
文件: login.py 项目: bbcf/pygdv
    def index(self, came_from='/'):
        '''
        Redirect user on tequila page in order to log him
        '''
        if tg.config.get('authentication.disable').lower() in ['t', 'true']:
            print constants.admin_user_email()

            environ = request.environ
            authentication_plugins = environ['repoze.who.plugins']
            identifier = authentication_plugins['ticket']
            secret = identifier.secret
            cookiename = identifier.cookie_name
            remote_addr = environ['REMOTE_ADDR']
            user = DBSession.query(User).filter(User.email == constants.admin_user_email()).first()
            admins = tg.config.get('admin.mails')
            group_admins = DBSession.query(Group).filter(Group.id == constants.group_admins_id).first()
            if user.email in admins:
                user not in group_admins.users and group_admins.users.append(user)
            else:
                user in group_admins.users and group_admins.users.remove(user)
            DBSession.flush()
            userdata = "%s|%s" % (user.id, user in group_admins.users)

            ticket = auth_tkt.AuthTicket(
                secret, user.email, remote_addr, tokens=token,
                user_data=userdata, time=None, cookie_name=cookiename,
                secure=True)

            val = ticket.cookie_value()
            # set it in the cookies
            response.set_cookie(
                cookiename, value=val, max_age=None, path='/', domain=None, secure=False,
                httponly=False, comment=None, expires=None, overwrite=False)
            raise redirect(came_from)

        u = resolve_relative_url(url(), request.environ)
        res = tequila.create_request(u + '/login/auth', 'tequila.epfl.ch')
        raise redirect('https://tequila.epfl.ch/cgi-bin/tequila/requestauth?request' + res)
示例#46
0
文件: sequence.py 项目: yjarosz/pygdv
def add_new_sequence(sequence):
    '''
    Method called when a new sequence is created on GDV.
    It should import fast from JBrowse
    '''
    print 'add new sequence'
    file_url = Assembly(sequence).get_sqlite_url()
    print file_url
    out = os.path.join(filemanager.temporary_directory(), 'Genes.sql')
    fileinfo = filemanager.FileInfo(inputtype='url',
                                    inpath=file_url,
                                    trackname='Genes',
                                    extension='sql',
                                    outpath=out,
                                    admin=True)
    print fileinfo
    user = DBSession.query(User).filter(
        User.key == constants.admin_user_key()).first()
    user_info = {'id': user.id, 'name': user.name, 'email': user.email}
    sequence_info = {'id': sequence.id, 'name': sequence.name}

    # track
    t = Track()
    t.name = fileinfo.trackname
    t.sequence_id = sequence.id
    t.user_id = user.id
    DBSession.add(t)
    DBSession.flush()
    # send task
    async = tasks.new_input.delay(user_info, fileinfo, sequence_info, t.id)
    t.task_id = async .task_id
    DBSession.add(t)

    sequence.default_tracks.append(t)
    DBSession.add(sequence)
    DBSession.flush()
示例#47
0
文件: util.py 项目: yjarosz/pygdv
def track_info(tracks, assembly_id=None):
    '''
    Build ``trackInfo`` variable.
    '''
    l = []
    if assembly_id is not None:
        l = [{'url':'tinfo_url',
                  'args': {'chunkSize': 20000},
                  'label':'DNA',
                  'type':'SequenceTrack',
                  'key':'DNA'}]
    for track in tracks:
        if track.parameters is None:
            track.parameters = {
                    'url': os.path.join(track.visualization, track.input.sha1, '{refseq}', constants.track_data),
                    'label': track.name,
                    'type': track.visualization == 'signal' and 'ImageTrack' or 'FeatureTrack',
                    'gdv_id': track.id,
                    'key': track.name,
                    'date': track.tiny_date
                }
    DBSession.flush()
    l += [track.parameters for track in tracks]
    return l
示例#48
0
文件: sequence.py 项目: bbcf/pygdv
    def index(self, *args, **kw):

        seq_form = form.NewSequenceForm(action=url('/sequences')).req()
        species = genrep.get_species()

        m = {}
        sp_to_add = []
        for sp in species:
            assemblies = genrep.get_assemblies_not_created_from_species_id(sp.id)
            if len(assemblies) > 0:
                m[sp.id] = [(ass.id, ass.name) for ass in assemblies]
                sp_to_add.append(sp)
        sp_opts =  [(sp.id, sp.species) for sp in sp_to_add]
        seq_form.child.children[1].options = sp_opts
        value = {'smapping' : json.dumps(m)}
        seq_form.value = value
        grid = datagrid.sequences_grid


        if request.method == 'GET':
            sequences = DBSession.query(Sequence).all()
            seq_grid = [util.to_datagrid(grid, sequences, "Sequences", len(sequences)>0)]

            return dict(page="sequences", widget=seq_form, grid=seq_grid)
        else :
            species_id = kw['species']
            assembly_id = kw['assembly']
            # look if the species already exist in GDV, else create it
            species = DBSession.query(Species).filter(Species.id == species_id).first()
            if not species:
                species = handler.genrep.get_species_by_id(species_id)
                current_sp = Species()
                current_sp.id = species.id
                current_sp.name = species.species
                DBSession.add(current_sp)
                DBSession.flush()
                current_sp = DBSession.query(Species).filter(Species.id == species_id).first()
                flash( '''Species created: %s'''%( current_sp ))

            # look if the assembly not already created, else create it
            if not DBSession.query(Sequence).filter(Sequence.id == assembly_id).first():
                assembly = handler.genrep.get_assembly_by_id(assembly_id)
                seq = Sequence()
                seq.id = assembly_id
                seq.name = assembly.name
                seq.species_id = species_id
                DBSession.add(seq)
                DBSession.flush()
                seq = DBSession.query(Sequence).filter(Sequence.id == assembly_id).first()
                handler.sequence.add_new_sequence(seq)
                flash( '''Sequence created: %s'''%( seq ))
            DBSession.flush()
            sequences = DBSession.query(Sequence).all()
            seq_grid = [util.to_datagrid(grid, sequences, "Sequences", len(sequences)>0)]
            return dict(page="sequences", widget=seq_form, grid=seq_grid)
示例#49
0
    def save(self, project_id, color, description, locations):
        user = handler.user.get_user_in_session(request)

        if not checker.check_permission(user=user,
                                        project_id=project_id,
                                        right_id=constants.right_upload_id):
            flash(
                'You must have %s permission to delete the project.' %
                constants.right_upload, 'error')
            return {'save': 'failed'}

        #print "save %s, color %s, desc %s loc %s" % (project_id, color, description, locations)
        ''' For the moment, there is only one selection per project'''
        sel = DBSession.query(Selection).filter(
            Selection.project_id == project_id).first()
        if sel is None:
            sel = Selection()
            sel.project_id = project_id

        sel.description = description
        sel.color = color
        DBSession.add(sel)
        DBSession.flush()

        locations_ids = []
        # add locations
        for loc in json.loads(locations):
            obj = None
            if 'id' in loc:
                obj = DBSession.query(Location).join(
                    Selection.locations).filter(
                        and_(Selection.id == sel.id,
                             Location.id == loc.get('id'))).first()

            if obj is None:
                obj = Location()

            obj.chromosome = loc.get('chr')
            obj.start = loc.get('start')
            obj.end = loc.get('end')
            obj.description = loc.get('desc', 'No description')
            obj.selection = sel
            DBSession.add(obj)
            DBSession.flush()
            locations_ids.append(obj.id)
        # remove not saved ones
        loc_to_remove = DBSession.query(Location).filter(
            not_(Location.id.in_(locations_ids))).all()
        for l in loc_to_remove:
            DBSession.delete(l)
        DBSession.flush()
        return {"saved": "ok"}
示例#50
0
文件: selection.py 项目: bbcf/pygdv
    def save(self, project_id, color, description, locations):
        user = handler.user.get_user_in_session(request)

        if not checker.check_permission(user=user, project_id=project_id, right_id=constants.right_upload_id):
            flash('You must have %s permission to delete the project.' % constants.right_upload, 'error')
            return {'save': 'failed'}

        #print "save %s, color %s, desc %s loc %s" % (project_id, color, description, locations)
        ''' For the moment, there is only one selection per project'''
        sel = DBSession.query(Selection).filter(Selection.project_id == project_id).first()
        if sel is None:
            sel = Selection()
            sel.project_id = project_id

        sel.description = description
        sel.color = color
        DBSession.add(sel)
        DBSession.flush()

        locations_ids = []
        # add locations
        for loc in json.loads(locations):
            obj = None
            if 'id' in loc:
                obj = DBSession.query(Location).join(Selection.locations).filter(
                        and_(Selection.id == sel.id, Location.id == loc.get('id'))).first()

            if obj is None:
                obj = Location()

            obj.chromosome = loc.get('chr')
            obj.start = loc.get('start')
            obj.end = loc.get('end')
            obj.description = loc.get('desc', 'No description')
            obj.selection = sel
            DBSession.add(obj)
            DBSession.flush()
            locations_ids.append(obj.id)
        # remove not saved ones
        loc_to_remove = DBSession.query(Location).filter(not_(Location.id.in_(locations_ids))).all()
        for l in loc_to_remove:
            DBSession.delete(l)
        DBSession.flush()
        return {"saved": "ok"}
示例#51
0
def e(project=None,
      project_id=None,
      name=None,
      track_ids=None,
      circle_ids=None):
    if project is None:
        project = DBSession.query(Project).filter(
            Project.id == project_id).first()

    if name is not None:
        project.name = name

    if track_ids is not None:
        project.tracks = []
        for tid in track_ids:
            t = DBSession.query(Track).filter(Track.id == tid).first()
            project.tracks.append(t)

    if circle_ids is not None:
        if not isinstance(circle_ids, list):
            circle_ids = [circle_ids]
        circle_ids = [int(i) for i in circle_ids]
        to_del = []
        for shared in project._circle_right:
            if shared.circle.id not in circle_ids:
                to_del.append(shared)
        for d in to_del:
            DBSession.delete(d)
            project._circle_right.remove(d)
        DBSession.flush()

        shared_ids = [c.id for c in project.shared_circles]
        read_right = DBSession.query(Right).filter(
            Right.id == constants.rights['read']['id']).first()
        for new_id in circle_ids:
            if new_id not in shared_ids:
                add_right(project=project, circle_id=new_id, right=read_right)
        DBSession.flush()
    DBSession.add(project)
    DBSession.flush()
    return project
示例#52
0
文件: project.py 项目: bbcf/pygdv
def remove_sharing(project=None, project_id=None):
    if project is None:
        project = DBSession.query(Project).filter(Project.id == project_id).first()
    for rc in project._circle_right:
        DBSession.delete(rc)
    DBSession.flush()
示例#53
0
文件: project.py 项目: bbcf/pygdv
def delete(project=None, project_id=None):
    if project is None:
        project = DBSession.query(Project).filter(Project.id == project_id).first()
    remove_sharing(project=project)
    DBSession.delete(project)
    DBSession.flush()
示例#54
0
文件: login.py 项目: bbcf/pygdv
    def auth(self, came_from='/', **kw):
        '''
        Fetch user back from tequila.
        Validate the key from tequila.
        Log user.
        '''
        if not 'key' in kw:
            raise redirect(came_from)

        # take parameters
        key = kw.get('key')
        environ = request.environ
        authentication_plugins = environ['repoze.who.plugins']
        identifier = authentication_plugins['ticket']
        secret = identifier.secret
        cookiename = identifier.cookie_name
        remote_addr = environ['REMOTE_ADDR']
        # get user
        principal = tequila.validate_key(key, 'tequila.epfl.ch')
        if principal is None:
            raise redirect('./login')
        tmp_user = self.build_user(principal)
        mail = tmp_user.email
        # log or create him
        user = DBSession.query(User).filter(User.email == tmp_user.email).first()
        if user is None:
            user_group = DBSession.query(Group).filter(Group.id == constants.group_users_id).first()
            user_group.users.append(tmp_user)
            DBSession.add(tmp_user)
            DBSession.flush()
            #transaction.commit()
            user = DBSession.query(User).filter(User.email == mail).first()
            flash('Your account has been created')
            DBSession.flush()
            self.build_circles_with_user(tmp_user, principal)
            DBSession.flush()
            #transaction.commit()
        elif user.name == constants.tmp_user_name:
            user.name = tmp_user.name
            user.firstname = tmp_user.firstname
            user._set_date(datetime.datetime.now())
            #user_group = DBSession.query(Group).filter(Group.id == constants.group_users_id).first()
            #user_group.users.append(tmp_user)
            flash('Your account has been created')
            DBSession.flush()
            self.build_circles_with_user(tmp_user, principal, user)
            DBSession.flush()
            #transaction.commit()
        else:
            flash('Welcome back', 'notice')
            self.check_circles_with_user(user, principal)

        # look if an user is admin or not
        admins = tg.config.get('admin.mails')
        group_admins = DBSession.query(Group).filter(Group.id == constants.group_admins_id).first()
        if user.email in admins:
            user not in group_admins.users and group_admins.users.append(user)
        else:
            user in group_admins.users and group_admins.users.remove(user)
        DBSession.flush()
        # create the authentication ticket
        user = DBSession.query(User).filter(User.email == mail).first()

        userdata = "%s|%s" % (user.id, user in group_admins.users)

        ticket = auth_tkt.AuthTicket(
                                       secret, user.email, remote_addr, tokens=token,
                                       user_data=userdata, time=None, cookie_name=cookiename,
                                       secure=True)
        val = ticket.cookie_value()
        # set it in the cookies
        response.set_cookie(
                     cookiename,
                     value=val,
                     max_age=None,
                     path='/',
                     domain=None,
                     secure=False,
                     httponly=False,
                     comment=None,
                     expires=None,
                     overwrite=False)
        transaction.commit()
        raise redirect(came_from)
示例#55
0
    def auth(self, came_from='/', **kw):
        '''
        Fetch user back from tequila.
        Validate the key from tequila.
        Log user.
        '''
        if not 'key' in kw:
            raise redirect(came_from)

        # take parameters
        key = kw.get('key')
        environ = request.environ
        authentication_plugins = environ['repoze.who.plugins']
        identifier = authentication_plugins['ticket']
        secret = identifier.secret
        cookiename = identifier.cookie_name
        remote_addr = environ['REMOTE_ADDR']
        # get user
        principal = tequila.validate_key(key, 'tequila.epfl.ch')
        if principal is None:
            raise redirect('./login')
        tmp_user = self.build_user(principal)
        mail = tmp_user.email
        # log or create him
        user = DBSession.query(User).filter(
            User.email == tmp_user.email).first()
        if user is None:
            user_group = DBSession.query(Group).filter(
                Group.id == constants.group_users_id).first()
            user_group.users.append(tmp_user)
            DBSession.add(tmp_user)
            DBSession.flush()
            #transaction.commit()
            user = DBSession.query(User).filter(User.email == mail).first()
            flash('Your account has been created')
            DBSession.flush()
            self.build_circles_with_user(tmp_user, principal)
            DBSession.flush()
            #transaction.commit()
        elif user.name == constants.tmp_user_name:
            user.name = tmp_user.name
            user.firstname = tmp_user.firstname
            user._set_date(datetime.datetime.now())
            #user_group = DBSession.query(Group).filter(Group.id == constants.group_users_id).first()
            #user_group.users.append(tmp_user)
            flash('Your account has been created')
            DBSession.flush()
            self.build_circles_with_user(tmp_user, principal, user)
            DBSession.flush()
            #transaction.commit()
        else:
            flash('Welcome back', 'notice')
            self.check_circles_with_user(user, principal)

        # look if an user is admin or not
        admins = tg.config.get('admin.mails')
        group_admins = DBSession.query(Group).filter(
            Group.id == constants.group_admins_id).first()
        if user.email in admins:
            user not in group_admins.users and group_admins.users.append(user)
        else:
            user in group_admins.users and group_admins.users.remove(user)
        DBSession.flush()
        # create the authentication ticket
        user = DBSession.query(User).filter(User.email == mail).first()

        userdata = "%s|%s" % (user.id, user in group_admins.users)

        ticket = auth_tkt.AuthTicket(secret,
                                     user.email,
                                     remote_addr,
                                     tokens=token,
                                     user_data=userdata,
                                     time=None,
                                     cookie_name=cookiename,
                                     secure=True)
        val = ticket.cookie_value()
        # set it in the cookies
        response.set_cookie(cookiename,
                            value=val,
                            max_age=None,
                            path='/',
                            domain=None,
                            secure=False,
                            httponly=False,
                            comment=None,
                            expires=None,
                            overwrite=False)
        transaction.commit()
        raise redirect(came_from)