Esempio n. 1
0
    def renderPage(self):
        access_token = self.request.get('token', None)
        if access_token:
            session = sessionmanager.getsession(
                self,
                access_token=access_token,
                redirect_uri=fbutils.base_url(self) + 'opensesame/access')
        else:
            session = sessionmanager.getsession(self)

        if session:
            testid = self.request.get('testid')
            q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)

            tests = q.fetch(1)
            if len(tests) <= 0:
                self.response.out.write('Wrong test id')
                return

            q = db.GqlQuery("SELECT * FROM TestResults WHERE testid = :1",
                            testid)
            results = q.fetch(1)
            if len(results) > 0: result = results[0]
            else: result = obj_testresults.TestResults(testid=testid)

            self.response.out.write('OK ' + result.stroutput())
        else:
            self.response.out.write('Wrong session')
    def renderPage(self):
        access_token = self.request.get('token', None)
        if access_token:
            session = sessionmanager.getsession(
                self,
                access_token=access_token,
                redirect_uri=fbutils.base_url(self) + 'opensesame/access')
        else:
            session = sessionmanager.getsession(self)

        if session:
            testid = self.request.get('testid')
            q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)

            tests = q.fetch(1)
            if len(tests) > 0:
                test = tests[0]

            self.response.headers['Content-Type'] = "application/x-gzip"
            self.response.headers[
                'Content-Disposition'] = "attachment; filename=" + str(
                    test.testfilename)
            self.response.out.write(test.testfile)
        else:
            self.response.out.write('Wrong session')
    def postPage(self, uid):
        code = self.request.get('code', None)
        frienduid = self.request.get('frienduid', None)
        
        session = sessionmanager.getsession(self)
        try:
            if session['me']['id'] != uid: code = None
        except: code = None
            
        action = self.request.get('action', None)
        if code != None and action == 'getFriendValues':
            objreturn = {}
            q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", frienduid)
            #q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
            networks  = q.fetch(1)

            if not len(networks) == 0:
                network = networks[0]
                league = network.getleague()
                
                objreturn['nodes'] = len(network.getnodes())
                objreturn['edges'] = len(network.getedges())
                objreturn['friendleagueids'] = league and [row[0] for row in league] or None
                objreturn['friendleaguenames'] = league and [row[1] for row in league] or None
            else:
                objreturn['nodes'] = None
                objreturn['edges'] = None
                objreturn['friendleagueids'] = None
                objreturn['friendleaguenames'] = None
            
            self.response.out.write(json.dumps(objreturn))
Esempio n. 4
0
    def renderPage(self, extension):
        uid = self.request.get('uid', None)
        network = None

        strpage = "Error."
        supported_extensions = ['gdf', 'graphml']
        if not uid == None and extension in supported_extensions:
            session = sessionmanager.getsession(self)
            if session and session['me']['id'] == uid:
                q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
                networks = q.fetch(1)

                if not len(networks) == 0:
                    network = networks[0]
                    graph = loadGraph(network.getnodes(), network.getedges())

                    strpage = ''
                    if extension == 'gdf':
                        for line in nx.generate_gdf(graph):
                            strpage += line + '\n'
                        self.response.headers['Content-Type'] = "text/gdf"

                    if extension == 'graphml':
                        for line in nx.generate_graphml(graph):
                            strpage += line + '\n'
                        self.response.headers['Content-Type'] = "xml/graphml"

        self.response.out.write(strpage)
 def renderPage(self):
     access_token = self.request.get('token', None)
     session = sessionmanager.getsession(self, access_token=access_token, redirect_uri=fbutils.base_url(self)+'opensesame/access')
     
     objreturn = {}
     objreturn['result'] = False
     objreturn['message'] = 'Wrong session'
     
     if session:
         roles = session['roles']
         if not 'administrator' in roles:
             objreturn['message'] = 'Wrong role, you are not administrator'
         else:
             objreturn['tests'] = []
             q = db.GqlQuery("SELECT * FROM Test")
             for test in q:
                 if test != None and test.startdate != None and test.enddate != None:
                     curTest = {}
                     curTest['testid'] = test.testid
                     curTest['name'] = test.name
                     curTest['description'] = test.description
                     curTest['startdate'] = test.startdate.strftime("%d/%m/%Y")
                     curTest['enddate'] = test.enddate.strftime("%d/%m/%Y")
                     curTest['withindates'] = test.startdate <= date.today() and test.enddate >= date.today()
                     curTest['active'] = test.active
                     
                     objreturn['tests'].append(curTest)
             
             objreturn['indexes'] = conf.INDEXES
             objreturn['result'] = True
             objreturn['message'] = ''
     
     self.response.out.write(json.dumps(objreturn))
Esempio n. 6
0
    def get(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session['roles']
            if not 'administrator' in roles:
                self.response.out.write(
                    "You are not an administrator for this site. Access denied."
                )
                return

            code = self.request.get('code', None)
            testid = self.request.get('testid', None)

            q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
            test = q.fetch(1)

            if len(test) > 0: test = test[0]
            else: test = None

            if test:
                if test.owner != session['me']['id']:
                    self.response.out.write(
                        "You are not the test owner of this test. Access denied."
                    )
                    return

                test.delete()
                logging.info("Deleted the psychological test: " + testid)

            self.redirect('/admin?code=' + code)
Esempio n. 7
0
    def post(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session['roles']
            if not 'administrator' in roles:
                self.response.out.write(
                    "You are not an administrator for this site. Access denied."
                )
                return

            code = self.request.get('code', None)
            testid = self.request.get('testid', None)

            testname = self.request.get('testname', None)
            description = self.request.get('testdescription', None)
            startdate = self.request.get('teststartdate', None)
            enddate = self.request.get('testenddate', None)
            try:
                testfilename = self.request.POST['testfile'].filename
                testfile = self.request.get('testfile', None)
            except:
                testfilename = None
                testfile = None

            if testid == None:
                testid = str(
                    datetime.datetime.now()) + " " + session['me']['id']
                test = obj_test.Test(testid=testid, name=testname)
            else:
                q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
                test = q.fetch(1)

                if len(test) == 0:
                    testid = str(
                        datetime.datetime.now()) + " " + session['me']['id']
                    test = obj_test.Test(testid=testid, name=testname)
                else:
                    test = test[0]
                    if test.owner != session['me']['id']:
                        self.response.out.write(
                            "You are not the test owner of this test. Access denied."
                        )
                        return

            test.owner = session['me']['id']
            test.description = description
            day, month, year = startdate.split("/")
            test.startdate = datetime.date(int(year), int(month), int(day))
            day, month, year = enddate.split("/")
            test.enddate = datetime.date(int(year), int(month), int(day))
            test.active = False
            if testfile != None:
                test.testfilename = testfilename
                test.testfile = db.Blob(testfile)
            test.put()

            logging.info("Uploaded a new psychological test: " + testid)
            #self.redirect('/admin/edittest?testid=' + testid + '&code=' + code)
            self.redirect('/admin?code=' + code)
    def get(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session["roles"]
            if not "administrator" in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return

            code = self.request.get("code", None)
            testid = self.request.get("testid", None)
            active = self.request.get("active", False) == "true"

            q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
            test = q.fetch(1)

            if len(test) > 0:
                test = test[0]
            else:
                test = None

            if test:
                test.active = active
                test.put()
                if active:
                    logging.info("Activated the psychological test: " + testid)
                else:
                    logging.info("Deactivated the psychological test: " + testid)

            self.redirect("/admin?code=" + code)
Esempio n. 9
0
    def renderPage(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session["roles"]
            if not "technician" in roles:
                self.response.out.write("You are not a technician for this site. Access denied.")
                return

            template_values = {
                "appId": conf.FBAPI_APP_ID,
                "token": session["access_token"],
                "app": session["appid"],
                "conf": conf,
                "me": session["me"],
                "roles": roles,
                "isdesktop": session["isdesktop"],
                "header": "",
                "code": self.request.get("code", None),
            }

            root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
            self.response.out.write(template.render(os.path.join(root, "templates/_header.html"), template_values))
            self.response.out.write(template.render(os.path.join(root, "admin/templates/tech.html"), template_values))
            self.response.out.write(template.render(os.path.join(root, "templates/_footer.html"), template_values))
        else:
            self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
    def get(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session["roles"]
            if not "administrator" in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return

            code = self.request.get("code", None)
            testid = self.request.get("testid", None)

            q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
            test = q.fetch(1)

            if len(test) > 0:
                test = test[0]
            else:
                test = None

            if test:
                if test.owner != session["me"]["id"]:
                    self.response.out.write("You are not the test owner of this test. Access denied.")
                    return

                test.delete()
                logging.info("Deleted the psychological test: " + testid)

            self.redirect("/admin?code=" + code)
def parsePost(self):
    session = sessionmanager.getsession(self)

    if session:
        roles = session['roles']

        if not 'administrator' in roles:
            self.response.out.write(
                "You are not an administrator for this site. Access denied.")
            return

        action = self.request.get('action', None)
        uid = self.request.get('uid', None)

        if action == "selectUid":
            objreturn = {}
            objreturn['indexes'] = []

            q = db.GqlQuery("SELECT * FROM Index WHERE uid = :1", uid)
            for index in q:
                if not index.name in objreturn['indexes']:
                    objreturn['indexes'].append(index.name)

            self.response.out.write(json.dumps(objreturn))

        elif action == "computeIndex":
            indexname = self.request.get('indexname', None)
            libSNA = computeprofileindex.getLibSNA(self, session)
            objreturn = computeprofileindex.computeIndex(
                self, libSNA, indexname, False, session)

            renderPage(self, 'admin')
        else:
            renderPage(self, 'admin')
def renderPage(self, mode='admin'):
    session = sessionmanager.getsession(self)
    
    if session:
        roles = session['roles']
    
        if mode == 'admin' and not 'administrator' in roles:
            self.response.out.write("You are not an administrator for this site. Access denied.")
            return
        elif not 'technician' in roles:
            self.response.out.write("You are not a technician for this site. Access denied.")
            return
        
        code = self.request.get('code', None)
        uid = self.request.get('uid', None)
        
        users = None
        network = None
        
        if uid == None:
            upload_url = '/' + mode + '/viewnetwork?code=' + code
            users = []
            q = db.GqlQuery("SELECT * FROM User")
            for user in q: users.append(user)
        else:
            if mode == 'tech': upload_url = '/tech/savenetwork?uid=' + uid + '&code=' + code
            else: upload_url = '/admin?code=' + code
            
            if uid == "_new_":
                network = None
            else:
                q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
                network = q.fetch(1)
    
                if len(network) == 0: network = None
                else: network = network[0]
            
        
        template_values = {
            'appId': conf.FBAPI_APP_ID,
            'token': session['access_token'], 
            'app': session['appid'],
            'conf': conf,
            'me': session['me'],
            'roles': roles,
            'upload_url': upload_url,
            'mode': mode,
            'uid': uid,
            'users': users,
            'network': network,
            'isdesktop': session['isdesktop'],
            'header': '',
            'code': code }
    
        root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
        self.response.out.write(template.render(os.path.join(root, 'admin/templates/vieweditnetwork.html'), template_values))
        self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
    else:
        self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
Esempio n. 13
0
    def get(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session['roles']
            if not 'administrator' in roles:
                self.response.out.write(
                    "You are not an administrator for this site. Access denied."
                )
                return

            code = self.request.get('code', None)
            testid = self.request.get('testid', None)
            active = self.request.get('active', False) == "true"

            q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
            test = q.fetch(1)

            if len(test) > 0: test = test[0]
            else: test = None

            if test:
                test.active = active
                test.put()
                if (active):
                    logging.info("Activated the psychological test: " + testid)
                else:
                    logging.info("Deactivated the psychological test: " +
                                 testid)

            self.redirect('/admin?code=' + code)
def parsePost(self):
    session = sessionmanager.getsession(self)

    if session:
        roles = session["roles"]

        if not "administrator" in roles:
            self.response.out.write("You are not an administrator for this site. Access denied.")
            return

        action = self.request.get("action", None)
        uid = self.request.get("uid", None)

        if action == "selectUid":
            objreturn = {}
            objreturn["indexes"] = []

            q = db.GqlQuery("SELECT * FROM Index WHERE uid = :1", uid)
            for index in q:
                if not index.name in objreturn["indexes"]:
                    objreturn["indexes"].append(index.name)

            self.response.out.write(json.dumps(objreturn))

        elif action == "computeIndex":
            indexname = self.request.get("indexname", None)
            libSNA = computeprofileindex.getLibSNA(self, session)
            objreturn = computeprofileindex.computeIndex(self, libSNA, indexname, False, session)

            renderPage(self, "admin")
        else:
            renderPage(self, "admin")
    def renderPage(self, extension):
        uid = self.request.get("uid", None)
        network = None

        strpage = "Error."
        supported_extensions = ["gdf", "graphml"]
        if not uid == None and extension in supported_extensions:
            session = sessionmanager.getsession(self)
            if session and session["me"]["id"] == uid:
                q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
                networks = q.fetch(1)

                if not len(networks) == 0:
                    network = networks[0]
                    graph = loadGraph(network.getnodes(), network.getedges())

                    strpage = ""
                    if extension == "gdf":
                        for line in nx.generate_gdf(graph):
                            strpage += line + "\n"
                        self.response.headers["Content-Type"] = "text/gdf"

                    if extension == "graphml":
                        for line in nx.generate_graphml(graph):
                            strpage += line + "\n"
                        self.response.headers["Content-Type"] = "xml/graphml"

        self.response.out.write(strpage)
    def renderPage(self):
        cookie = SimpleCookie(os.environ['HTTP_COOKIE'])
        printout = ''
        self.cookie_keys = cookie.keys()
        if not self.cookie_keys:
            self.response.out.write('No session yet')
            return
        self.cookie_keys.sort()
        data = ''.join(cookie[k].value for k in self.cookie_keys)
        printout += data + '\n\n\n'

        i = gaesessions.SIG_LEN + gaesessions.SID_LEN
        sig, b64pdump = data[:gaesessions.SIG_LEN], data[i:]
        printout += 'sig = ' + sig + '\n'
        b64pdump += "=" * ((4 - len(b64pdump) % 4) % 4)
        printout += 'len = ' + str(len(b64pdump)) + '\n'
        printout += 'padding = ' + str(((4 - len(b64pdump) % 4) % 4)) + '\n\n'

        try:
            pdump = b64decode(b64pdump)

            if pdump:
                printout += printdict(decode_data(pdump))
            else:
                printout += 'data is in memcache/db: load it on-demand'
        except:
            lens = len(b64pdump)
            lenx = lens - (lens % 4 if lens % 4 else 4)
            try:
                printout += b64decode(b64pdump[:lenx])
            except:
                printout += str(sys.exc_info())

        session = sessionmanager.getsession(self)

        template_values = {
            'appId': conf.FBAPI_APP_ID,
            'token': session['access_token'],
            'app': session['appid'],
            'conf': conf,
            'me': session['me'],
            'cookie': printout,
            'isdesktop': session and session['isdesktop'] or False,
            'header': '',
            'code': self.request.get('code', None)
        }

        root = os.path.normpath(
            os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_header.html'),
                            template_values))
        self.response.out.write(
            template.render(
                os.path.join(root, 'admin/templates/dumpcookie.html'),
                template_values))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_footer.html'),
                            template_values))
Esempio n. 17
0
def parsePost(self):
    session = sessionmanager.getsession(self)

    if session:
        roles = session['roles']

        if not 'administrator' in roles:
            self.response.out.write(
                "You are not an administrator for this site. Access denied.")
            return

        action = self.request.get('action', None)
        uid = self.request.get('uid', None)

        if action == "getNodes":
            objreturn = {}
            nodes, edges, networkhash = getNodesEdges(self, uid, session)

            q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
            network = q.fetch(1)

            if len(network) == 0: network = obj_network.Network(uid=uid)
            else: network = network[0]

            network.updated_time = datetime.datetime.now()
            network.setnodes(str(nodes))
            network.setedges(str(edges))
            network.networkhash = networkhash
            network.put()

            objreturn['nodes'] = str(nodes)
            objreturn['edges'] = str(edges)
            objreturn['networkhash'] = networkhash

            self.response.out.write(json.dumps(objreturn))
        elif action == "computeLeague":
            objreturn = {}
            nodes = eval(self.request.get('nodes', None))
            edges = eval(self.request.get('edges', None))

            libSNA = libsna.SocialNetwork()
            libSNA.loadGraph(nodes=nodes, edges=edges)

            table = computeLeague(libSNA, uid, session)

            q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
            network = q.fetch(1)

            if len(network) == 0: network = obj_network.Network(uid=uid)
            else: network = network[0]

            network.updated_time = datetime.datetime.now()
            network.setleague(str(table))
            network.put()

            objreturn["league"] = str(table)
            self.response.out.write(json.dumps(objreturn))
        else:
            renderPage(self, 'admin')
    def renderPage(self, uid, indexname):
        code = self.request.get('code', None)
        index = None
        
        value = None
        nodevalues = None
        edgevalues = None
        nodegaussian = None
        edgegaussian = None
        
        session = sessionmanager.getsession(self)
        try:
            if session['me']['id'] != uid: code = None
        except: code = None
                        
        q = db.GqlQuery("SELECT * FROM Index " +
                        "WHERE uid = :1 AND name = :2 " +
                        "ORDER BY updated_time DESC",
                        uid,
                        indexname)
        indexes = q.fetch(1)

        if not len(indexes) == 0:
            index = indexes[0]
            
            value = index.value
            nodevalues = self.setcentiles(index.get_nodevalues())
            edgevalues = self.setcentiles(index.get_edgevalues())
            nodegaussian = self.getgaussian(nodevalues)
            edgegaussian = self.getgaussian(edgevalues)
            
        if session == None:
            app_friends = None
        else:
            app_friends = fbutils.fql("SELECT uid, name, is_app_user " +
                                      "FROM user " +
                                      "WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1 " +
                                      "ORDER BY name", session['access_token'])
        
        template_values = {
            'conf': conf,
            'indexname': indexname,
            'description': conf.INDEXES[indexname],
            'uid': uid,
            'index': index,
            'nodevalues': nodevalues,
            'edgevalues': edgevalues,
            'nodegaussian': nodegaussian,
            'edgegaussian': edgegaussian,
            'value': value,
            'friends': app_friends,
            'isdesktop': session and session['isdesktop'] or False,
            'header': 'sociologicalindex',
            'code': code }
        
        root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
        self.response.out.write(template.render(os.path.join(root, 'pages/templates/sociologicalindex.html'), template_values))
        self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
def parsePost(self):
    session = sessionmanager.getsession(self)
    
    if session:
        roles = session['roles']
        
        if not 'administrator' in roles:
            self.response.out.write("You are not an administrator for this site. Access denied.")
            return
    
        action = self.request.get('action', None)
        uid = self.request.get('uid', None)
        
        if action == "getNodes":
            objreturn = {}
            nodes, edges, networkhash = getNodesEdges(self, uid, session)
            
            q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
            network = q.fetch(1)

            if len(network) == 0: network = obj_network.Network(uid = uid)
            else: network = network[0]
            
            network.updated_time = datetime.datetime.now()
            network.setnodes(str(nodes))
            network.setedges(str(edges))
            network.networkhash = networkhash
            network.put()
            
            objreturn['nodes'] = str(nodes)
            objreturn['edges'] = str(edges)
            objreturn['networkhash'] = networkhash
            
            self.response.out.write(json.dumps(objreturn))
        elif action == "computeLeague":
            objreturn = {}
            nodes = eval(self.request.get('nodes', None))
            edges = eval(self.request.get('edges', None))
            
            libSNA = libsna.SocialNetwork() 
            libSNA.loadGraph(nodes=nodes, edges=edges)

            table = computeLeague(libSNA, uid, session)
            
            q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
            network = q.fetch(1)

            if len(network) == 0: network = obj_network.Network(uid = uid)
            else: network = network[0]
            
            network.updated_time = datetime.datetime.now()
            network.setleague(str(table))
            network.put()
            
            objreturn["league"] = str(table)               
            self.response.out.write(json.dumps(objreturn))
        else:
            renderPage(self, 'admin')
Esempio n. 20
0
    def renderPage(self, uid):
        code = self.request.get('code', None)
        
        session = sessionmanager.getsession(self)
        try:
            if session['me']['id'] != uid: code = None
        except: code = None
        
        nodes = None
        edges = None
        league = None
        hiddenleague = False
        
        q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
        networks = q.fetch(1)

        if not len(networks) == 0:
            network = networks[0]
            
            nodes = network.getnodes()
            edges = network.getedges()
            league = network.getleague()
            
            try:
                if not fbutils.is_friend(session['access_token'], session['me']['id'], uid): 
                    for row in league:
                        row[1] = re.sub("\w", "x", row[1]).title()
                    hiddenleague = True
            except:
                for row in league:
                    row[1] = re.sub("\w", "x", row[1]).title()
                hiddenleague = True
        
        if session == None:
            app_friends = None
        else:
            app_friends = fbutils.fql("SELECT uid, name, is_app_user " +
                                      "FROM user " +
                                      "WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1 " +
                                      "ORDER BY name", session['access_token'])
        
        template_values = {
            'conf': conf,
            'uid': uid,
            'me': session['me'],
            'nodes': nodes,
            'edges': edges,
            'league': league,
            'hiddenleague': hiddenleague,
            'friends': app_friends,
            'isdesktop': session and session['isdesktop'] or False,
            'header': 'network',
            'code': code }

        root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
        self.response.out.write(template.render(os.path.join(root, 'pages/templates/network.html'), template_values))
        self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
Esempio n. 21
0
    def post(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session['roles']

            if not 'technician' in roles:
                self.response.out.write(
                    "You are not a technician for this site. Access denied.")
                return

            action = self.request.get('action', None)
            code = self.request.get('code', None)
            uid = self.request.get('uid', None)

            if action == "getNodes":
                objreturn = {}
                nodes, edges, networkhash = getNodesEdges(self, uid, session)

                objreturn['nodes'] = str(nodes)
                objreturn['edges'] = str(edges)
                objreturn['networkhash'] = networkhash

                self.response.out.write(json.dumps(objreturn))
            elif action == "computeLeague":
                objreturn = {}
                nodes = eval(self.request.get('nodes', None))
                edges = eval(self.request.get('edges', None))

                libSNA = libsna.SocialNetwork()
                libSNA.loadGraph(nodes=nodes, edges=edges)

                table = computeLeague(libSNA, uid, session)
                objreturn["league"] = str(table)
                self.response.out.write(json.dumps(objreturn))
            elif action == "saveNetwork":
                networkhash = self.request.get('networkhash', None)
                nodes = self.request.get('nodes', None)
                edges = self.request.get('edges', None)
                league = self.request.get('league', None)

                q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
                network = q.fetch(1)

                if len(network) == 0: network = obj_network.Network(uid=uid)
                else: network = network[0]

                network.updated_time = datetime.datetime.now()
                network.networkhash = networkhash
                network.setnodes(nodes)
                network.setedges(edges)
                network.setleague(league)
                network.put()

                logging.info("Updatet network data for user: " + uid)
                self.redirect('/tech/viewnetwork?uid=' + uid + '&code=' + code)
            else:
                self.redirect('/tech/viewnetwork?uid=' + uid + '&code=' + code)
    def post(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session["roles"]

            if not "technician" in roles:
                self.response.out.write("You are not a technician for this site. Access denied.")
                return

            action = self.request.get("action", None)
            code = self.request.get("code", None)
            uid = self.request.get("uid", None)

            if action == "selectUid":
                objreturn = {}
                objreturn["indexes"] = []

                q = db.GqlQuery("SELECT * FROM Index WHERE uid = :1", uid)
                for index in q:
                    if not index.name in objreturn["indexes"]:
                        objreturn["indexes"].append(index.name)

                self.response.out.write(json.dumps(objreturn))
            elif action == "computeIndex":
                indexname = self.request.get("indexname", None)
                libSNA = computeprofileindex.getLibSNA(self, session)
                objreturn = computeprofileindex.computeIndex(
                    self, libSNA, indexname, False, session, saveInDatastore=False
                )

                if "nodes" in objreturn:
                    objreturn["nodes"] = str(objreturn["nodes"])
                if "edges" in objreturn:
                    objreturn["edges"] = str(objreturn["edges"])
                self.response.out.write(json.dumps(objreturn))
            elif action == "saveIndex":
                indexname = self.request.get("indexname", None)
                networkhash = self.request.get("networkhash", None)
                value = self.request.get("value", None)
                edges = self.request.get("edges", None)
                nodes = self.request.get("nodes", None)

                index = obj_index.Index(uid=self.request.get("uid", None), name=indexname)
                index.updated_time = datetime.datetime.now()
                index.networkhash = networkhash

                index.value = float(value)
                if not edges == None:
                    index.set_edgevalues(edges)
                if not nodes == None:
                    index.set_nodevalues(nodes)
                index.put()

                logging.info("Updated index data for user: "******"/tech/viewindex?uid=" + uid + "&code=" + code)
            else:
                self.redirect("/tech/viewindex?uid=" + uid + "&code=" + code)
    def post(self):
        session = sessionmanager.getsession(self)
        
        if session:
            roles = session['roles']
            
            if not 'technician' in roles:
                self.response.out.write("You are not a technician for this site. Access denied.")
                return
        
            action = self.request.get('action', None)
            code = self.request.get('code', None)
            uid = self.request.get('uid', None)
            
            if action == "getNodes":
                objreturn = {}
                nodes, edges, networkhash = getNodesEdges(self, uid, session)
                
                objreturn['nodes'] = str(nodes)
                objreturn['edges'] = str(edges)
                objreturn['networkhash'] = networkhash
                
                self.response.out.write(json.dumps(objreturn))
            elif action == "computeLeague":
                objreturn = {}
                nodes = eval(self.request.get('nodes', None))
                edges = eval(self.request.get('edges', None))
                
                libSNA = libsna.SocialNetwork() 
                libSNA.loadGraph(nodes=nodes, edges=edges)
    
                table = computeLeague(libSNA, uid, session)
                objreturn["league"] = str(table)               
                self.response.out.write(json.dumps(objreturn))
            elif action == "saveNetwork":
                networkhash = self.request.get('networkhash', None)
                nodes = self.request.get('nodes', None)
                edges = self.request.get('edges', None)
                league = self.request.get('league', None)
                
                q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
                network = q.fetch(1)
    
                if len(network) == 0: network = obj_network.Network(uid = uid)
                else: network = network[0]

                network.updated_time = datetime.datetime.now()
                network.networkhash = networkhash
                network.setnodes(nodes)
                network.setedges(edges)
                network.setleague(league)
                network.put()
    
                logging.info("Updatet network data for user: " + uid)
                self.redirect('/tech/viewnetwork?uid=' + uid + '&code=' + code)
            else:
                self.redirect('/tech/viewnetwork?uid=' + uid + '&code=' + code)
Esempio n. 24
0
 def renderPage(self):
     access_token = self.request.get('token', None)
     if access_token: session = sessionmanager.getsession(self, access_token=access_token, redirect_uri=fbutils.base_url(self)+'opensesame/access')
     else: session = sessionmanager.getsession(self)
         
     if session:
         testid = self.request.get('testid')
         q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
         
         tests = q.fetch(1)
         if len(tests) > 0:
             test = tests[0]
         
         self.response.headers['Content-Type'] = "application/x-gzip"
         self.response.headers['Content-Disposition'] = "attachment; filename=" + str(test.testfilename)
         self.response.out.write(test.testfile)
     else:
         self.response.out.write('Wrong session')
Esempio n. 25
0
    def renderPage(self):
        session = sessionmanager.getsession(self, redirect_uri=fbutils.base_url(self) + "opensesame/access")

        if session:
            SERVER_ADDRESS = ("127.0.0.1", 33333)

            template_values = {
                "appId": conf.FBAPI_APP_ID,
                "token": session["access_token"],
                "app": session["appid"],
                "conf": conf,
                "me": session["me"],
                "roles": session["roles"],
                "isdesktop": session["isdesktop"],
                "header": "",
            }

            root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
            self.response.out.write(template.render(os.path.join(root, "templates/_header.html"), template_values))

            self.response.out.write('<header class="clearfix">')
            self.response.out.write(
                '<p id="picture" style="background-image: url(/static/images/macchie.jpg); background-size: 64px 64px"></p>'
            )
            self.response.out.write("<h1>Rorschach Test Platform authentication</h1>")
            self.response.out.write("</header>")

            self.response.out.write('<section id="normalsection" class="clearfix">')
            self.response.out.write("<h3>Associate OpenSesame with Rorschach Test Platform</h3>")
            self.response.out.write(
                "<p>In order to use the OpenSesame plugin, you need to authenticate with Facebook and give grants to the Rorschach Test Platform application.</p>"
            )
            self.response.out.write(
                "<p>By clicking the button below you will create a temporary access token to be used by the OpenSesame plugin.<br/>"
            )
            self.response.out.write(
                "The access token created with this procedure will have a lifetime of two hours (as by Facebook standards) and so after two hours it will be automatically declared invalid.</p>"
            )
            self.response.out.write(
                '<form action="http://%s:%s/" method="post" name="codeSubmit" id="codeSubmit">' % SERVER_ADDRESS
            )
            self.response.out.write(
                '<input type="hidden" id="code" name="code" value="' + self.request.get("code", None) + '" />'
            )
            self.response.out.write(
                '<input type="hidden" id="access_token" name="access_token" value="' + session["access_token"] + '" />'
            )
            self.response.out.write(
                '<p class="button"><a href="#" class="facebook-button" onclick="$(\'#codeSubmit\').submit();">'
            )
            self.response.out.write('<span class="plus">Save the access token</span></a></p>')
            self.response.out.write("</section>")

            self.response.out.write(template.render(os.path.join(root, "templates/_footer.html"), template_values))
        else:
            self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self) + "opensesame/access"))
Esempio n. 26
0
    def renderPage(self):
        session = sessionmanager.getsession(self)

        if session:
            indexes = {}
            q = db.GqlQuery(
                "SELECT * FROM Index " + "WHERE uid = :1 " +
                "ORDER BY updated_time DESC", session['me']['id'])
            for index in q:
                if not index.networkhash == None and \
                   not index.value == None:
                    indexes[index.name] = (
                        conf.INDEX_TYPES[index.name]) % index.value

            computed_groups = {}
            for group in conf.INDEX_GROUPS:
                comp = 0
                for index in group['indexes']:
                    if index in indexes:
                        comp += 1
                computed_groups[group['name']] = comp

            template_values = {
                'appId': conf.FBAPI_APP_ID,
                'token': session['access_token'],
                'app': session['appid'],
                'conf': conf,
                'me': session['me'],
                'roles': session['roles'],
                'computedindexes': indexes,
                'numindexes': len(conf.INDEXES),
                'index_groups': conf.INDEX_GROUPS,
                'computed_groups': computed_groups,
                'index_names': conf.INDEXES,
                'isdesktop': session['isdesktop'],
                'header': '',
                'code': self.request.get('code', None)
            }

            root = os.path.normpath(
                os.path.join(os.path.dirname(__file__), os.path.pardir))
            self.response.out.write(
                template.render(os.path.join(root, 'templates/_header.html'),
                                template_values))
            self.response.out.write(
                template.render(
                    os.path.join(root, 'pages/templates/profile.html'),
                    template_values))
            self.response.out.write(
                template.render(os.path.join(root, 'templates/_footer.html'),
                                template_values))
        else:
            self.redirect(
                fbutils.oauth_login_url(self=self,
                                        next_url=fbutils.base_url(self)))
Esempio n. 27
0
 def renderPage(self):
     session = sessionmanager.getsession(self)
     msgtype = self.request.get('msgtype', None)
     
     
     if msgtype == 'index':
         indexname = self.request.get('indexname', None)
         value = self.request.get('value', None)
         
         if indexname == None or value == None:
             self.response.out.write("Error, wrong parameters.")
             logging.error("Unable to post to suer wall: wrong parameters.")
             return
         
         result = fbutils.fb_call("me/feed",
                                  {'access_token' : session['access_token'],
                                   'message': 'I have just computed my ' + indexname + ' sociological index, its value is ' + value,
                                   'name': 'Rorschach test platform',
                                   'caption': indexname.title() + ' is a sociological index computed on the information present in FB. ' + conf.INDEXES[indexname] + '.',
                                   'picture': fbutils.base_url(self) + 'smallgraph/' + session['me']['id'] + '/' + indexname,
                                   'link': conf.base_url(self) + 'index/' + session['me']['id'] + '/' + indexname},
                                  method='POST')
         
         if not 'id' in result: logging.error("Unable to post to the user wall: " + str(result))
         
     elif msgtype == 'network':
         nodes = self.request.get('nodes', None)
         edges = self.request.get('edges', None)
         
         league = self.request.get('league', 'None').decode('utf-8')
         league = string.replace(league, '&#39;', '\'')
         league = eval(league)
         
         i = 1
         message  = 'My Facebook network has ' + nodes + ' contacts and ' + edges + ' connections amongst them!\n'
         message += 'In my network the more influential contacts are:\n'
         for curuser in league:
             message += str(i) + '. ' + curuser[1] + '\n'
             i += 1
         
         result = fbutils.fb_call("me/feed",
                                  {'access_token' : session['access_token'],
                                   'message': message,
                                   'name': 'My network elite group',
                                   'caption': 'The elite group has been computed by Rorschach test platform with the information from your network of contatcs. For all your contacts information about their centrality has been computed using SNA. These information are about the role of influence and the number of connection of a friend within your network. Scoring these results, it has been possible to produce the list of the top influencers of your friends.',
                                   'link': conf.base_url(self) + 'network/' + session['me']['id']},
                                  method='POST')
         
         if not 'id' in result: logging.error("Unable to post to the user wall: " + str(result))
         
     else:
         logging.error("Wrong msgtype parameter to postwall: " + str(msgtype))
         
     self.response.out.write(json.dumps(result))
Esempio n. 28
0
def renderPage(self, mode='new'):
    session = sessionmanager.getsession(self)

    if session:
        roles = session['roles']

        if not 'administrator' in roles:
            self.response.out.write(
                "You are not an administrator for this site. Access denied.")
            return

        code = self.request.get('code', None)
        upload_url = '/admin/savetest?code=' + code

        test = None

        if mode == 'edit':
            testid = self.request.get('testid', None)
            q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
            tests = q.fetch(1)

            if len(tests) > 0:
                test = tests[0]

        template_values = {
            'appId': conf.FBAPI_APP_ID,
            'token': session['access_token'],
            'app': session['appid'],
            'conf': conf,
            'me': session['me'],
            'roles': roles,
            'test': test,
            'upload_url': upload_url,
            'isdesktop': session['isdesktop'],
            'header': 'viewcreatetest',
            'code': code
        }

        root = os.path.normpath(
            os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_header.html'),
                            template_values))
        self.response.out.write(
            template.render(
                os.path.join(root, 'admin/templates/viewcreatetest.html'),
                template_values))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_footer.html'),
                            template_values))
    else:
        self.redirect(
            fbutils.oauth_login_url(self=self,
                                    next_url=fbutils.base_url(self)))
    def post(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session["roles"]
            if not "administrator" in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return

            code = self.request.get("code", None)
            testid = self.request.get("testid", None)

            testname = self.request.get("testname", None)
            description = self.request.get("testdescription", None)
            startdate = self.request.get("teststartdate", None)
            enddate = self.request.get("testenddate", None)
            try:
                testfilename = self.request.POST["testfile"].filename
                testfile = self.request.get("testfile", None)
            except:
                testfilename = None
                testfile = None

            if testid == None:
                testid = str(datetime.datetime.now()) + " " + session["me"]["id"]
                test = obj_test.Test(testid=testid, name=testname)
            else:
                q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
                test = q.fetch(1)

                if len(test) == 0:
                    testid = str(datetime.datetime.now()) + " " + session["me"]["id"]
                    test = obj_test.Test(testid=testid, name=testname)
                else:
                    test = test[0]
                    if test.owner != session["me"]["id"]:
                        self.response.out.write("You are not the test owner of this test. Access denied.")
                        return

            test.owner = session["me"]["id"]
            test.description = description
            day, month, year = startdate.split("/")
            test.startdate = datetime.date(int(year), int(month), int(day))
            day, month, year = enddate.split("/")
            test.enddate = datetime.date(int(year), int(month), int(day))
            test.active = False
            if testfile != None:
                test.testfilename = testfilename
                test.testfile = db.Blob(testfile)
            test.put()

            logging.info("Uploaded a new psychological test: " + testid)
            # self.redirect('/admin/edittest?testid=' + testid + '&code=' + code)
            self.redirect("/admin?code=" + code)
Esempio n. 30
0
    def renderPage(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session['roles']
            if not 'administrator' in roles:
                self.response.out.write(
                    "You are not an administrator for this site. Access denied."
                )
                return

            withindates = {}
            tests = []
            q = db.GqlQuery("SELECT * FROM Test")
            for test in q:
                if test != None and test.startdate != None and test.enddate != None:
                    if test.startdate <= date.today(
                    ) and test.enddate >= date.today():
                        withindates[test.name] = True

                tests.append(test)

            template_values = {
                'appId': conf.FBAPI_APP_ID,
                'token': session['access_token'],
                'app': session['appid'],
                'conf': conf,
                'me': session['me'],
                'roles': roles,
                'tests': tests,
                'withindates': withindates,
                'isdesktop': session['isdesktop'],
                'header': '',
                'code': self.request.get('code', None)
            }

            root = os.path.normpath(
                os.path.join(os.path.dirname(__file__), os.path.pardir))
            self.response.out.write(
                template.render(os.path.join(root, 'templates/_header.html'),
                                template_values))
            self.response.out.write(
                template.render(
                    os.path.join(root, 'admin/templates/admin.html'),
                    template_values))
            self.response.out.write(
                template.render(os.path.join(root, 'templates/_footer.html'),
                                template_values))
        else:
            self.redirect(
                fbutils.oauth_login_url(self=self,
                                        next_url=fbutils.base_url(self)))
 def renderPage(self):
     access_token = self.request.get('token', None)
     if access_token: session = sessionmanager.getsession(self, access_token=access_token, redirect_uri=fbutils.base_url(self)+'opensesame/access')
     else: session = sessionmanager.getsession(self)
         
     if session:
         testid = self.request.get('testid')
         q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
         
         tests = q.fetch(1)
         if len(tests) <= 0:
             self.response.out.write('Wrong test id')
             return
         
         q = db.GqlQuery("SELECT * FROM TestResults WHERE testid = :1", testid)
         results = q.fetch(1)
         if len(results) > 0: result = results[0]
         else: result = obj_testresults.TestResults(testid=testid)
         
         self.response.out.write('OK ' + result.stroutput())
     else:
         self.response.out.write('Wrong session')
    def postPage(self, uid, indexname):
        frienduid = self.request.get('frienduid', None)
        
        myvalues = self.request.get('myvalues', None)
        if myvalues != None: myvalues = eval(myvalues)
        myvaluesG = self.request.get('myvaluesG', None)
        if myvaluesG != None: myvaluesG = eval(myvaluesG)
        
        session = sessionmanager.getsession(self)
        try:
            if session['me']['id'] != uid:
                session.terminate()
                session = None
        except:
            session.terminate()
            session = None
            
        action = self.request.get('action', None)
        if session and action == 'getFriendValues':
            objreturn = {}
            q = db.GqlQuery("SELECT * FROM Index " +
                        "WHERE uid = :1 AND name = :2 " +
                        "ORDER BY updated_time DESC",
                        frienduid,
                        indexname)
            indexes = q.fetch(1)

            if not len(indexes) == 0:
                index = indexes[0]
            
                objreturn['value'] = index.value
                newvalues = self.setcentiles(index.get_nodevalues())
                if newvalues != None: objreturn['nodevalues'] = str(self.mergevalues(myvalues, newvalues))
                else: objreturn['nodevalues'] = str(newvalues)
                newgaussian = self.getgaussian(newvalues)
                if newgaussian != None: objreturn['nodegaussian'] = str(self.mergevaluesG(myvaluesG, newgaussian))
                else: objreturn['nodegaussian'] = str(newgaussian)
                
                newvalues = self.setcentiles(index.get_edgevalues())
                if newvalues != None: objreturn['edgevalues'] = str(self.mergevalues(myvalues, newvalues))
                else: objreturn['edgevalues'] = str(newvalues)
                newgaussian = self.getgaussian(newvalues)
                if newgaussian != None: objreturn['edgegaussian'] = str(self.mergevaluesG(myvaluesG, newgaussian))
                else: objreturn['edgegaussian'] = str(newgaussian)
            else:
                objreturn['value'] = None
            
                
            self.response.out.write(json.dumps(objreturn))
        else:
            self.response.out.write("Error, session invalid or invalid action.")
 def renderPage(self):
     cookie = SimpleCookie(os.environ['HTTP_COOKIE'])
     printout = ''
     self.cookie_keys = cookie.keys()
     if not self.cookie_keys:
         self.response.out.write('No session yet')
         return
     self.cookie_keys.sort()
     data = ''.join(cookie[k].value for k in self.cookie_keys)
     printout += data + '\n\n\n'
     
     i = gaesessions.SIG_LEN + gaesessions.SID_LEN
     sig, b64pdump = data[:gaesessions.SIG_LEN], data[i:]
     printout += 'sig = ' + sig + '\n'
     b64pdump += "=" * ((4 - len(b64pdump) % 4) % 4)
     printout += 'len = ' + str(len(b64pdump)) + '\n'
     printout += 'padding = ' + str(((4 - len(b64pdump) % 4) % 4)) + '\n\n'
     
     try:
         pdump = b64decode(b64pdump)
         
         if pdump:
             printout += printdict(decode_data(pdump))
         else:
             printout += 'data is in memcache/db: load it on-demand'
     except:
         lens = len(b64pdump)
         lenx = lens - (lens % 4 if lens % 4 else 4)
         try:
             printout += b64decode(b64pdump[:lenx])
         except:
             printout += str(sys.exc_info())
     
     session = sessionmanager.getsession(self)
     
     template_values = {
             'appId': conf.FBAPI_APP_ID,
             'token': session['access_token'], 
             'app': session['appid'],
             'conf': conf,
             'me': session['me'],
             'cookie': printout,
             'isdesktop': session and session['isdesktop'] or False,
             'header': '',
             'code': self.request.get('code', None) }
     
     root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
     self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
     self.response.out.write(template.render(os.path.join(root, 'admin/templates/dumpcookie.html'), template_values))
     self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
def renderPage(self, mode="new"):
    session = sessionmanager.getsession(self)

    if session:
        roles = session["roles"]

        if not "administrator" in roles:
            self.response.out.write("You are not an administrator for this site. Access denied.")
            return

        code = self.request.get("code", None)
        upload_url = "/admin/savetest?code=" + code

        test = None

        if mode == "edit":
            testid = self.request.get("testid", None)
            q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
            tests = q.fetch(1)

            if len(tests) > 0:
                test = tests[0]

        template_values = {
            "appId": conf.FBAPI_APP_ID,
            "token": session["access_token"],
            "app": session["appid"],
            "conf": conf,
            "me": session["me"],
            "roles": roles,
            "test": test,
            "upload_url": upload_url,
            "isdesktop": session["isdesktop"],
            "header": "viewcreatetest",
            "code": code,
        }

        root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(template.render(os.path.join(root, "templates/_header.html"), template_values))
        self.response.out.write(
            template.render(os.path.join(root, "admin/templates/viewcreatetest.html"), template_values)
        )
        self.response.out.write(template.render(os.path.join(root, "templates/_footer.html"), template_values))
    else:
        self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
Esempio n. 35
0
 def renderPage(self):
     session = sessionmanager.getsession(self)
     
     if session:
         indexes = {}
         q = db.GqlQuery("SELECT * FROM Index " +
                     "WHERE uid = :1 " +
                     "ORDER BY updated_time DESC",
                     session['me']['id'])
         for index in q:            
             if not index.networkhash == None and \
                not index.value == None:
                 indexes[index.name] = (conf.INDEX_TYPES[index.name]) % index.value
                 
         computed_groups = {}
         for group in conf.INDEX_GROUPS:
             comp = 0
             for index in group['indexes']:
                 if index in indexes:
                     comp += 1
             computed_groups[group['name']] = comp
         
         template_values = {
             'appId': conf.FBAPI_APP_ID,
             'token': session['access_token'], 
             'app': session['appid'],
             'conf': conf,
             'me': session['me'],
             'roles': session['roles'],
             'computedindexes': indexes,
             'numindexes': len(conf.INDEXES),
             'index_groups': conf.INDEX_GROUPS,
             'computed_groups': computed_groups, 
             'index_names': conf.INDEXES,
             'isdesktop': session['isdesktop'],
             'header': '',
             'code': self.request.get('code', None) }
         
         root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
         self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
         self.response.out.write(template.render(os.path.join(root, 'pages/templates/profile.html'), template_values))
         self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
     else:
         self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
def renderPage(self):
    session = sessionmanager.getsession(self)
    
    if session:
        roles = session['roles']
    
        if not 'administrator' in roles:
            self.response.out.write("You are not an administrator for this site. Access denied.")
            return
        
        code = self.request.get('code', None)
        upload_url = '/admin/savetest?code=' + code
        
        testid = self.request.get('testid', None)
        q = db.GqlQuery("SELECT * FROM Test WHERE testid = :1", testid)
        tests = q.fetch(1)
        test = (len(tests) > 0) and tests[0] or None
        
        testresults = []
        q = db.GqlQuery("SELECT * FROM TestResults WHERE testid = :1", testid)
        for result in q: testresults.append(result)
        
        template_values = {
            'appId': conf.FBAPI_APP_ID,
            'token': session['access_token'], 
            'app': session['appid'],
            'conf': conf,
            'me': session['me'],
            'roles': roles,
            'test': test,
            'testresults': testresults,
            'upload_url': upload_url,
            'isdesktop': session['isdesktop'],
            'header': '',
            'code': code }
        
        root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
        self.response.out.write(template.render(os.path.join(root, 'admin/templates/viewtestresults.html'), template_values))
        self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
    else:
        self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
Esempio n. 37
0
    def renderPage(self):
        session = sessionmanager.getsession(self)
        
        if session:
            roles = session['roles']
            if not 'administrator' in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return
        
            withindates = {}
            tests = []
            q = db.GqlQuery("SELECT * FROM Test")
            for test in q:
                if test != None and test.startdate != None and test.enddate != None:
                    if test.startdate <= date.today() and test.enddate >= date.today():
                        withindates[test.name] = True

                tests.append(test)
            
            template_values = {
                'appId': conf.FBAPI_APP_ID,
                'token': session['access_token'], 
                'app': session['appid'],
                'conf': conf,
                'me': session['me'],
                'roles': roles,
                'tests': tests,
                'withindates': withindates,
                'isdesktop': session['isdesktop'],
                'header': '',
                'code': self.request.get('code', None) }
            
            root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
            self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
            self.response.out.write(template.render(os.path.join(root, 'admin/templates/admin.html'), template_values))
            self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
        else:
            self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
    def postPage(self, uid):
        code = self.request.get('code', None)
        frienduid = self.request.get('frienduid', None)

        session = sessionmanager.getsession(self)
        try:
            if session['me']['id'] != uid: code = None
        except:
            code = None

        action = self.request.get('action', None)
        if code != None and action == 'getFriendValues':
            objreturn = {}
            q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", frienduid)
            #q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
            networks = q.fetch(1)

            if not len(networks) == 0:
                network = networks[0]
                league = network.getleague()

                objreturn['nodes'] = len(network.getnodes())
                objreturn['edges'] = len(network.getedges())
                objreturn['friendleagueids'] = league and [
                    row[0] for row in league
                ] or None
                objreturn['friendleaguenames'] = league and [
                    row[1] for row in league
                ] or None
            else:
                objreturn['nodes'] = None
                objreturn['edges'] = None
                objreturn['friendleagueids'] = None
                objreturn['friendleaguenames'] = None

            self.response.out.write(json.dumps(objreturn))
Esempio n. 39
0
    def postPage(self, uid, indexname):
        frienduid = self.request.get('frienduid', None)

        myvalues = self.request.get('myvalues', None)
        if myvalues != None: myvalues = eval(myvalues)
        myvaluesG = self.request.get('myvaluesG', None)
        if myvaluesG != None: myvaluesG = eval(myvaluesG)

        session = sessionmanager.getsession(self)
        try:
            if session['me']['id'] != uid:
                session.terminate()
                session = None
        except:
            session.terminate()
            session = None

        action = self.request.get('action', None)
        if session and action == 'getFriendValues':
            objreturn = {}
            q = db.GqlQuery(
                "SELECT * FROM Index " + "WHERE uid = :1 AND name = :2 " +
                "ORDER BY updated_time DESC", frienduid, indexname)
            indexes = q.fetch(1)

            if not len(indexes) == 0:
                index = indexes[0]

                objreturn['value'] = index.value
                newvalues = self.setcentiles(index.get_nodevalues())
                if newvalues != None:
                    objreturn['nodevalues'] = str(
                        self.mergevalues(myvalues, newvalues))
                else:
                    objreturn['nodevalues'] = str(newvalues)
                newgaussian = self.getgaussian(newvalues)
                if newgaussian != None:
                    objreturn['nodegaussian'] = str(
                        self.mergevaluesG(myvaluesG, newgaussian))
                else:
                    objreturn['nodegaussian'] = str(newgaussian)

                newvalues = self.setcentiles(index.get_edgevalues())
                if newvalues != None:
                    objreturn['edgevalues'] = str(
                        self.mergevalues(myvalues, newvalues))
                else:
                    objreturn['edgevalues'] = str(newvalues)
                newgaussian = self.getgaussian(newvalues)
                if newgaussian != None:
                    objreturn['edgegaussian'] = str(
                        self.mergevaluesG(myvaluesG, newgaussian))
                else:
                    objreturn['edgegaussian'] = str(newgaussian)
            else:
                objreturn['value'] = None

            self.response.out.write(json.dumps(objreturn))
        else:
            self.response.out.write(
                "Error, session invalid or invalid action.")
def renderPage(self, extension, mode='admin'):
    backend = self.request.get('backend', False)
    session = {}
    
    if backend: session['access_token'] = self.request.get('access_token', '') 
    else:
        session = sessionmanager.getsession(self)
        if session:
            roles = session['roles']
    
            if mode == 'admin' and not 'administrator' in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return
            elif not 'technician' in roles:
                self.response.out.write("You are not a technician for this site. Access denied.")
                return
        else:
            self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
        
    if extension in supported_extensions:
        q = db.GqlQuery("SELECT * FROM Index")
        
        if extension == 'xml':
            self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write('<indexes count="%s">\n' % q.count())
            
            for index in q:
                self.response.out.write('  <index uid="%s" name="%s" updated_time="%s" networkhash="%s">\n' % (index.uid, index.name, index.updated_time, index.networkhash))
                self.response.out.write('    <value value="%s" />' % index.value)
                self.response.out.write('    <nodevalues count="%s">\n' % len(index.get_nodevalues() or []))
                for nodevalue in (index.get_nodevalues() or []):
                    self.response.out.write('      <nodevalue bucket="%s" numnodes="%s" />\n' % (nodevalue[0], nodevalue[1]))
                self.response.out.write('    </nodevalues>\n')
                self.response.out.write('    <edgevalues count="%s">\n' % len(index.get_edgevalues() or []))
                for edgevalue in (index.get_edgevalues() or []):
                    self.response.out.write('      <edgevalue bucket="%s" numnodes="%s" />\n' % (edgevalue[0], edgevalue[1]))
                self.response.out.write('    </edgevalues>\n')
                self.response.out.write('  </index>\n\n')
                
            self.response.out.write('</indexes>')
                
        if extension == 'csv':
            self.response.headers['Content-Type'] = "text/csv"
            self.response.out.write('uid,name,updated_time,networkhash,value,nodebucket,nodevalue,edgebucket,edgevalue\n')
            
            for index in q:
                if len((index.get_nodevalues() or [])) == 0 and len((index.get_edgevalues() or [])) == 0:
                    self.response.out.write('%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (index.uid, index.name, index.updated_time, index.networkhash, index.value, '', '', '', '')) 
                for nodevalue in (index.get_nodevalues() or []):
                    self.response.out.write('%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (index.uid, index.name, index.updated_time, index.networkhash, index.value, nodevalue[0], nodevalue[1], '', ''))
                for edgevalue in (index.get_edgevalues() or []):
                    self.response.out.write('%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (index.uid, index.name, index.updated_time, index.networkhash, index.value, '', '', edgevalue[0], edgevalue[1]))
            
        if extension == 'xls':
            self.response.headers['Content-Type'] = "application/vnd.ms-excel"
            self.response.out.write('uid\tname\tupdated_time\tnetworkhash\tvalue\tnodebucket\tnodevalue\tedgebucket\tedgevalue\r\n')
            
            for index in q:
                if len((index.get_nodevalues() or [])) == 0 and len((index.get_edgevalues() or [])) == 0:
                    self.response.out.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' % (index.uid, index.name, index.updated_time, index.networkhash, index.value, '', '', '', '')) 
                for nodevalue in (index.get_nodevalues() or []):
                    self.response.out.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' % (index.uid, index.name, index.updated_time, index.networkhash, index.value, nodevalue[0], nodevalue[0], '', ''))
                for edgevalue in (index.get_edgevalues() or []):
                    self.response.out.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' % (index.uid, index.name, index.updated_time, index.networkhash, index.value, '', '', edgevalue[0], edgevalue[1]))
    else:
        self.response.out.write('Wrong format requested.')
def renderPageLogin(self, extension, mode='admin'):
    backend = self.request.get('backend', False)
    session = {}
    
    if backend: session['access_token'] = self.request.get('access_token', '') 
    else:
        session = sessionmanager.getsession(self)
        if session:
            roles = session['roles']
    
            if mode == 'admin' and not 'administrator' in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return
            elif not 'technician' in roles:
                self.response.out.write("You are not a technician for this site. Access denied.")
                return
        else:
            self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
        
    if extension in supported_extensions_login:
        if extension == 'docs':
            global serviceG
            global secret
            
            backend = self.request.get('backend', False)
            
            if backend:
                file_name = self.request.get('file_name', False)
                access_token = pickle.loads(base64.b64decode(self.request.get('google_access_token', '')))
                
                serviceG = gdata.apps.service.AppsService(source=conf.GOOGLE_APP_NAME)
                serviceG.SetOAuthInputParameters(signature_method=gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
                                                consumer_key=conf.GOOGLE_CONSUMER_KEY,
                                                consumer_secret=conf.GOOGLE_CONSUMER_SECRET)
                
                serviceG.current_token = access_token
                serviceG.SetOAuthToken(access_token)
                
                q = db.GqlQuery("SELECT * FROM Index")
                gspreadsheet = gdata.spreadsheet.service.SpreadsheetsService()
                gspreadsheet.SetOAuthToken(access_token)
                
                spreadsheet_id, worksheet_id = get_spreadsheet_by_name(gspreadsheet, file_name)
                index_worksheet_id = initialize_spreadsheet(gspreadsheet, spreadsheet_id, worksheet_id, q)
                populate_spreadsheet(gspreadsheet, spreadsheet_id, index_worksheet_id, q)
            else:
                scopes = ['https://docs.google.com/feeds/', 'https://spreadsheets.google.com/feeds/']
                oauth_callback = fbutils.base_url(self) + mode + '/indexes.docs?code=' + self.request.get('code')
                autheticated = self.request.get('oauth_token', None)
    
                if not autheticated:
                    serviceG = gdata.apps.service.AppsService(source=conf.GOOGLE_APP_NAME)
                    serviceG.SetOAuthInputParameters(signature_method=gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
                                                    consumer_key=conf.GOOGLE_CONSUMER_KEY,
                                                    consumer_secret=conf.GOOGLE_CONSUMER_SECRET)

                    request_token = serviceG.FetchOAuthRequestToken(scopes=scopes, oauth_callback=oauth_callback)
                    secret = request_token.secret
                    serviceG.SetOAuthToken(request_token)

                    google_auth_page_url = serviceG.GenerateOAuthAuthorizationURL()
                    self.redirect(google_auth_page_url) 
                else:
                    oauth_token = gdata.auth.OAuthTokenFromUrl(self.request.uri)
                    if oauth_token:
                        oauth_token.secret = secret
                        oauth_token.oauth_input_params = serviceG.GetOAuthInputParameters()
                        serviceG.SetOAuthToken(oauth_token)
                        
                        oauth_verifier = self.request.get('oauth_verifier', default_value='')
                        access_token = serviceG.UpgradeToOAuthAccessToken(oauth_verifier=oauth_verifier)
                        
                        if access_token:
                            serviceG.current_token = access_token
                            serviceG.SetOAuthToken(access_token)
                        else:
                            self.response.out.write("Error performing the OAuth authentication.")
                            return
                    else:
                        self.response.out.write("Error performing the OAuth authentication.")
                        return
                    
                    file_name = 'Computed indexes (%s)' % datetime.datetime.today()
                    spreadsheet_url = create_spreadsheet(access_token, file_name)
                    
                    taskqueue.add(url='/' + mode + '/indexes.docs',
                                  params={'code': self.request.get('code', None),
                                          'google_access_token': base64.b64encode(pickle.dumps(access_token)),
                                          'file_name': file_name,
                                          'backend': True,
                                          'access_token': session['access_token']},
                                  queue_name='gdocs-queue', method='POST', target='backend-indexes')
                    
                    self.redirect(spreadsheet_url)
Esempio n. 42
0
def renderPage(self, mode='admin'):
    session = sessionmanager.getsession(self)

    if session:
        roles = session['roles']

        if mode == 'admin' and not 'administrator' in roles:
            self.response.out.write(
                "You are not an administrator for this site. Access denied.")
            return
        elif not 'technician' in roles:
            self.response.out.write(
                "You are not a technician for this site. Access denied.")
            return

        code = self.request.get('code', None)
        uid = self.request.get('uid', None)

        users = None
        network = None

        if uid == None:
            upload_url = '/' + mode + '/viewnetwork?code=' + code
            users = []
            q = db.GqlQuery("SELECT * FROM User")
            for user in q:
                users.append(user)
        else:
            if mode == 'tech':
                upload_url = '/tech/savenetwork?uid=' + uid + '&code=' + code
            else:
                upload_url = '/admin?code=' + code

            if uid == "_new_":
                network = None
            else:
                q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
                network = q.fetch(1)

                if len(network) == 0: network = None
                else: network = network[0]

        template_values = {
            'appId': conf.FBAPI_APP_ID,
            'token': session['access_token'],
            'app': session['appid'],
            'conf': conf,
            'me': session['me'],
            'roles': roles,
            'upload_url': upload_url,
            'mode': mode,
            'uid': uid,
            'users': users,
            'network': network,
            'isdesktop': session['isdesktop'],
            'header': '',
            'code': code
        }

        root = os.path.normpath(
            os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_header.html'),
                            template_values))
        self.response.out.write(
            template.render(
                os.path.join(root, 'admin/templates/vieweditnetwork.html'),
                template_values))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_footer.html'),
                            template_values))
    else:
        self.redirect(
            fbutils.oauth_login_url(self=self,
                                    next_url=fbutils.base_url(self)))
Esempio n. 43
0
    def renderPage(self):
        session = sessionmanager.getsession(self)
        
        if session:
            app_friends = fbutils.fql(
                "SELECT uid, name, is_app_user, pic_square "
                "FROM user "
                "WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND "
                "  is_app_user = 1", session['access_token'])
            
            q = db.GqlQuery("SELECT * FROM User WHERE uid = :1", session['me']['id'])
            users = q.fetch(1)

            datefb = session['me']['updated_time'].replace("+0000", "").replace("T", " ")
            datefb = datetime.datetime.fromtimestamp(
                   time.mktime(time.strptime(datefb, "%Y-%m-%d %H:%M:%S")))
            
            if len(users) > 0:
                curuser = users[0]
                datedb = curuser.updated_time

                if datefb > datedb:
                    curuser.first_name = session['me']['first_name']
                    curuser.last_name = session['me']['last_name']
                    curuser.link = session['me']['link']
                    if 'username' in session['me']:
                        curuser.username = session['me']['username']
                    curuser.updated_time = datefb
                    curuser.put()
                  
                    logging.info('User updated: ' + session['me']['id'])
            else:
                curuser = obj_user.User(uid = session['me']['id'])
                curuser.first_name = session['me']['first_name']
                curuser.last_name = session['me']['last_name']
                curuser.link = session['me']['link']
                if 'username' in session['me']:
                    curuser.username = session['me']['username']
                curuser.updated_time = datefb
                curuser.put()
              
                logging.info('User added: ' + session['me']['id'])

            indexes = []
            q = db.GqlQuery("SELECT * FROM Index " +
                        "WHERE uid = :1 " +
                        "ORDER BY updated_time DESC",
                        session['me']['id'])
            
            for index in q:            
                if not index.networkhash == None and \
                   not index.value == None and \
                   not index.name in indexes:
                    indexes.append(index.name)
            
            tests = []
            q = db.GqlQuery("SELECT * FROM Test")
        
            for test in q:
                if test.active and datetime.date.today() >= test.startdate and datetime.date.today() <= test.enddate:
                    tests.append(test)

            template_values = {
                'appId': conf.FBAPI_APP_ID,
                'token': session['access_token'],
                'app_friends': app_friends,
                'app': session['appid'],
                'conf': conf,
                'me': session['me'],
                'roles': session['roles'],
                'computedindexes': indexes,
                'numindexes': len(conf.INDEXES),
                'tests': tests,
                'isdesktop': session['isdesktop'],
                'header': '',
                'code': self.request.get('code') }

            root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
            self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
            self.response.out.write(template.render(os.path.join(root, 'pages/templates/home.html'), template_values))
            self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
        else:
            self.response.out.write('''
            <html><head>
            <script type="text/javascript">
            <!--
            var _gaq = _gaq || [];
            _gaq.push(['_setAccount', 'UA-256445-3']);
            _gaq.push(['_trackPageview']);

            (function() {
              var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
              ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
              var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
            })();
            // -->
            </script>''')
            
            self.response.out.write('<meta HTTP-EQUIV="REFRESH" content="0; url=' +
                fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)) +
                '"></head><body></body></html>')
    def renderPage(self, uid):
        code = self.request.get('code', None)

        session = sessionmanager.getsession(self)
        try:
            if session['me']['id'] != uid: code = None
        except:
            code = None

        nodes = None
        edges = None
        league = None
        hiddenleague = False

        q = db.GqlQuery("SELECT * FROM Network WHERE uid = :1", uid)
        networks = q.fetch(1)

        if not len(networks) == 0:
            network = networks[0]

            nodes = network.getnodes()
            edges = network.getedges()
            league = network.getleague()

            try:
                if not fbutils.is_friend(session['access_token'],
                                         session['me']['id'], uid):
                    for row in league:
                        row[1] = re.sub("\w", "x", row[1]).title()
                    hiddenleague = True
            except:
                for row in league:
                    row[1] = re.sub("\w", "x", row[1]).title()
                hiddenleague = True

        if session == None:
            app_friends = None
        else:
            app_friends = fbutils.fql(
                "SELECT uid, name, is_app_user " + "FROM user " +
                "WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1 "
                + "ORDER BY name", session['access_token'])

        template_values = {
            'conf': conf,
            'uid': uid,
            'me': session['me'],
            'nodes': nodes,
            'edges': edges,
            'league': league,
            'hiddenleague': hiddenleague,
            'friends': app_friends,
            'isdesktop': session and session['isdesktop'] or False,
            'header': 'network',
            'code': code
        }

        root = os.path.normpath(
            os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_header.html'),
                            template_values))
        self.response.out.write(
            template.render(os.path.join(root, 'pages/templates/network.html'),
                            template_values))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_footer.html'),
                            template_values))
def renderPageLogin(self, extension, mode="admin"):
    backend = self.request.get("backend", False)
    session = {}

    if backend:
        session["access_token"] = self.request.get("access_token", "")
    else:
        session = sessionmanager.getsession(self)
        if session:
            roles = session["roles"]

            if mode == "admin" and not "administrator" in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return
            elif not "technician" in roles:
                self.response.out.write("You are not a technician for this site. Access denied.")
                return
        else:
            self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))

    if extension in supported_extensions_login:
        if extension == "docs":
            global serviceG
            global secret

            if backend:
                file_name = self.request.get("file_name", False)
                access_token = pickle.loads(base64.b64decode(self.request.get("google_access_token", "")))

                serviceG = gdata.apps.service.AppsService(source=conf.GOOGLE_APP_NAME)
                serviceG.SetOAuthInputParameters(
                    signature_method=gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
                    consumer_key=conf.GOOGLE_CONSUMER_KEY,
                    consumer_secret=conf.GOOGLE_CONSUMER_SECRET,
                )

                serviceG.current_token = access_token
                serviceG.SetOAuthToken(access_token)

                q = db.GqlQuery("SELECT * FROM Network")
                gspreadsheet = gdata.spreadsheet.service.SpreadsheetsService()
                gspreadsheet.SetOAuthToken(access_token)

                spreadsheet_id, worksheet_id = get_spreadsheet_by_name(gspreadsheet, file_name)
                nodes_worksheet_id, edges_worksheet_id, leagues_worksheet_id = initialize_spreadsheet(
                    gspreadsheet, spreadsheet_id, worksheet_id, q
                )
                populate_spreadsheet(
                    gspreadsheet, spreadsheet_id, nodes_worksheet_id, edges_worksheet_id, leagues_worksheet_id, q
                )
            else:
                scopes = ["https://docs.google.com/feeds/", "https://spreadsheets.google.com/feeds/"]
                oauth_callback = fbutils.base_url(self) + mode + "/networks.docs?code=" + self.request.get("code")
                autheticated = self.request.get("oauth_token", None)

                if not autheticated:
                    serviceG = gdata.apps.service.AppsService(source=conf.GOOGLE_APP_NAME)
                    serviceG.SetOAuthInputParameters(
                        signature_method=gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
                        consumer_key=conf.GOOGLE_CONSUMER_KEY,
                        consumer_secret=conf.GOOGLE_CONSUMER_SECRET,
                    )

                    request_token = serviceG.FetchOAuthRequestToken(scopes=scopes, oauth_callback=oauth_callback)
                    secret = request_token.secret
                    serviceG.SetOAuthToken(request_token)

                    google_auth_page_url = serviceG.GenerateOAuthAuthorizationURL()
                    self.redirect(google_auth_page_url)
                else:
                    oauth_token = gdata.auth.OAuthTokenFromUrl(self.request.uri)
                    if oauth_token:
                        oauth_token.secret = secret
                        oauth_token.oauth_input_params = serviceG.GetOAuthInputParameters()
                        serviceG.SetOAuthToken(oauth_token)

                        oauth_verifier = self.request.get("oauth_verifier", default_value="")
                        access_token = serviceG.UpgradeToOAuthAccessToken(oauth_verifier=oauth_verifier)

                        if access_token:
                            serviceG.current_token = access_token
                            serviceG.SetOAuthToken(access_token)
                        else:
                            self.response.out.write("Error performing the OAuth authentication.")
                            return
                    else:
                        self.response.out.write("Error performing the OAuth authentication.")
                        return

                    file_name = "Network informations (%s)" % datetime.datetime.today()
                    spreadsheet_url = create_spreadsheet(access_token, file_name)

                    taskqueue.add(
                        url="/" + mode + "/networks.docs",
                        params={
                            "code": self.request.get("code", None),
                            "google_access_token": base64.b64encode(pickle.dumps(access_token)),
                            "file_name": file_name,
                            "backend": True,
                            "access_token": session["access_token"],
                        },
                        queue_name="gdocs-queue",
                        method="POST",
                        target="backend-indexes",
                    )

                    self.redirect(spreadsheet_url)
def renderPage(self, extension, mode="admin"):
    backend = self.request.get("backend", False)
    session = {}

    if backend:
        session["access_token"] = self.request.get("access_token", "")
    else:
        session = sessionmanager.getsession(self)
        if session:
            roles = session["roles"]

            if mode == "admin" and not "administrator" in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return
            elif not "technician" in roles:
                self.response.out.write("You are not a technician for this site. Access denied.")
                return
        else:
            self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))

    if extension in supported_extensions:
        q = db.GqlQuery("SELECT * FROM Network")

        if extension == "xml":
            self.response.headers["Content-Type"] = "text/xml"
            self.response.out.write('<networks count="%s">' % q.count())

            for network in q:
                self.response.out.write(
                    '  <network uid="%s" updated_time="%s" netowrkhash="%s">\n'
                    % (network.uid, network.updated_time, network.networkhash)
                )
                self.response.out.write('    <nodes count="%s">\n' % len(network.getnodes() or []))
                for node in network.getnodes() or []:
                    self.response.out.write('      <node id="%s" />\n' % node)
                self.response.out.write("    </nodes>\n")
                self.response.out.write('    <edges count="%s">\n' % len(network.getedges() or []))
                for fromnode, tonode in network.getedges() or []:
                    self.response.out.write('      <edge fromNodeId="%s" toNodeId="%s" />\n' % (fromnode, tonode))
                self.response.out.write("    </edges>\n")
                self.response.out.write('    <league count="%s">\n' % len(network.getleague() or []))
                for table in network.getleague() or []:
                    self.response.out.write(
                        '      <friend uid="%s" name="%s" degree="%s" closeness="%s" betweenness="%s"/>\n'
                        % (table[0], table[1], table[2], table[3], table[4])
                    )
                self.response.out.write("    </league>\n")
                self.response.out.write("  </network>\n\n")

            self.response.out.write("</networks>")

        if extension == "csv":
            self.response.headers["Content-Type"] = "text/csv"
            self.response.out.write(
                "uid,updated_time,networkhash,nodeid,fromnodeid,tonodeid,uid,name,degree,closeness,betweenness\n"
            )

            for network in q:
                if (
                    len((network.getnodes() or [])) == 0
                    and len((network.getedges() or [])) == 0
                    and len((network.getleague() or [])) == 0
                ):
                    self.response.out.write(
                        "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n"
                        % (network.uid, network.updated_time, network.networkhash, "", "", "", "", "", "", "", "")
                    )
                for nodevalue in network.getnodes() or []:
                    self.response.out.write(
                        "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n"
                        % (
                            network.uid,
                            network.updated_time,
                            network.networkhash,
                            nodevalue,
                            "",
                            "",
                            "",
                            "",
                            "",
                            "",
                            "",
                        )
                    )
                for edgevalue in network.getedges() or []:
                    self.response.out.write(
                        "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n"
                        % (
                            network.uid,
                            network.updated_time,
                            network.networkhash,
                            "",
                            edgevalue[0],
                            edgevalue[1],
                            "",
                            "",
                            "",
                            "",
                            "",
                        )
                    )
                for table in network.getleague() or []:
                    self.response.out.write(
                        "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n"
                        % (
                            network.uid,
                            network.updated_time,
                            network.networkhash,
                            "",
                            "",
                            "",
                            table[0],
                            table[1],
                            table[2],
                            table[3],
                            table[4],
                        )
                    )

        if extension == "xls":
            self.response.headers["Content-Type"] = "application/vnd.ms-excel"
            self.response.out.write(
                "uid\tupdated_time\tnetworkhash\tnodeid\tfromnodeid\ttonodeid\tuid,name\tdegree\tcloseness\tbetweenness\r\n"
            )

            for network in q:
                if (
                    len((network.getnodes() or [])) == 0
                    and len((network.getedges() or [])) == 0
                    and len((network.getleague() or [])) == 0
                ):
                    self.response.out.write(
                        "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n"
                        % (network.uid, network.updated_time, network.networkhash, "", "", "", "", "", "", "", "")
                    )
                for nodevalue in network.getnodes() or []:
                    self.response.out.write(
                        "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n"
                        % (
                            network.uid,
                            network.updated_time,
                            network.networkhash,
                            nodevalue,
                            "",
                            "",
                            "",
                            "",
                            "",
                            "",
                            "",
                        )
                    )
                for edgevalue in network.getedges() or []:
                    self.response.out.write(
                        "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n"
                        % (
                            network.uid,
                            network.updated_time,
                            network.networkhash,
                            "",
                            edgevalue[0],
                            edgevalue[1],
                            "",
                            "",
                            "",
                            "",
                            "",
                        )
                    )
                for table in network.getleague() or []:
                    self.response.out.write(
                        "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n"
                        % (
                            network.uid,
                            network.updated_time,
                            network.networkhash,
                            "",
                            "",
                            "",
                            table[0],
                            table[1],
                            table[2],
                            table[3],
                            table[4],
                        )
                    )
    else:
        self.response.out.write("Wrong format requested.")
def renderPageLogin(self, extension, mode='admin'):
    backend = self.request.get('backend', False)
    session = {}
    
    if backend: session['access_token'] = self.request.get('access_token', '') 
    else:
        session = sessionmanager.getsession(self)
        if session:
            roles = session['roles']
    
            if mode == 'admin' and not 'administrator' in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return
            elif not 'technician' in roles:
                self.response.out.write("You are not a technician for this site. Access denied.")
                return
        else:
            self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
            
    if extension in supported_extensions_login:
        if extension == 'docs':
            global serviceG
            global secret
            
            if backend:
                file_name = self.request.get('file_name', False)
                access_token = pickle.loads(base64.b64decode(self.request.get('google_access_token', '')))
                
                serviceG = gdata.apps.service.AppsService(source=conf.GOOGLE_APP_NAME)
                serviceG.SetOAuthInputParameters(signature_method=gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
                                                consumer_key=conf.GOOGLE_CONSUMER_KEY,
                                                consumer_secret=conf.GOOGLE_CONSUMER_SECRET)
                
                serviceG.current_token = access_token
                serviceG.SetOAuthToken(access_token)
                
                q = db.GqlQuery("SELECT * FROM Network")
                gspreadsheet = gdata.spreadsheet.service.SpreadsheetsService()
                gspreadsheet.SetOAuthToken(access_token)
                
                spreadsheet_id, worksheet_id = get_spreadsheet_by_name(gspreadsheet, file_name)
                nodes_worksheet_id, edges_worksheet_id, leagues_worksheet_id = initialize_spreadsheet(gspreadsheet, spreadsheet_id, worksheet_id, q)
                populate_spreadsheet(gspreadsheet, spreadsheet_id, nodes_worksheet_id, edges_worksheet_id, leagues_worksheet_id, q)
            else:
                scopes = ['https://docs.google.com/feeds/', 'https://spreadsheets.google.com/feeds/']
                oauth_callback = fbutils.base_url(self) + mode + '/networks.docs?code=' + self.request.get('code')
                autheticated = self.request.get('oauth_token', None)
    
                if not autheticated:
                    serviceG = gdata.apps.service.AppsService(source=conf.GOOGLE_APP_NAME)
                    serviceG.SetOAuthInputParameters(signature_method=gdata.auth.OAuthSignatureMethod.HMAC_SHA1,
                                                    consumer_key=conf.GOOGLE_CONSUMER_KEY,
                                                    consumer_secret=conf.GOOGLE_CONSUMER_SECRET)

                    request_token = serviceG.FetchOAuthRequestToken(scopes=scopes, oauth_callback=oauth_callback)
                    secret = request_token.secret
                    serviceG.SetOAuthToken(request_token)

                    google_auth_page_url = serviceG.GenerateOAuthAuthorizationURL()
                    self.redirect(google_auth_page_url) 
                else:
                    oauth_token = gdata.auth.OAuthTokenFromUrl(self.request.uri)
                    if oauth_token:
                        oauth_token.secret = secret
                        oauth_token.oauth_input_params = serviceG.GetOAuthInputParameters()
                        serviceG.SetOAuthToken(oauth_token)
                        
                        oauth_verifier = self.request.get('oauth_verifier', default_value='')
                        access_token = serviceG.UpgradeToOAuthAccessToken(oauth_verifier=oauth_verifier)
                        
                        if access_token:
                            serviceG.current_token = access_token
                            serviceG.SetOAuthToken(access_token)
                        else:
                            self.response.out.write("Error performing the OAuth authentication.")
                            return
                    else:
                        self.response.out.write("Error performing the OAuth authentication.")
                        return
                    
                    file_name = 'Network informations (%s)' % datetime.datetime.today()
                    spreadsheet_url = create_spreadsheet(access_token, file_name)
                    
                    taskqueue.add(url='/' + mode + '/networks.docs',
                                  params={'code': self.request.get('code', None),
                                          'google_access_token': base64.b64encode(pickle.dumps(access_token)),
                                          'file_name': file_name,
                                          'backend': True,
                                          'access_token': session['access_token']},
                                  queue_name='gdocs-queue', method='POST', target='backend-indexes')
                    
                    self.redirect(spreadsheet_url)
Esempio n. 48
0
    def renderPage(self, uid, indexname):
        code = self.request.get('code', None)
        index = None

        value = None
        nodevalues = None
        edgevalues = None
        nodegaussian = None
        edgegaussian = None

        session = sessionmanager.getsession(self)
        try:
            if session['me']['id'] != uid: code = None
        except:
            code = None

        q = db.GqlQuery(
            "SELECT * FROM Index " + "WHERE uid = :1 AND name = :2 " +
            "ORDER BY updated_time DESC", uid, indexname)
        indexes = q.fetch(1)

        if not len(indexes) == 0:
            index = indexes[0]

            value = index.value
            nodevalues = self.setcentiles(index.get_nodevalues())
            edgevalues = self.setcentiles(index.get_edgevalues())
            nodegaussian = self.getgaussian(nodevalues)
            edgegaussian = self.getgaussian(edgevalues)

        if session == None:
            app_friends = None
        else:
            app_friends = fbutils.fql(
                "SELECT uid, name, is_app_user " + "FROM user " +
                "WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1 "
                + "ORDER BY name", session['access_token'])

        template_values = {
            'conf': conf,
            'indexname': indexname,
            'description': conf.INDEXES[indexname],
            'uid': uid,
            'index': index,
            'nodevalues': nodevalues,
            'edgevalues': edgevalues,
            'nodegaussian': nodegaussian,
            'edgegaussian': edgegaussian,
            'value': value,
            'friends': app_friends,
            'isdesktop': session and session['isdesktop'] or False,
            'header': 'sociologicalindex',
            'code': code
        }

        root = os.path.normpath(
            os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_header.html'),
                            template_values))
        self.response.out.write(
            template.render(
                os.path.join(root, 'pages/templates/sociologicalindex.html'),
                template_values))
        self.response.out.write(
            template.render(os.path.join(root, 'templates/_footer.html'),
                            template_values))
def renderPage(self, extension, mode='admin'):
    backend = self.request.get('backend', False)
    session = {}
    
    if backend: session['access_token'] = self.request.get('access_token', '') 
    else:
        session = sessionmanager.getsession(self)
        if session:
            roles = session['roles']
    
            if mode == 'admin' and not 'administrator' in roles:
                self.response.out.write("You are not an administrator for this site. Access denied.")
                return
            elif not 'technician' in roles:
                self.response.out.write("You are not a technician for this site. Access denied.")
                return
        else:
            self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
        
    if extension in supported_extensions:
        q = db.GqlQuery("SELECT * FROM Network")
        
        if extension == 'xml':
            self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write('<networks count="%s">' % q.count())
            
            for network in q:
                self.response.out.write('  <network uid="%s" updated_time="%s" netowrkhash="%s">\n' % (network.uid, network.updated_time, network.networkhash))
                self.response.out.write('    <nodes count="%s">\n' % len(network.getnodes() or []))
                for node in (network.getnodes() or []):
                    self.response.out.write('      <node id="%s" />\n' % node)
                self.response.out.write('    </nodes>\n')
                self.response.out.write('    <edges count="%s">\n' % len(network.getedges() or []))
                for fromnode, tonode in (network.getedges() or []):
                    self.response.out.write('      <edge fromNodeId="%s" toNodeId="%s" />\n' % (fromnode, tonode))
                self.response.out.write('    </edges>\n')
                self.response.out.write('    <league count="%s">\n' % len(network.getleague() or []))
                for table in (network.getleague() or []):
                    self.response.out.write('      <friend uid="%s" name="%s" degree="%s" closeness="%s" betweenness="%s"/>\n' % (table[0], table[1], table[2], table[3], table[4]))
                self.response.out.write('    </league>\n')
                self.response.out.write('  </network>\n\n')
                                        
            self.response.out.write('</networks>')
                
        if extension == 'csv':
            self.response.headers['Content-Type'] = "text/csv"
            self.response.out.write('uid,updated_time,networkhash,nodeid,fromnodeid,tonodeid,uid,name,degree,closeness,betweenness\n')
            
            for network in q:
                if len((network.getnodes() or [])) == 0 and len((network.getedges() or [])) == 0 and len((network.getleague() or [])) == 0:
                    self.response.out.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (network.uid, network.updated_time, network.networkhash, '', '', '', '', '', '', '', '')) 
                for nodevalue in (network.getnodes() or []):
                    self.response.out.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (network.uid, network.updated_time, network.networkhash, nodevalue, '', '', '', '', '', '', ''))
                for edgevalue in (network.getedges() or []):
                    self.response.out.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (network.uid, network.updated_time, network.networkhash, '', edgevalue[0], edgevalue[1], '', '', '', '', ''))
                for table in (network.getleague() or []):    
                    self.response.out.write('%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (network.uid, network.updated_time, network.networkhash, '', '', '', table[0], table[1], table[2], table[3], table[4]))
            
        if extension == 'xls':
            self.response.headers['Content-Type'] = "application/vnd.ms-excel"
            self.response.out.write('uid\tupdated_time\tnetworkhash\tnodeid\tfromnodeid\ttonodeid\tuid,name\tdegree\tcloseness\tbetweenness\r\n')
            
            for network in q:
                if len((network.getnodes() or [])) == 0 and len((network.getedges() or [])) == 0 and len((network.getleague() or [])) == 0:
                    self.response.out.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' % (network.uid, network.updated_time, network.networkhash, '', '', '', '', '', '', '', '')) 
                for nodevalue in (network.getnodes() or []):
                    self.response.out.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' % (network.uid, network.updated_time, network.networkhash, nodevalue, '', '', '', '', '', '', ''))
                for edgevalue in (network.getedges() or []):
                    self.response.out.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' % (network.uid, network.updated_time, network.networkhash, '', edgevalue[0], edgevalue[1], '', '', '', '', ''))
                for table in (network.getleague() or []):    
                    self.response.out.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' % (network.uid, network.updated_time, network.networkhash, '', '', '', table[0], table[1], table[2], table[3], table[4]))
    else:
        self.response.out.write('Wrong format requested.')
def renderPage(self, mode="admin"):
    session = sessionmanager.getsession(self)

    if self.request.get("code", None) and session:
        roles = session["roles"]

        if mode == "admin" and not "administrator" in roles:
            self.response.out.write("You are not an administrator for this site. Access denied.")
            return
        elif not "technician" in roles:
            self.response.out.write("You are not a technician for this site. Access denied.")
            return

        code = self.request.get("code", None)
        uid = self.request.get("uid", None)

        users = None
        index = None

        if uid == None:
            upload_url = "/" + mode + "/viewindex?code=" + code
            users = []
            q = db.GqlQuery("SELECT * FROM User")
            for user in q:
                users.append(user)
        else:
            if mode == "tech":
                upload_url = "/tech/saveindex?uid=" + uid + "&code=" + code
            else:
                upload_url = "/admin?code=" + code

            indexname = self.request.get("indexname", None)

            if indexname != "_new_":
                q = db.GqlQuery(
                    "SELECT * FROM Index WHERE uid = :1 AND name = :2 ORDER BY updated_time DESC", uid, indexname
                )
                index = q.fetch(1)

                if len(index) == 0:
                    index = None
                else:
                    index = index[0]
            else:
                index = None

        template_values = {
            "appId": conf.FBAPI_APP_ID,
            "token": session["access_token"],
            "app": session["appid"],
            "conf": conf,
            "me": session["me"],
            "roles": roles,
            "upload_url": upload_url,
            "mode": mode,
            "uid": uid,
            "users": users,
            "index": index,
            "isdesktop": session and session["isdesktop"] or False,
            "header": "",
            "code": code,
        }

        root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
        self.response.out.write(template.render(os.path.join(root, "templates/_header.html"), template_values))
        self.response.out.write(
            template.render(os.path.join(root, "admin/templates/vieweditindex.html"), template_values)
        )
        self.response.out.write(template.render(os.path.join(root, "templates/_footer.html"), template_values))
    else:
        self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)))
Esempio n. 51
0
    def renderPage(self):
        session = sessionmanager.getsession(
            self, redirect_uri=fbutils.base_url(self) + 'opensesame/access')

        if session:
            SERVER_ADDRESS = ('127.0.0.1', 33333)

            template_values = {
                'appId': conf.FBAPI_APP_ID,
                'token': session['access_token'],
                'app': session['appid'],
                'conf': conf,
                'me': session['me'],
                'roles': session['roles'],
                'isdesktop': session['isdesktop'],
                'header': ''
            }

            root = os.path.normpath(
                os.path.join(os.path.dirname(__file__), os.path.pardir))
            self.response.out.write(
                template.render(os.path.join(root, 'templates/_header.html'),
                                template_values))

            self.response.out.write('<header class="clearfix">')
            self.response.out.write(
                '<p id="picture" style="background-image: url(/static/images/macchie.jpg); background-size: 64px 64px"></p>'
            )
            self.response.out.write(
                '<h1>Rorschach Test Platform authentication</h1>')
            self.response.out.write('</header>')

            self.response.out.write(
                '<section id="normalsection" class="clearfix">')
            self.response.out.write(
                '<h3>Associate OpenSesame with Rorschach Test Platform</h3>')
            self.response.out.write(
                '<p>In order to use the OpenSesame plugin, you need to authenticate with Facebook and give grants to the Rorschach Test Platform application.</p>'
            )
            self.response.out.write(
                '<p>By clicking the button below you will create a temporary access token to be used by the OpenSesame plugin.<br/>'
            )
            self.response.out.write(
                'The access token created with this procedure will have a lifetime of two hours (as by Facebook standards) and so after two hours it will be automatically declared invalid.</p>'
            )
            self.response.out.write(
                '<form action="http://%s:%s/" method="post" name="codeSubmit" id="codeSubmit">'
                % SERVER_ADDRESS)
            self.response.out.write(
                '<input type="hidden" id="code" name="code" value="' +
                self.request.get('code', None) + '" />')
            self.response.out.write(
                '<input type="hidden" id="access_token" name="access_token" value="'
                + session['access_token'] + '" />')
            self.response.out.write(
                '<p class="button"><a href="#" class="facebook-button" onclick="$(\'#codeSubmit\').submit();">'
            )
            self.response.out.write(
                '<span class="plus">Save the access token</span></a></p>')
            self.response.out.write('</section>')

            self.response.out.write(
                template.render(os.path.join(root, 'templates/_footer.html'),
                                template_values))
        else:
            self.redirect(
                fbutils.oauth_login_url(self=self,
                                        next_url=fbutils.base_url(self) +
                                        'opensesame/access'))
    def post(self):
        session = sessionmanager.getsession(self)

        if session:
            roles = session['roles']

            if not 'technician' in roles:
                self.response.out.write(
                    "You are not a technician for this site. Access denied.")
                return

            action = self.request.get('action', None)
            code = self.request.get('code', None)
            uid = self.request.get('uid', None)

            if action == "selectUid":
                objreturn = {}
                objreturn['indexes'] = []

                q = db.GqlQuery("SELECT * FROM Index WHERE uid = :1", uid)
                for index in q:
                    if not index.name in objreturn['indexes']:
                        objreturn['indexes'].append(index.name)

                self.response.out.write(json.dumps(objreturn))
            elif action == "computeIndex":
                indexname = self.request.get('indexname', None)
                libSNA = computeprofileindex.getLibSNA(self, session)
                objreturn = computeprofileindex.computeIndex(
                    self,
                    libSNA,
                    indexname,
                    False,
                    session,
                    saveInDatastore=False)

                if 'nodes' in objreturn:
                    objreturn['nodes'] = str(objreturn['nodes'])
                if 'edges' in objreturn:
                    objreturn['edges'] = str(objreturn['edges'])
                self.response.out.write(json.dumps(objreturn))
            elif action == "saveIndex":
                indexname = self.request.get('indexname', None)
                networkhash = self.request.get('networkhash', None)
                value = self.request.get('value', None)
                edges = self.request.get('edges', None)
                nodes = self.request.get('nodes', None)

                index = obj_index.Index(uid=self.request.get('uid', None),
                                        name=indexname)
                index.updated_time = datetime.datetime.now()
                index.networkhash = networkhash

                index.value = float(value)
                if not edges == None: index.set_edgevalues(edges)
                if not nodes == None: index.set_nodevalues(nodes)
                index.put()

                logging.info("Updated index data for user: " + uid)
                self.redirect('/tech/viewindex?uid=' + uid + '&code=' + code)
            else:
                self.redirect('/tech/viewindex?uid=' + uid + '&code=' + code)
 def renderPage(self):
     access_token = self.request.get('token', None)
     session = sessionmanager.getsession(self, access_token=access_token, redirect_uri=fbutils.base_url(self)+'opensesame/access')
     
     objreturn = {}
     objreturn['result'] = False
     objreturn['message'] = 'Wrong session'
     
     if session:
         indexes = {}
         for index in conf.INDEXES.keys(): indexes[index] = "<null>"
         
         q = db.GqlQuery("SELECT * FROM Index " +
                         "WHERE uid = :1 " +
                         "ORDER BY updated_time DESC",
                         session['me']['id'])
         for index in q:
             if not index.networkhash == None and not index.value == None:
                 indexes[index.name] = (conf.INDEX_TYPES[index.name]) % index.value
         
         SERVER_ADDRESS = ('127.0.0.1', 33333)
         
         reqired_indexes = []
         try: reqired_indexes = eval(self.request.get('reqired_indexes'))
         except: pass
         
         template_values = {
             'appId': conf.FBAPI_APP_ID,
             'token': session['access_token'],
             'app': session['appid'],
             'conf': conf,
             'me': session['me'],
             'roles': session['roles'],
             'isdesktop': session['isdesktop'],
             'header': ''}
         
         root = os.path.normpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
         self.response.out.write(template.render(os.path.join(root, 'templates/_header.html'), template_values))
         
         self.response.out.write('<header class="clearfix">')
         self.response.out.write('<p id="picture" style="background-image: url(/static/images/macchie.jpg); background-size: 64px 64px"></p>')
         self.response.out.write('<h1>Rorschach Test Platform index value retrieval for OpenSesame</h1>')
         self.response.out.write('</header>')
         
         self.response.out.write('<section id="normalsection" class="clearfix">')
         self.response.out.write('<h3>Index values to be submitted to the OpenSesame test</h3>')
         self.response.out.write('<p>The test you are about to take wants to download the values of some index computed on Rorschach Test Platform.</p>')
         self.response.out.write('<p>To proceed you have to verify that all needed indexes are computed for your profile, and then click on the "Save index values" button below.<br/>&nbsp;</p>') 
         self.response.out.write('<form action="http://%s:%s/" method="post" name="valueSubmit" id="valueSubmit">' % SERVER_ADDRESS)
         
         self.response.out.write('<table width="800px" style="border: 1px solid black">')
         self.response.out.write('<thead><td style="padding: 5px"><strong>Index Name</strong></td><td style="padding: 5px"><strong>Computed value</strong></td><td style="padding: 5px"><strong>Action</strong></td></thead>')
         for cur_index in reqired_indexes: 
             self.response.out.write('<tr><td id="' + cur_index + '_name" style="padding: 5px"><a href="/index/' + session['me']['id'] + '/' + cur_index + '" target="_blank">' + cur_index + '</a></td>')
             self.response.out.write('<td id="' + cur_index + '_value" style="padding: 5px">' + (indexes[cur_index] == "<null>" and "&lt;null&gt;" or str(indexes[cur_index])) + '</td>')
             self.response.out.write('<td><p class="button"><a href="#" class="facebook-button" id="' + cur_index + '_button">')
             self.response.out.write('<span class="plus">Compute</span></a></p></td></tr>')
             self.response.out.write('<input type="hidden" id="' + cur_index + '" name="' + cur_index + '" value="' + str(indexes[cur_index]) + '" />')
             self.response.out.write('<script type="text/javascript">\n')
             self.response.out.write('<!--\n')
             self.response.out.write('$(document).ready(function(){\n')
             self.response.out.write('$("#' + cur_index + '_button").click(function() { $.ajax({ type : "POST", url : "/computeprofileindex", dataType : "json", ')
             self.response.out.write('data: { id : "' + session['me']['id'] + '", access_token : "' + access_token +  '", index : "' + cur_index + '" },')
             self.response.out.write('success: function(data) { if (data.error === true) { alert("Error computing index: ' + cur_index + '"); } else { ')
             self.response.out.write('if (data.value != "") { $("#' + cur_index + '_value").text(data.value); $("#' + cur_index + '").val(data.value); } ')
             self.response.out.write('else { alert("The computation has been sent background. Hit che compute button in a few minutes to get the computed value."); } } },')
             self.response.out.write('error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error computing index: ' + cur_index + '"); } }); ')
             self.response.out.write(' return false; }); });\n') 
             self.response.out.write('// -->\n')
             self.response.out.write('</script>')
             
         self.response.out.write('</table>')
         self.response.out.write('</form><p><br/>')
         
         self.response.out.write('<p class="button"><a href="#" class="facebook-button" onclick="$(\'#valueSubmit\').submit();">')
         self.response.out.write('<span class="plus">Save index values</span></a></p>')
         self.response.out.write('</section>')
         
         self.response.out.write(template.render(os.path.join(root, 'templates/_footer.html'), template_values))
     else:
         self.redirect(fbutils.oauth_login_url(self=self, next_url=fbutils.base_url(self)+'opensesame/access'))
Esempio n. 54
0
def renderPage(self, extension, mode='admin'):
    backend = self.request.get('backend', False)
    session = {}

    if backend: session['access_token'] = self.request.get('access_token', '')
    else:
        session = sessionmanager.getsession(self)
        if session:
            roles = session['roles']

            if mode == 'admin' and not 'administrator' in roles:
                self.response.out.write(
                    "You are not an administrator for this site. Access denied."
                )
                return
            elif not 'technician' in roles:
                self.response.out.write(
                    "You are not a technician for this site. Access denied.")
                return
        else:
            self.redirect(
                fbutils.oauth_login_url(self=self,
                                        next_url=fbutils.base_url(self)))

    if extension in supported_extensions:
        q = db.GqlQuery("SELECT * FROM Index")

        if extension == 'xml':
            self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write('<indexes count="%s">\n' % q.count())

            for index in q:
                self.response.out.write(
                    '  <index uid="%s" name="%s" updated_time="%s" networkhash="%s">\n'
                    % (index.uid, index.name, index.updated_time,
                       index.networkhash))
                self.response.out.write('    <value value="%s" />' %
                                        index.value)
                self.response.out.write('    <nodevalues count="%s">\n' %
                                        len(index.get_nodevalues() or []))
                for nodevalue in (index.get_nodevalues() or []):
                    self.response.out.write(
                        '      <nodevalue bucket="%s" numnodes="%s" />\n' %
                        (nodevalue[0], nodevalue[1]))
                self.response.out.write('    </nodevalues>\n')
                self.response.out.write('    <edgevalues count="%s">\n' %
                                        len(index.get_edgevalues() or []))
                for edgevalue in (index.get_edgevalues() or []):
                    self.response.out.write(
                        '      <edgevalue bucket="%s" numnodes="%s" />\n' %
                        (edgevalue[0], edgevalue[1]))
                self.response.out.write('    </edgevalues>\n')
                self.response.out.write('  </index>\n\n')

            self.response.out.write('</indexes>')

        if extension == 'csv':
            self.response.headers['Content-Type'] = "text/csv"
            self.response.out.write(
                'uid,name,updated_time,networkhash,value,nodebucket,nodevalue,edgebucket,edgevalue\n'
            )

            for index in q:
                if len((index.get_nodevalues() or [])) == 0 and len(
                    (index.get_edgevalues() or [])) == 0:
                    self.response.out.write(
                        '%s,%s,%s,%s,%s,%s,%s,%s,%s\n' %
                        (index.uid, index.name, index.updated_time,
                         index.networkhash, index.value, '', '', '', ''))
                for nodevalue in (index.get_nodevalues() or []):
                    self.response.out.write(
                        '%s,%s,%s,%s,%s,%s,%s,%s,%s\n' %
                        (index.uid, index.name, index.updated_time,
                         index.networkhash, index.value, nodevalue[0],
                         nodevalue[1], '', ''))
                for edgevalue in (index.get_edgevalues() or []):
                    self.response.out.write(
                        '%s,%s,%s,%s,%s,%s,%s,%s,%s\n' %
                        (index.uid, index.name, index.updated_time,
                         index.networkhash, index.value, '', '', edgevalue[0],
                         edgevalue[1]))

        if extension == 'xls':
            self.response.headers['Content-Type'] = "application/vnd.ms-excel"
            self.response.out.write(
                'uid\tname\tupdated_time\tnetworkhash\tvalue\tnodebucket\tnodevalue\tedgebucket\tedgevalue\r\n'
            )

            for index in q:
                if len((index.get_nodevalues() or [])) == 0 and len(
                    (index.get_edgevalues() or [])) == 0:
                    self.response.out.write(
                        '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' %
                        (index.uid, index.name, index.updated_time,
                         index.networkhash, index.value, '', '', '', ''))
                for nodevalue in (index.get_nodevalues() or []):
                    self.response.out.write(
                        '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' %
                        (index.uid, index.name, index.updated_time,
                         index.networkhash, index.value, nodevalue[0],
                         nodevalue[0], '', ''))
                for edgevalue in (index.get_edgevalues() or []):
                    self.response.out.write(
                        '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n' %
                        (index.uid, index.name, index.updated_time,
                         index.networkhash, index.value, '', '', edgevalue[0],
                         edgevalue[1]))
    else:
        self.response.out.write('Wrong format requested.')