示例#1
0
    def save_result(self, event_id, testcase_id, username, hwname, smolt, result, bugs, comment):
        """Saves the validated data to ResultsDB."""

        if hwname is not None:
            hwname = hwname.encode('ascii', 'xmlcharrefreplace')
        if result is not None:
            result = result.encode('ascii', 'xmlcharrefreplace')
        filled = self.__update_profile_cookies(username, smolt, hwname)
        # This cookie is used for showing the "DONE" status message in the testcase
        # grid on the Event page
        if testcase_id not in filled:
            filled[testcase_id] = result
        response.set_cookie("filled", json.dumps(filled))


        q = DBSession.query(db.Testcase)
        q = q.filter(db.Testcase.id == testcase_id)
        tc = q.one()

        # Prepares the data for ResultsDB storage
        q = DBSession.query(db.Event)
        q = q.filter(db.Event.id == event_id)
        event = q.one()

        job_id = event.resultsdb_job

        # normalize the empty smolt url to empty string

        if smolt is None or smolt.strip() == "":
            smolt = ""

        # Preparing the data for ResultsDB

        # Set "extra data" (from the ResultsDB's POW)
        # The result is stored here, so we can easily work with the result, without needing
        # to distinguish between the "tc" and "txt" type in the results view.
        keyval_pairs = dict(username=username, hwname=hwname, smolt=smolt, result=result, tctype = tc.type.name)

        # Some ResultsDB fields, reasonably used, so we don't need to create that much extra-data fields
        if comment is not None:
            summary = comment.encode('ascii', 'xmlcharrefreplace')
        else:
            summary = comment
        highlights = bugs

        # For the txt testcase, we set the ResultsDB result to PASSED
        # tc type testcase already has a subset of ResultsDB valid results.
        if tc.type.name == 'txt':
            result = "PASSED"

        # Store the data into ResultsDB
        tr_id = self.rdb.start_testrun(tc.url, job_id)
        retval = self.rdb.end_testrun(tr_id, result, tc.url, keyval_pairs, summary = summary, highlights = highlights)
        if retval == 0:
            flash("Result for '%s' sucessfully saved" % tc.name)
        else:
            flash("Result for '%s' could not be saved (ResultsDB error)" % tc.name, 'error')

        #FIXME: change model, so the event-category is one-to-many instead of many-to-many
        redirect(url('show_event', dict(event_id = event.id)))
示例#2
0
 def forget(controller_result, raised=None):
     """
     Check if the form's inputs can be forgotten, and set the cookie to forget if so.
     :param res: the result of the controller action
     :param raised: any error (redirect or exception) raised by the controller action
     """
     if _ok_to_forget(response, controller_result, raised):
         response.set_cookie('memorable_forget', request.path)
示例#3
0
 def forget(controller_result, raised=None):
     """
     Check if the form's inputs can be forgotten, and set the cookie to forget if so.
     :param res: the result of the controller action
     :param raised: any error (redirect or exception) raised by the controller action
     """
     if _ok_to_forget(response, controller_result, raised):
         response.set_cookie('memorable_forget', request.path)
示例#4
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)
示例#5
0
    def __call__(self, message, status=None,
        overwrite=False,
        **extra_payload):

        if response is None:
            raise ValueError("Must provide a response object or "
                "configure a callable that provides one")

        payload = []

        if not overwrite and request:
            try:
                # Get payload, if already set before
                payload = request.environ['webflash.payload']
                payload = json.loads(url_unquote(payload))
                log.debug("Got payload from environ %d", id(request.environ))
                if isinstance(payload, dict):
                    log.debug('Upgrading old-style payload...')
                    payload = [payload]
            except:
                # No previous payload set before
                pass

        payload.append(
            dict(
                # Force the message to be unicode so lazystrings, etc... are coerced
                message=unicode_text(message),
                status=status or self.default_status,
                **extra_payload
            ))

        payload = url_quote(json.dumps(payload))

        if request:
            # Save the payload in environ too in case JavaScript is not being
            # used and the message is being displayed in the same request.
            request.environ['webflash.payload'] = payload
            log.debug("Setting payload in environ %d", id(request.environ))
        log.debug("Setting payload in cookie")
        response.set_cookie(self.cookie_name, payload)

        if len(response.headers['Set-Cookie']) > 4096:
            raise ValueError('Flash value is too long (cookie would be >4k)')
示例#6
0
 def __update_profile_cookies(self, username, smolt, hwname):
     # Stores the last values of username/smolt/hwname from cookies
     username_orig = request.cookies.get('username', None)
     smolt_orig = request.cookies.get('smolt', None)
     hwname_orig = request.cookies.get('hwname', None)
     filled = json.loads(request.cookies.get('filled', "{}"))
     # Sets new cookie values for username and smolt
     response.set_cookie("username", username)
     response.set_cookie("smolt", smolt)
     response.set_cookie("hwname", hwname)
     if username_orig != username or smolt_orig != smolt or hwname_orig != hwname:
         filled = {}
         response.set_cookie("filled", json.dumps(filled))
     return filled
示例#7
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)
示例#8
0
文件: util.py 项目: leondomingo/Sapns
def save_language(lang):
    _language = config.get('app.language_cookie', 'sp_language')
    response.set_cookie(_language, value=lang, max_age=60*60*24*30*365) # 1 year
示例#9
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)
示例#10
0
 def set_language(self, languageid, came_from=url('/')):
     """Set language cookie"""
     language = DBSession.query(Language).get(languageid.decode())
     response.set_cookie('lang', language.id)
     flash('%s %s' % (_('Preferred language set to:'), language.name))
     redirect(came_from)
示例#11
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)
示例#12
0
def save_language(lang):
    _language = config.get('app.language_cookie', 'sp_language')
    response.set_cookie(_language, value=lang,
                        max_age=60 * 60 * 24 * 30 * 365)  # 1 year
示例#13
0
文件: login.py 项目: bbcf/biorepo
    def auth(self, came_from='/', **kw):
        '''
        Fetch user back from tequila.
        Validate the key from tequila.
        Log user.
        '''
        if not kw.has_key('key'):
            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')

        #in case of user gets several labs
        try:
            if session["first_passage"] == False:
                #second passage
                tmp_user = session["tmp_user"]
                tmp_lab = session['tmp_lab']
        except:
            #first passage
            session["first_passage"] = True
            session["principal_tequila"] = principal
            session.save()
            tmp_user, tmp_lab = self.build_user(principal)
        try:
            mail = tmp_user.email
        except:
            flash("Sorry, you've been disconnected. You can try to relog yourself now", 'error')
            raise redirect('/login/out')
        # 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.name == gl.group_users).first()
            user_group.users.append(tmp_user)
            DBSession.add(tmp_user)
            DBSession.flush()

            user = DBSession.query(User).filter(User.email == mail).first()
            flash(u'Your account has been created  %s' % (user.firstname + ' ' + user.name, ))
            DBSession.flush()
            print "######################"
            print "key user :"******"######################"
            print "key user :"******"######################"
            print "key user :"******"lab created : ", lab
        else:
            if lab not in user.labs:
                lab.users.append(user)
                DBSession.flush()

            print "lab existing : ", lab

        #create attributs / check existing attributs
        attributs = DBSession.query(Attributs).filter(Attributs.lab_id == lab.id).all()
        if len(attributs) == 0:
            attributs = None
        lab_id = lab.id
        #parsing "unit".ini
        config = ConfigParser.RawConfigParser()
        config.read(path_conf_unit(lab.name))
        list_sample_att = (config.get('samples_attributs:main', 'keys')).split(',')
        list_sample_hiding = (config.get('samples_hiding:main', 'keys')).split(',')
        if len(list_sample_hiding) == 1 and list_sample_hiding[0] == '':
            list_sample_hiding = ''
        list_measurement_att = (config.get('meas_attributs:main', 'keys')).split(',')
        list_meas_hiding = (config.get('meas_hiding:main', 'keys')).split(',')
        if len(list_meas_hiding) == 1 and list_meas_hiding[0] == '':
            list_meas_hiding = ''
        list_searchable = (config.get('searchable_attributs:main', 'keys')).split(',')
        list_deprecated = (config.get('deprecated_attributs:main', 'keys')).split(',')
        dict_att_values_sample = {}
        dict_att_values_meas = {}
        dict_widgets_sample_att = {}
        dict_widgets_meas_att = {}
        dict_hiding_s_att = {}
        dict_hiding_m_att = {}
        for x in list_sample_att:
            dict_att_values_sample[x] = (config.get('samples_attributs:' + x, x)).split(',')
            dict_widgets_sample_att[x] = (config.get('samples_attributs:' + x, 'widget')).split(',')
        for x in list_measurement_att:
            dict_att_values_meas[x] = (config.get('meas_attributs:' + x, x)).split(',')
            dict_widgets_meas_att[x] = (config.get('meas_attributs:' + x, 'widget')).split(',')

        #to build the search page
        search_fields_to_display = (config.get('search_grid_fields:main', 'keys')).split(',')
        session["search_grid_fields"] = search_fields_to_display

        #hidingradiobutton lists
        #samples
        if isinstance(list_sample_hiding, list):
            for x in list_sample_hiding:
                dic_mapping = {}
                list_possibilities = (config.get('samples_attributs:' + x, x)).split(',')
                for p in list_possibilities:
                    attribs_by_poss = (config.get('samples_attributs:' + x, p + "_mapping")).split(',')
                    dic_mapping[p] = attribs_by_poss
                dict_hiding_s_att[x] = dic_mapping
        if len(dict_hiding_s_att.keys()) > 0:
            session["hiding_sample"] = dict_hiding_s_att
        else:
            session["hiding_sample"] = {}
        #measurements
        if isinstance(list_meas_hiding, list):
            for x in list_meas_hiding:
                dic_mapping = {}
                list_possibilities = (config.get('meas_attributs:' + x, x)).split(',')
                for p in list_possibilities:
                    attribs_by_poss = (config.get('meas_attributs:' + x, p + "_mapping")).split(',')
                    dic_mapping[p] = attribs_by_poss
                dict_hiding_m_att[x] = dic_mapping
        if len(dict_hiding_m_att.keys()) > 0:
            session["hiding_meas"] = dict_hiding_m_att
        else:
            session["hiding_meas"] = {}
        session.save()

        #creating fixed values list
        list_fixed_values_samples = []
        list_fixed_values_meas = []
        fixed_value_case = ['singleselectfield', 'multiselectfield', 'hiding_singleselectfield', 'hiding_multiselectfield']

        for fix_s in list_sample_att:
            for i in dict_att_values_sample[fix_s]:
                if i != "None":
                    if fix_s not in list_fixed_values_samples:
                        list_fixed_values_samples.append(fix_s)
        for fix_m in list_measurement_att:
            for i in dict_att_values_meas[fix_m]:
                if i != "None":
                    if fix_m not in list_fixed_values_meas:
                        list_fixed_values_meas.append(fix_m)
        print list_fixed_values_samples, "<--- fixed sample"
        print list_fixed_values_meas, "<---- fixed meas"
        if attributs is None:
            #########################################
            ###### creating samples attributs #######
            #########################################
            for s in list_sample_att:
                #TODO virer cast str
                widget = str(dict_widgets_sample_att[s])
                owner_widget = "sample"
                attribut = self.build_attribut(s, lab_id, list_fixed_values_samples, list_searchable, list_deprecated, widget, owner_widget)
                DBSession.add(attribut)
                DBSession.flush()
                if attribut.fixed_value == False:
                    #if Attribut do not get fixed values
                    att_value = self.build_None_attribut_value(attribut.id)
                    DBSession.add(att_value)
                    DBSession.flush()

            #########################################
            #### creating measurements attributs ####
            #########################################
            for m in list_measurement_att:
                widget = str(dict_widgets_meas_att[m])
                owner_widget = "measurement"
                attribut = self.build_attribut(m, lab_id, list_fixed_values_meas, list_searchable, list_deprecated, widget, owner_widget)
                DBSession.add(attribut)
                DBSession.flush()
                if attribut.fixed_value == False:
                    #if Attribut do not get fixed values
                    att_value = self.build_None_attribut_value(attribut.id)
                    DBSession.add(att_value)
                    DBSession.flush()

            #########################################
            ####### creating attributs values #######
            #########################################
            #######         for samples       #######
            #########################################
            dict_fixed_values_samples = {}
            list_attributs_samples_values = self.build_attribut_value('samples_attributs:', lab_id, dict_fixed_values_samples, list_fixed_values_samples, config)
            for att_v in list_attributs_samples_values:
                DBSession.add(att_v)
            DBSession.flush()
            #########################################
            ######       for measurements     #######
            #########################################
            dict_fixed_values_meas = {}
            list_attributs_meas_values = self.build_attribut_value('meas_attributs:', lab_id, dict_fixed_values_meas, list_fixed_values_meas, config)
            for att_v in list_attributs_meas_values:
                DBSession.add(att_v)
            DBSession.flush()

        #check if there is a new key (or several...) in the config file of the lab
        else:
            list_existant_keys = []
            print list_searchable, "-------------searchable"
            for k in attributs:
                list_existant_keys.append(str(k.key))
            for att_s in list_sample_att:
                att_s = unicode(att_s)
                if att_s not in list_existant_keys:
                    #########################################
                    ###### creating samples attributs #######
                    #########################################
                    widget = str(dict_widgets_sample_att[att_s])
                    owner_widget = "sample"
                    new_sample_attribut = self.build_attribut(att_s, lab_id, list_fixed_values_samples, list_searchable, list_deprecated, widget, owner_widget)
                    print new_sample_attribut
                    DBSession.add(new_sample_attribut)
                    DBSession.flush()
                    if new_sample_attribut.fixed_value == False:
                        #if Attribut do not get fixed values
                        att_value = self.build_None_attribut_value(new_sample_attribut.id)
                        DBSession.add(att_value)
                        DBSession.flush()
                    #########################################
                    ####### creating attributs values #######
                    #########################################
                    #######         for samples       #######
                    #########################################
                    dict_fixed_values_samples = {}
                    list_attributs_samples_values = self.build_attribut_value('samples_attributs:', lab_id, dict_fixed_values_samples, list_fixed_values_samples, config)
                    for att_v in list_attributs_samples_values:
                        DBSession.add(att_v)
                    DBSession.flush()
                #check widgets type
                att_2_check = DBSession.query(Attributs).filter(and_(Attributs.lab_id == lab_id, Attributs.key == att_s, Attributs.owner == "sample")).first()
                wid_sample_tmp = dict_widgets_sample_att[att_s]

                for w_s in wid_sample_tmp:
                    if w_s != att_2_check.widget:
                        in_db_before = att_2_check.widget
                        in_db_now = w_s
                        att_2_check.widget = w_s
                        if in_db_before in fixed_value_case and in_db_now not in fixed_value_case:
                            att_2_check.fixed_value = False
                        elif in_db_before not in fixed_value_case and in_db_now in fixed_value_case:
                            att_2_check.fixed_value = True
                        DBSession.flush()
                #check and update search buttons
                if att_2_check is None:
                    print att_s, "not in db"
                if att_2_check is not None and not att_2_check.searchable and att_2_check.key in list_searchable:
                    att_2_check.searchable = True
                    DBSession.flush()
                elif att_2_check is not None and att_2_check.searchable and att_2_check.key not in list_searchable:
                    att_2_check.searchable = False
                    DBSession.flush()

            for att_m in list_measurement_att:
                att_m = unicode(att_m)
                if att_m not in list_existant_keys:
                    #########################################
                    #### creating measurements attributs ####
                    #########################################
                    #TODO virer cast str
                    widget = str(dict_widgets_meas_att[att_m])
                    owner_widget = "measurement"
                    new_meas_attribut = self.build_attribut(att_m, lab_id, list_fixed_values_meas, list_searchable, list_deprecated, widget, owner_widget)
                    DBSession.add(new_meas_attribut)
                    DBSession.flush()
                    if new_meas_attribut.fixed_value == False:
                        #if Attribut do not get fixed values
                        att_value = self.build_None_attribut_value(new_meas_attribut.id)
                        DBSession.add(att_value)
                        DBSession.flush()
                    #########################################
                    ####### creating attributs values #######
                    #########################################
                    ######       for measurements     #######
                    #########################################
                    dict_fixed_values_meas = {}
                    list_attributs_meas_values = self.build_attribut_value('meas_attributs:', lab_id, dict_fixed_values_meas, list_fixed_values_meas, config)
                    for att_v in list_attributs_meas_values:
                        DBSession.add(att_v)
                    DBSession.flush()
                #check the widgets
                att_2_check = DBSession.query(Attributs).filter(and_(Attributs.lab_id == lab_id, Attributs.key == att_m, Attributs.owner == "measurement")).first()
                wid_meas_tmp = dict_widgets_meas_att[att_m]
                for w_m in wid_meas_tmp:
                    if w_m != att_2_check.widget:
                        in_db_before = att_2_check.widget
                        in_db_now = w_m
                        att_2_check.widget = w_m
                        if in_db_before in fixed_value_case and in_db_now not in fixed_value_case:
                            att_2_check.fixed_value = False
                        elif in_db_before not in fixed_value_case and in_db_now in fixed_value_case:
                            att_2_check.fixed_value = True
                        DBSession.flush()
                #check and update search buttons
                if att_2_check is None:
                    print att_m, "not in db"
                if att_2_check is not None and not att_2_check.searchable and att_2_check.key in list_searchable:
                    att_2_check.searchable = True
                    DBSession.flush()
                elif att_2_check is not None and att_2_check.searchable and att_2_check.key not in list_searchable:
                    att_2_check.searchable = False
                    DBSession.flush()

            #if lab choose to delete an attributs (or undelete a key...)
            #Attributs obj have to stay into the db but user can not add others Attributs() with this key --> deprecated == True
            not_deprecated_in_db = DBSession.query(Attributs).filter(and_(Attributs.lab_id == lab_id, Attributs.deprecated == False)).all()
            for k in not_deprecated_in_db:
                if k.key in list_deprecated:
                    k.deprecated = True
                    DBSession.add(k)
                    DBSession.flush()

            deprecated_in_db = DBSession.query(Attributs).filter(and_(Attributs.lab_id == lab_id, Attributs.deprecated == True)).all()
            for k in deprecated_in_db:
                if k.key not in list_deprecated:
                    k.deprecated = False
                    DBSession.add(k)
                    DBSession.flush()

            #test if deleted attributs_values
            #build a dictionnary to fast check what is into db
            dict_att_values_db = {}
            for a in attributs:
                #dict_att_values_db[a.key] = empty_list
                list_tmp = []
                for v in a.values:
                    if v.deprecated == False:
                        try:
                            list_tmp.append(str(v.value))
                        except:
                            list_tmp.append(v.value)
                if len(list_tmp) == 0:
                    list_tmp = [None]
                dict_att_values_db[str(a.key)] = list_tmp

            #You have to check deletion BEFORE addition
            #checking attribut value(s) deletion(s) in samples attributs
            self.check_value_deletion(list_sample_att, dict_att_values_sample, dict_att_values_db, lab_id)
            #checking attribut value(s) deletion(s) in measurements attributs
            self.check_value_deletion(list_measurement_att, dict_att_values_meas, dict_att_values_db, lab_id)
            #checking attribut value(s) addition in sample attributs
            self.check_value_addition(list_sample_att, dict_att_values_sample, dict_att_values_db, lab_id)
            #checking attribut value(s) addition in measurements attributs
            self.check_value_addition(list_measurement_att, dict_att_values_meas, dict_att_values_db, lab_id)

        # look if an user is admin or not
        admins = tg.config.get('admin.mails')
        group_admins = DBSession.query(Group).filter(Group.name == gl.group_admins).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 = str(user.id)
        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()
        extern_meas = session.get("extern_meas", False)
        check_tequila = session.get("check_tequila", False)
        if extern_meas is False and check_tequila is False:
            raise redirect(came_from)
        elif extern_meas is False and check_tequila:
            raise redirect("/search")
        else:
            del session["extern_meas"]
            raise redirect(url('/measurements/external_add'))
示例#14
0
文件: login.py 项目: bbcf/biorepo
    def auth(self, came_from='/', **kw):
        '''
        Fetch user back from tequila.
        Validate the key from tequila.
        Log user.
        '''
        if not kw.has_key('key'):
            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')

        #in case of user gets several labs
        try:
            if session["first_passage"] == False:
                #second passage
                tmp_user = session["tmp_user"]
                tmp_lab = session['tmp_lab']
        except:
            #first passage
            session["first_passage"] = True
            session["principal_tequila"] = principal
            session.save()
            tmp_user, tmp_lab = self.build_user(principal)
        try:
            mail = tmp_user.email
        except:
            flash(
                "Sorry, you've been disconnected. You can try to relog yourself now",
                'error')
            raise redirect('/login/out')
        # 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.name == gl.group_users).first()
            user_group.users.append(tmp_user)
            DBSession.add(tmp_user)
            DBSession.flush()

            user = DBSession.query(User).filter(User.email == mail).first()
            flash(u'Your account has been created  %s' %
                  (user.firstname + ' ' + user.name, ))
            DBSession.flush()
            print "######################"
            print "key user :"******"######################"
            print "key user :"******"######################"
            print "key user :"******"lab created : ", lab
        else:
            if lab not in user.labs:
                lab.users.append(user)
                DBSession.flush()

            print "lab existing : ", lab

        #create attributs / check existing attributs
        attributs = DBSession.query(Attributs).filter(
            Attributs.lab_id == lab.id).all()
        if len(attributs) == 0:
            attributs = None
        lab_id = lab.id
        #parsing "unit".ini
        config = ConfigParser.RawConfigParser()
        config.read(path_conf_unit(lab.name))
        list_sample_att = (config.get('samples_attributs:main',
                                      'keys')).split(',')
        list_sample_hiding = (config.get('samples_hiding:main',
                                         'keys')).split(',')
        if len(list_sample_hiding) == 1 and list_sample_hiding[0] == '':
            list_sample_hiding = ''
        list_measurement_att = (config.get('meas_attributs:main',
                                           'keys')).split(',')
        list_meas_hiding = (config.get('meas_hiding:main', 'keys')).split(',')
        if len(list_meas_hiding) == 1 and list_meas_hiding[0] == '':
            list_meas_hiding = ''
        list_searchable = (config.get('searchable_attributs:main',
                                      'keys')).split(',')
        list_deprecated = (config.get('deprecated_attributs:main',
                                      'keys')).split(',')
        dict_att_values_sample = {}
        dict_att_values_meas = {}
        dict_widgets_sample_att = {}
        dict_widgets_meas_att = {}
        dict_hiding_s_att = {}
        dict_hiding_m_att = {}
        for x in list_sample_att:
            dict_att_values_sample[x] = (config.get('samples_attributs:' + x,
                                                    x)).split(',')
            dict_widgets_sample_att[x] = (config.get('samples_attributs:' + x,
                                                     'widget')).split(',')
        for x in list_measurement_att:
            dict_att_values_meas[x] = (config.get('meas_attributs:' + x,
                                                  x)).split(',')
            dict_widgets_meas_att[x] = (config.get('meas_attributs:' + x,
                                                   'widget')).split(',')

        #to build the search page
        search_fields_to_display = (config.get('search_grid_fields:main',
                                               'keys')).split(',')
        session["search_grid_fields"] = search_fields_to_display

        #hidingradiobutton lists
        #samples
        if isinstance(list_sample_hiding, list):
            for x in list_sample_hiding:
                dic_mapping = {}
                list_possibilities = (config.get('samples_attributs:' + x,
                                                 x)).split(',')
                for p in list_possibilities:
                    attribs_by_poss = (config.get('samples_attributs:' + x,
                                                  p + "_mapping")).split(',')
                    dic_mapping[p] = attribs_by_poss
                dict_hiding_s_att[x] = dic_mapping
        if len(dict_hiding_s_att.keys()) > 0:
            session["hiding_sample"] = dict_hiding_s_att
        else:
            session["hiding_sample"] = {}
        #measurements
        if isinstance(list_meas_hiding, list):
            for x in list_meas_hiding:
                dic_mapping = {}
                list_possibilities = (config.get('meas_attributs:' + x,
                                                 x)).split(',')
                for p in list_possibilities:
                    attribs_by_poss = (config.get('meas_attributs:' + x,
                                                  p + "_mapping")).split(',')
                    dic_mapping[p] = attribs_by_poss
                dict_hiding_m_att[x] = dic_mapping
        if len(dict_hiding_m_att.keys()) > 0:
            session["hiding_meas"] = dict_hiding_m_att
        else:
            session["hiding_meas"] = {}
        session.save()

        #creating fixed values list
        list_fixed_values_samples = []
        list_fixed_values_meas = []
        fixed_value_case = [
            'singleselectfield', 'multiselectfield',
            'hiding_singleselectfield', 'hiding_multiselectfield'
        ]

        for fix_s in list_sample_att:
            for i in dict_att_values_sample[fix_s]:
                if i != "None":
                    if fix_s not in list_fixed_values_samples:
                        list_fixed_values_samples.append(fix_s)
        for fix_m in list_measurement_att:
            for i in dict_att_values_meas[fix_m]:
                if i != "None":
                    if fix_m not in list_fixed_values_meas:
                        list_fixed_values_meas.append(fix_m)
        print list_fixed_values_samples, "<--- fixed sample"
        print list_fixed_values_meas, "<---- fixed meas"
        if attributs is None:
            #########################################
            ###### creating samples attributs #######
            #########################################
            for s in list_sample_att:
                #TODO virer cast str
                widget = str(dict_widgets_sample_att[s])
                owner_widget = "sample"
                attribut = self.build_attribut(s, lab_id,
                                               list_fixed_values_samples,
                                               list_searchable,
                                               list_deprecated, widget,
                                               owner_widget)
                DBSession.add(attribut)
                DBSession.flush()
                if attribut.fixed_value == False:
                    #if Attribut do not get fixed values
                    att_value = self.build_None_attribut_value(attribut.id)
                    DBSession.add(att_value)
                    DBSession.flush()

            #########################################
            #### creating measurements attributs ####
            #########################################
            for m in list_measurement_att:
                widget = str(dict_widgets_meas_att[m])
                owner_widget = "measurement"
                attribut = self.build_attribut(m, lab_id,
                                               list_fixed_values_meas,
                                               list_searchable,
                                               list_deprecated, widget,
                                               owner_widget)
                DBSession.add(attribut)
                DBSession.flush()
                if attribut.fixed_value == False:
                    #if Attribut do not get fixed values
                    att_value = self.build_None_attribut_value(attribut.id)
                    DBSession.add(att_value)
                    DBSession.flush()

            #########################################
            ####### creating attributs values #######
            #########################################
            #######         for samples       #######
            #########################################
            dict_fixed_values_samples = {}
            list_attributs_samples_values = self.build_attribut_value(
                'samples_attributs:', lab_id, dict_fixed_values_samples,
                list_fixed_values_samples, config)
            for att_v in list_attributs_samples_values:
                DBSession.add(att_v)
            DBSession.flush()
            #########################################
            ######       for measurements     #######
            #########################################
            dict_fixed_values_meas = {}
            list_attributs_meas_values = self.build_attribut_value(
                'meas_attributs:', lab_id, dict_fixed_values_meas,
                list_fixed_values_meas, config)
            for att_v in list_attributs_meas_values:
                DBSession.add(att_v)
            DBSession.flush()

        #check if there is a new key (or several...) in the config file of the lab
        else:
            list_existant_keys = []
            print list_searchable, "-------------searchable"
            for k in attributs:
                list_existant_keys.append(str(k.key))
            for att_s in list_sample_att:
                att_s = unicode(att_s)
                if att_s not in list_existant_keys:
                    #########################################
                    ###### creating samples attributs #######
                    #########################################
                    widget = str(dict_widgets_sample_att[att_s])
                    owner_widget = "sample"
                    new_sample_attribut = self.build_attribut(
                        att_s, lab_id, list_fixed_values_samples,
                        list_searchable, list_deprecated, widget, owner_widget)
                    print new_sample_attribut
                    DBSession.add(new_sample_attribut)
                    DBSession.flush()
                    if new_sample_attribut.fixed_value == False:
                        #if Attribut do not get fixed values
                        att_value = self.build_None_attribut_value(
                            new_sample_attribut.id)
                        DBSession.add(att_value)
                        DBSession.flush()
                    #########################################
                    ####### creating attributs values #######
                    #########################################
                    #######         for samples       #######
                    #########################################
                    dict_fixed_values_samples = {}
                    list_attributs_samples_values = self.build_attribut_value(
                        'samples_attributs:', lab_id,
                        dict_fixed_values_samples, list_fixed_values_samples,
                        config)
                    for att_v in list_attributs_samples_values:
                        DBSession.add(att_v)
                    DBSession.flush()
                #check widgets type
                att_2_check = DBSession.query(Attributs).filter(
                    and_(Attributs.lab_id == lab_id, Attributs.key == att_s,
                         Attributs.owner == "sample")).first()
                wid_sample_tmp = dict_widgets_sample_att[att_s]

                for w_s in wid_sample_tmp:
                    if w_s != att_2_check.widget:
                        in_db_before = att_2_check.widget
                        in_db_now = w_s
                        att_2_check.widget = w_s
                        if in_db_before in fixed_value_case and in_db_now not in fixed_value_case:
                            att_2_check.fixed_value = False
                        elif in_db_before not in fixed_value_case and in_db_now in fixed_value_case:
                            att_2_check.fixed_value = True
                        DBSession.flush()
                #check and update search buttons
                if att_2_check is None:
                    print att_s, "not in db"
                if att_2_check is not None and not att_2_check.searchable and att_2_check.key in list_searchable:
                    att_2_check.searchable = True
                    DBSession.flush()
                elif att_2_check is not None and att_2_check.searchable and att_2_check.key not in list_searchable:
                    att_2_check.searchable = False
                    DBSession.flush()

            for att_m in list_measurement_att:
                att_m = unicode(att_m)
                if att_m not in list_existant_keys:
                    #########################################
                    #### creating measurements attributs ####
                    #########################################
                    #TODO virer cast str
                    widget = str(dict_widgets_meas_att[att_m])
                    owner_widget = "measurement"
                    new_meas_attribut = self.build_attribut(
                        att_m, lab_id, list_fixed_values_meas, list_searchable,
                        list_deprecated, widget, owner_widget)
                    DBSession.add(new_meas_attribut)
                    DBSession.flush()
                    if new_meas_attribut.fixed_value == False:
                        #if Attribut do not get fixed values
                        att_value = self.build_None_attribut_value(
                            new_meas_attribut.id)
                        DBSession.add(att_value)
                        DBSession.flush()
                    #########################################
                    ####### creating attributs values #######
                    #########################################
                    ######       for measurements     #######
                    #########################################
                    dict_fixed_values_meas = {}
                    list_attributs_meas_values = self.build_attribut_value(
                        'meas_attributs:', lab_id, dict_fixed_values_meas,
                        list_fixed_values_meas, config)
                    for att_v in list_attributs_meas_values:
                        DBSession.add(att_v)
                    DBSession.flush()
                #check the widgets
                att_2_check = DBSession.query(Attributs).filter(
                    and_(Attributs.lab_id == lab_id, Attributs.key == att_m,
                         Attributs.owner == "measurement")).first()
                wid_meas_tmp = dict_widgets_meas_att[att_m]
                for w_m in wid_meas_tmp:
                    if w_m != att_2_check.widget:
                        in_db_before = att_2_check.widget
                        in_db_now = w_m
                        att_2_check.widget = w_m
                        if in_db_before in fixed_value_case and in_db_now not in fixed_value_case:
                            att_2_check.fixed_value = False
                        elif in_db_before not in fixed_value_case and in_db_now in fixed_value_case:
                            att_2_check.fixed_value = True
                        DBSession.flush()
                #check and update search buttons
                if att_2_check is None:
                    print att_m, "not in db"
                if att_2_check is not None and not att_2_check.searchable and att_2_check.key in list_searchable:
                    att_2_check.searchable = True
                    DBSession.flush()
                elif att_2_check is not None and att_2_check.searchable and att_2_check.key not in list_searchable:
                    att_2_check.searchable = False
                    DBSession.flush()

            #if lab choose to delete an attributs (or undelete a key...)
            #Attributs obj have to stay into the db but user can not add others Attributs() with this key --> deprecated == True
            not_deprecated_in_db = DBSession.query(Attributs).filter(
                and_(Attributs.lab_id == lab_id,
                     Attributs.deprecated == False)).all()
            for k in not_deprecated_in_db:
                if k.key in list_deprecated:
                    k.deprecated = True
                    DBSession.add(k)
                    DBSession.flush()

            deprecated_in_db = DBSession.query(Attributs).filter(
                and_(Attributs.lab_id == lab_id,
                     Attributs.deprecated == True)).all()
            for k in deprecated_in_db:
                if k.key not in list_deprecated:
                    k.deprecated = False
                    DBSession.add(k)
                    DBSession.flush()

            #test if deleted attributs_values
            #build a dictionnary to fast check what is into db
            dict_att_values_db = {}
            for a in attributs:
                #dict_att_values_db[a.key] = empty_list
                list_tmp = []
                for v in a.values:
                    if v.deprecated == False:
                        try:
                            list_tmp.append(str(v.value))
                        except:
                            list_tmp.append(v.value)
                if len(list_tmp) == 0:
                    list_tmp = [None]
                dict_att_values_db[str(a.key)] = list_tmp

            #You have to check deletion BEFORE addition
            #checking attribut value(s) deletion(s) in samples attributs
            self.check_value_deletion(list_sample_att, dict_att_values_sample,
                                      dict_att_values_db, lab_id)
            #checking attribut value(s) deletion(s) in measurements attributs
            self.check_value_deletion(list_measurement_att,
                                      dict_att_values_meas, dict_att_values_db,
                                      lab_id)
            #checking attribut value(s) addition in sample attributs
            self.check_value_addition(list_sample_att, dict_att_values_sample,
                                      dict_att_values_db, lab_id)
            #checking attribut value(s) addition in measurements attributs
            self.check_value_addition(list_measurement_att,
                                      dict_att_values_meas, dict_att_values_db,
                                      lab_id)

        # look if an user is admin or not
        admins = tg.config.get('admin.mails')
        group_admins = DBSession.query(Group).filter(
            Group.name == gl.group_admins).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 = str(user.id)
        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()
        extern_meas = session.get("extern_meas", False)
        check_tequila = session.get("check_tequila", False)
        if extern_meas is False and check_tequila is False:
            raise redirect(came_from)
        elif extern_meas is False and check_tequila:
            raise redirect("/search")
        else:
            del session["extern_meas"]
            raise redirect(url('/measurements/external_add'))