Example #1
0
def login(environ, start_response):
    request = Request(environ)
    message = ''
    if 'form.submitted' in request.POST:
        came_from = request.POST['came_from']
        login_name = request.POST['login_name']
        password = request.POST['password']
        remote_addr = environ['REMOTE_ADDR']
        if _validate(login_name, password):
            headers = [('Location', came_from)]
            ticket = auth_tkt.AuthTicket(SECRET,
                                         login_name,
                                         remote_addr,
                                         cookie_name=COOKIE_NAME,
                                         secure=True,
                                         digest_algo="sha512")
            headers = _get_cookies(environ, ticket.cookie_value())
            headers.append(('Location', came_from))
            start_response('302 Found', headers)
            return []
        message = 'Authentication failed'
    else:
        came_from = request.GET.get('came_from', '')
        login_name = ''

    body = LOGIN_FORM_TEMPLATE % {
        'message': message,
        'came_from': came_from,
        'login_name': login_name,
    }
    start_response('200 OK', [])
    return [body]
Example #2
0
    def remember(self, environ, identity):
        '''
        Remember the user.
        '''
        if self.include_ip:
            remote_addr = environ['REMOTE_ADDR']
        else:
            remote_addr = '0.0.0.0'

        cookies = get_cookies(environ)
        #old_cookie = cookies.get(self.cookie_name)
        existing = cookies.get(self.cookie_name)
        old_cookie_value = getattr(existing, 'value', None)
        max_age = identity.get('max_age', None)

        timestamp, userid, tokens, userdata = None, '', '', ''

        if old_cookie_value:
            try:
                timestamp, userid, tokens, userdata = auth_tkt.parse_ticket(
                    self.secret, old_cookie_value, remote_addr)
            except auth_tkt.BadTicket:
                pass

        who_userid = identity['repoze.who.userid']
        who_tokens = identity.get('tokens', '')
        who_userdata = identity.get('userdata', '')

        encoding_data = self.userid_type_encoders.get(type(who_userid))
        if encoding_data:
            encoding, encoder = encoding_data
            who_userid = encoder(who_userid)
            who_userdata = 'userid_type:%s' % encoding

        if not isinstance(tokens, basestring):
            tokens = ','.join(tokens)
        if not isinstance(who_tokens, basestring):
            who_tokens = ','.join(who_tokens)
        old_data = (userid, tokens, userdata)
        new_data = (who_userid, who_tokens, who_userdata)

        if old_data != new_data or (self.reissue_time and (
            (timestamp + self.reissue_time) < time.time())):
            ticket = auth_tkt.AuthTicket(self.secret,
                                         who_userid,
                                         remote_addr,
                                         tokens=who_tokens,
                                         user_data=who_userdata,
                                         cookie_name=self.cookie_name,
                                         secure=self.secure)
            new_cookie_value = ticket.cookie_value()

            #cur_domain = environ.get('HTTP_HOST', environ.get('SERVER_NAME'))
            #wild_domain = '.' + cur_domain
            if old_cookie_value != new_cookie_value:
                # return a set of Set-Cookie headers
                return self._get_cookies(environ, new_cookie_value, max_age)
Example #3
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)
 def _makeTicket(self,
                 userid='userid',
                 remote_addr='0.0.0.0',
                 tokens=[],
                 userdata='userdata',
                 cookie_name='auth_tkt',
                 secure=False,
                 time=None):
     from paste.auth import auth_tkt
     ticket = auth_tkt.AuthTicket('secret',
                                  userid,
                                  remote_addr,
                                  tokens=tokens,
                                  user_data=userdata,
                                  time=time,
                                  cookie_name=cookie_name,
                                  secure=secure)
     return ticket.cookie_value()
Example #5
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)
Example #6
0
 def get_user_cookie(self, user):
     """store a user in a cookie"""
     _id = user['_id']
     ticket = auth_tkt.AuthTicket(self.settings.shared_secret, _id, "127.0.0.1")
     return ticket.cookie_value()
Example #7
0
    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'))