예제 #1
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"))
예제 #2
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 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)))
예제 #5
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)))
예제 #6
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)))
예제 #7
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)))
예제 #8
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))
예제 #9
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 getsession(self, access_token=None, redirect_uri=None):
    session = get_current_session()

    #try:
    try:
        if not access_token:
            access_token = fbutils.fbapi_auth(self, self.request.get('code'),
                                              redirect_uri)[0]
        fbutils.fb_call('me', args={'access_token': access_token})
    except:
        session.terminate()
        return None

    try:
        if not session.is_active():
            conf.BASE_URL = fbutils.base_url(self)
            session.regenerate_id()
            session.start()
            logging.info("Created a new session " + str(session))

            me = fbutils.fb_call('me', args={'access_token': access_token})
            if 'error' in me: raise Exception(me['error'['message']])
            appid = fbutils.fb_call(conf.FBAPI_APP_ID,
                                    args={'access_token': access_token})
            if 'error' in appid: raise Exception(appid['error'['message']])
            app_token = fbutils.fbapi_get_application_access_token(
                self, redirect_uri)
            if 'error' in app_token:
                raise Exception(app_token['error'['message']])
            roles = fbutils.get_user_roles(app_token, me['id'])
            if 'error' in roles: raise Exception(roles['error'['message']])

            session['access_token'] = access_token
            session['me'] = me
            session['appid'] = appid
            session['app_token'] = app_token
            session['isdesktop'] = not bool(
                RE_MOBILE.search(get_user_agent(self.request)))

            session['roles'] = ['user']
            if 'administrators' in (roles or []) or 'insights' in (roles
                                                                   or []):
                session['roles'].append('administrator')
            if 'administrators' in (roles or []):
                session['roles'].append('technician')

            session.save()
    except:
        session.terminate()
        return None

    return session
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)))
예제 #12
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)))
예제 #14
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 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 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)
예제 #18
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')
 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))
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)
예제 #22
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)))
 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')
예제 #24
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>')
예제 #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'))
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)))
 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'))
예제 #29
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.')