def __activate__(self, context):

         try:
             self.log = context["log"]
             self.response = context["response"]
             self.request = context["request"]
             self.systemConfig = context["systemConfig"]
             self.storage = context["Services"].getStorage()
             self.indexer = context["Services"].getIndexer()
             self.sessionState = context["sessionState"]
             self.sessionState.set("username", "admin")

             out = self.response.getPrintWriter("text/plain; charset=UTF-8")
             relationshipMapper = ApplicationContextProvider.getApplicationContext().getBean("relationshipMapper")
             externalCurationMessageBuilder = ApplicationContextProvider.getApplicationContext().getBean("externalCurationMessageBuilder")

             oid = self.request.getParameter("oid")

             if oid is None :
                 identifier = self.request.getParameter("identifier")
                 oid = self.findOidByIdentifier(identifier)


             relationshipMap = relationshipMapper.getRelationshipMap(oid)
             relationshipMapJsonObject = externalCurationMessageBuilder.buildMessage(relationshipMap)
             out.println(relationshipMapJsonObject.toString(True))
             out.close()
         finally:
             self.sessionState.remove("username")
    def __activate__(self, context):
        self.None = context["log"]
        self.systemConfig = context["systemConfig"]
        self.sessionState = context["sessionState"]
        self.response = context["response"]
        self.request = context["request"]
        self.services = context["Services"]

        self.sessionState.set("username", "admin")
        self.writer = self.response.getPrintWriter("text/plain; charset=UTF-8")

        curationJobDao = ApplicationContextProvider.getApplicationContext().getBean("curationJobDao")
        publicationHandler = ApplicationContextProvider.getApplicationContext().getBean("publicationHandler")
        jobs = JsonSimple(File(FascinatorHome.getPath() + "/curation-status-responses/inProgressJobs.json")).getArray("inProgressJobs")
        self.writer.println(jobs.size())


        for curationJob in jobs:
            curationJob
            jobStatus = self.queryJobStatus(curationJob)
            self.writer.println(jobStatus.toString())
            status = jobStatus.getString("failed", "status")
            self.writeResponseToStatusResponseCache(jobStatus.getInteger(None, "job_id"), jobStatus)
            self.writer.println(status)
            if "complete" == status:
                publicationHandler.publishRecords(jobStatus.getArray("job_items"))
                self.updateLocalRecordRelations(jobStatus.getArray("job_items"))
           
            self.writer.close()
            self.sessionState.remove("username")
예제 #3
0
    def __activate__(self, context):

         try:
             self.log = context["log"]
             self.response = context["response"]
             self.request = context["request"]
             self.systemConfig = context["systemConfig"]
             self.storage = context["Services"].getStorage()
             self.indexer = context["Services"].getIndexer()
             self.sessionState = context["sessionState"]
             self.sessionState.set("username", "admin")

             out = self.response.getPrintWriter("text/plain; charset=UTF-8")
             relationshipMapper = ApplicationContextProvider.getApplicationContext().getBean("relationshipMapper")
             externalCurationMessageBuilder = ApplicationContextProvider.getApplicationContext().getBean("externalCurationMessageBuilder")

             oid = self.request.getParameter("oid")

             if oid is None :
                 identifier = self.request.getParameter("identifier")
                 oid = self.findOidByIdentifier(identifier)

             relationshipType = self.request.getParameter("relationship")
             curatedPid = self.request.getParameter("curatedPid")
             sourceId = self.request.getParameter("sourceIdentifier")

             digitalObject = StorageUtils.getDigitalObject(self.storage, oid)

             metadataJson = self.getTfPackage(digitalObject)


             relationships = metadataJson.getArray("relationships")
             found = False
             for relationship in relationships:
                 if relationship.get("identifier") == sourceId:
                     relationship.put("isCurated",True)
                     relationship.put("curatedPid",curatedPid)
                     found = True

             if not found:
                 relationship = JsonObject()
                 relationship.put("isCurated",True)
                 relationship.put("curatedPid",curatedPid)
                 relationship.put("relationship",relationshipType)
                 relationship.put("identifier",sourceId)
                 relationships.add(relationship)

             self.log.info(metadataJson.toString(True))
             out.println(metadataJson.toString(True))
             istream = ByteArrayInputStream(String(metadataJson.toString(True)).getBytes())

             for pid in digitalObject.getPayloadIdList():

                 if pid.endswith(".tfpackage"):
                     StorageUtils.createOrUpdatePayload(digitalObject,pid,istream)


             out.close()
         finally:
             self.sessionState.remove("username")
예제 #4
0
    def __activate__(self, context):

        try:
            self.log = context["log"]
            self.response = context["response"]
            self.request = context["request"]
            self.systemConfig = context["systemConfig"]
            self.storage = context["Services"].getStorage()
            self.indexer = context["Services"].getIndexer()
            self.sessionState = context["sessionState"]
            self.sessionState.set("username", "admin")

            out = self.response.getPrintWriter("text/plain; charset=UTF-8")
            relationshipMapper = ApplicationContextProvider.getApplicationContext(
            ).getBean("relationshipMapper")
            externalCurationMessageBuilder = ApplicationContextProvider.getApplicationContext(
            ).getBean("externalCurationMessageBuilder")

            builder = StringBuilder()
            aux = ""
            reader = self.httpRequest.getReader()
            aux = reader.readLine()
            while aux is not None:
                builder.append(aux)
                aux = reader.readLine()

            requestJsonString = builder.toString()

            requestJson = JsonSimple(requestJsonString)

            #              out.println(relationshipMapJsonObject.toString(True))
            out.close()
        finally:
            self.sessionState.remove("username")
    def __activate__(self, context):
         
         try:
             self.log = context["log"]
             self.response = context["response"]
             self.request = context["request"]
             self.systemConfig = context["systemConfig"]
             self.storage = context["Services"].getStorage()
             self.indexer = context["Services"].getIndexer()
             self.sessionState = context["sessionState"]
             self.sessionState.set("username", "admin")
        
             out = self.response.getPrintWriter("text/plain; charset=UTF-8")
             relationshipMapper = ApplicationContextProvider.getApplicationContext().getBean("relationshipMapper")
             externalCurationMessageBuilder = ApplicationContextProvider.getApplicationContext().getBean("externalCurationMessageBuilder")
         
             builder = StringBuilder()
             aux = ""
             reader = self.httpRequest.getReader()
             aux = reader.readLine()
             while aux is not None:
                 builder.append(aux)
                 aux =reader.readLine()

             requestJsonString = builder.toString()
             
             requestJson = JsonSimple(requestJsonString)
             
             
             
             
#              out.println(relationshipMapJsonObject.toString(True))         
             out.close()
         finally:
             self.sessionState.remove("username")
    def __activate__(self, context):

        try:
            self.log = context["log"]
            self.response = context["response"]
            self.request = context["request"]
            self.systemConfig = context["systemConfig"]
            self.storage = context["Services"].getStorage()
            self.indexer = context["Services"].getIndexer()
            self.sessionState = context["sessionState"]
            self.sessionState.set("username", "admin")

            out = self.response.getPrintWriter("text/plain; charset=UTF-8")
            relationshipMapper = ApplicationContextProvider.getApplicationContext(
            ).getBean("relationshipMapper")
            externalCurationMessageBuilder = ApplicationContextProvider.getApplicationContext(
            ).getBean("externalCurationMessageBuilder")

            oid = self.request.getParameter("oid")

            if oid is None:
                identifier = self.request.getParameter("identifier")
                oid = self.findOidByIdentifier(identifier)

            relationshipMap = relationshipMapper.getRelationshipMap(oid)
            relationshipMapJsonObject = externalCurationMessageBuilder.buildMessage(
                relationshipMap)
            out.println(relationshipMapJsonObject.toString(True))
            out.close()
        finally:
            self.sessionState.remove("username")
예제 #7
0
 def getViewers(self, oid, owner):
     accessControl = ApplicationContextProvider.getApplicationContext(
     ).getBean("fascinatorAccess")
     users = accessControl.getUsers(oid)
     if users.contains(owner):
         users.remove(owner)
     return users
예제 #8
0
파일: userinfo.py 프로젝트: qcif/rdsi-arms
    def __constructInfoJson(self, username):
        """
            There are users managed by internal auth manager with no attributes
            There are users managed by external auth managers e.g. shibboleth who have attributes
            We put all available attributes of a user in to return value 
        """
        # print "Query username = %s" % username
        username = username.strip()

        authUserDao = ApplicationContextProvider.getApplicationContext().getBean("hibernateAuthUserDao")
        parameters = HashMap()
        parameters.put("username", username)
        userObjectList = authUserDao.query("getUser", parameters)

        # print "Returned object = %s" % str(userObjectList)
        # print "Returned size = %d" % userObjectList.size() 
        userJson = JsonObject()
        try:
            if userObjectList.size() > 0:
                # One hit will be enough to get user object
                userObj = userObjectList.get(0)
                attrbs = userObj.getAttributes()
                for attrb in attrbs.keySet():
#                     print "Attribute %s = %s) % (attrb, attrbs.get(attrb).getValStr())
                    userJson.put(attrb, attrbs.get(attrb).getValStr())
            else:
               # This should not be reached with external sourced users
                self.log.warn("Wrong username? Every user should have a record")
                userJson.put("userName", username) 
        except Exception, e:
            self.log.error("%s: cannot construct user attribute JSON, detail = %s" % (self.__class__.__name__ , str(e)))
            userJson.put("userName", username)
    def __getUserInfo(self, username):
        """
            Query HibernateUser to get a user information
            There are users managed by internal auth manager with no attributes other than password
            There are users managed by external auth managers e.g. shibboleth who have attributes
            Each user, at the time of writing: 20140904, each user has multiple identical attribute sets,
            so, only the first one is used
            We put all available attributes of a user in to return value 
        """
        username = username.strip()

        authUserDao = ApplicationContextProvider.getApplicationContext().getBean("hibernateAuthUserDao")
        parameters = HashMap()
        parameters.put("username", username)
        userObjectList = authUserDao.query("getUser", parameters)

        userJson = JsonObject()
        userJson.put("username", username) 
        try:
            if userObjectList.size() > 0:
                # One hit will be enough to get user object
                userJson = self.__constructUserAttribs(userObjectList.get(0), self.ATTRIB_FILTER)
            else:
               # This should not be reached with external sourced users
                self.log.warn("Wrong username or internal user is queried")
        except Exception, e:
            self.log.error("%s: cannot construct user attribute JSON, detail = %s" % (self.__class__.__name__ , str(e)))
예제 #10
0
    def __getUserInfo(self, username):
        """
            Query HibernateUser to get a user information
            There are users managed by internal auth manager with no attributes other than password
            There are users managed by external auth managers e.g. shibboleth who have attributes
            Each user, at the time of writing: 20140904, each user has multiple identical attribute sets,
            so, only the first one is used
            We put all available attributes of a user in to return value 
        """
        username = username.strip()

        authUserDao = ApplicationContextProvider.getApplicationContext(
        ).getBean("hibernateAuthUserDao")
        parameters = HashMap()
        parameters.put("username", username)
        userObjectList = authUserDao.query("getUser", parameters)

        userJson = JsonObject()
        userJson.put("username", username)
        try:
            if userObjectList.size() > 0:
                # One hit will be enough to get user object
                userJson = self.__constructUserAttribs(userObjectList.get(0),
                                                       self.ATTRIB_FILTER)
            else:
                # This should not be reached with external sourced users
                self.log.warn("Wrong username or internal user is queried")
        except Exception, e:
            self.log.error(
                "%s: cannot construct user attribute JSON, detail = %s" %
                (self.__class__.__name__, str(e)))
 def __activate__(self, context):
     self.velocityContext = context
     self.response = self.velocityContext["response"]
     self.maintenanceModeService = ApplicationContextProvider.getApplicationContext(
     ).getBean("maintenanceModeService")
     if self.maintenanceModeService.isMaintanceMode() == False:
         self.response.sendRedirect(self.velocityContext["portalPath"] +
                                    "/home")
예제 #12
0
    def __createNew(self):
        self.vc("log").debug("Creating a new package...")
        packageType, jsonConfigFile = self.__getPackageTypeAndJsonConfigFile()
        self.vc("log").debug("packageType = '{}'", packageType)
        self.vc("log").debug("jsonConfigFile = '{}'", jsonConfigFile)

        manifestHash = "%s.tfpackage" % uuid.uuid4()
        # store the manifest file for harvesting
        packageDir = FascinatorHome.getPathFile("packages")
        packageDir.mkdirs()
        manifestFile = File(packageDir, manifestHash)
        outStream = FileOutputStream(manifestFile)
        outWriter = OutputStreamWriter(outStream, "UTF-8")

        self.vc("sessionState").set("package/active", None)
        manifest = self.__getActiveManifest()
        manifest.setType(packageType)
        metaList = list(self.vc("formData").getValues("metaList"))
        jsonObj = manifest.getJsonObject()
        for metaName in metaList:
            value = self.vc("formData").get(metaName)
            jsonObj.put(metaName, value)
        if self.vc("formData").getValues("sequencesMetaList") != None:    
            sequenceService = ApplicationContextProvider.getApplicationContext().getBean("sequenceService")
            sequencesMetaList = list(self.vc("formData").getValues("sequencesMetaList"))
            for sequenceInfo in sequencesMetaList:   
                sequenceInfoJson = JsonSimple(sequenceInfo)
                sequenceIndex = sequenceService.getSequence(sequenceInfoJson.getString(None,"sequenceName"))
                jsonObj.put(sequenceInfoJson.getString(None,"metadataName"), String.format(sequenceInfoJson.getString(None,"stringFormat"),sequenceIndex))
        self.vc("log").debug("json object created is: %r" % jsonObj)
        outWriter.write(manifest.toString(True))
        outWriter.close()
        # adding ability to set access plugin
        accessPlugin = self.vc("formData").get("access_plugin", "derby")
        if accessPlugin is not None:
            self.vc("page").authentication.set_access_plugin(accessPlugin)
        try:
            # harvest the package as an object
            username = self.vc("sessionState").get("username")
            if username is None:
                username = "******" # necessary?
            harvester = None
            # set up config files, creating if necessary
            workflowsDir = FascinatorHome.getPathFile("harvest/workflows")
            configFile = self.__getFile(workflowsDir, jsonConfigFile)
            self.__getFile(workflowsDir, "packaging-rules.py")
            # run the harvest client with our packaging workflow config
            harvester = HarvestClient(configFile, manifestFile, username)
            harvester.start()
            manifestId = harvester.getUploadOid()
            harvester.shutdown()
        except Exception, ex:
            error = "Packager workflow failed: %s" % str(ex)
            self.vc("log").error(error, ex)
            if harvester is not None:
                harvester.shutdown()
            return '{ "status": "failed" }'
예제 #13
0
    def __activate__(self, context):
        self.None = context["log"]
        self.systemConfig = context["systemConfig"]
        self.sessionState = context["sessionState"]
        self.response = context["response"]
        self.request = context["request"]

        self.sessionState.set("username", "admin")
        self.writer = self.response.getPrintWriter("text/plain; charset=UTF-8")

        curationJobDao = ApplicationContextProvider.getApplicationContext(
        ).getBean("curationJobDao")
        publicationHandler = ApplicationContextProvider.getApplicationContext(
        ).getBean("publicationHandler")
        jobs = curationJobDao.query("findInProgressJobs", HashMap())
        self.writer.println(jobs.size())

        for curationJob in jobs:
            if curationJob.getCurationJobId() is not None:
                self.writer.println(curationJob.getCurationJobId())
            else:
                self.writer.println("Null huh")

            jobStatus = self.queryJobStatus(curationJob)
            self.writer.println(jobStatus.toString())
            status = jobStatus.getString("failed", "status")
            self.writeResponseToStatusResponseCache(
                jobStatus.getInteger(None, "job_id"), jobStatus)
            self.writer.println(status)
            if "complete" == status:
                publicationHandler.publishRecords(
                    jobStatus.getArray("job_items"))
                curationJob.setStatus(status)
                curationJobDao.create(curationJob)
            else:
                if "failed" == status:
                    curationJob.setStatus(status)
                    curationJobDao.create(curationJob)
            self.writer.close()
            self.sessionState.remove("username")
예제 #14
0
 def listUserAttributes(self):
     """ Query HibernateUserAttribute to get the stored user attributes supported by current authentication manager 
         Return a JSONArray: can be empty if only internal manager is used
     """
     authUserAttrbDao = ApplicationContextProvider.getApplicationContext().getBean("hibernateAuthUserAttributeDao")
     attributeList = authUserAttrbDao.query("getUserAttributeList",HashMap())
     
     aList = JSONArray()
     if attributeList.size() > 0:
         filtered = [attribName for attribName in attributeList if attribName not in self.ATTRIB_FILTER]
         for a in filtered:
             aList.add(a)
     return aList
예제 #15
0
    def __activate__(self, context):
        self.None = context["log"]
        self.systemConfig = context["systemConfig"]
        self.sessionState = context["sessionState"]
        self.response = context["response"]
        self.request = context["request"]

        self.sessionState.set("username","admin")
        self.writer = self.response.getPrintWriter("text/plain; charset=UTF-8")

        curationJobDao = ApplicationContextProvider.getApplicationContext().getBean("curationJobDao")
        publicationHandler = ApplicationContextProvider.getApplicationContext().getBean("publicationHandler");
        jobs = curationJobDao.query("findInProgressJobs", HashMap())
        self.writer.println(jobs.size())


        for curationJob in jobs:
            if curationJob.getCurationJobId() is not None:
                self.writer.println(curationJob.getCurationJobId())
            else:
                self.writer.println("Null huh")

            jobStatus = self.queryJobStatus(curationJob)
            self.writer.println(jobStatus.toString())
            status = jobStatus.getString("failed", "status")
            self.writeResponseToStatusResponseCache(jobStatus.getInteger(None, "job_id"), jobStatus)
            self.writer.println(status)
            if "complete" == status:
                publicationHandler.publishRecords(jobStatus.getArray("job_items"))
                curationJob.setStatus(status)
                curationJobDao.create(curationJob)
            else:
                if "failed" == status:
                    curationJob.setStatus(status)
                    curationJobDao.create(curationJob)
            self.writer.close()
            self.sessionState.remove("username")
예제 #16
0
    def __activate__(self, context):
        self.velocityContext = context
        self.formData = self.velocityContext["formData"]
        self.request = self.velocityContext["request"]
        self.apiKeyService = ApplicationContextProvider.getApplicationContext().getBean("apiKeyTokenService")
        self.systemConfig = JsonSimpleConfig()
        self.log = self.velocityContext["log"]

        if self.request.getMethod() == "POST":
            if self.formData.get("action") == "Add":
                self.add_key()
            if self.formData.get("action") == "Remove":
                self.remove_key()
            if self.formData.get("action") == "Regenerate":
                self.regenerate_key()
        self.json = JsonSimple()
예제 #17
0
    def listUserAttributes(self):
        """ Query HibernateUserAttribute to get the stored user attributes supported by current authentication manager 
            Return a JSONArray: can be empty if only internal manager is used
        """
        authUserAttrbDao = ApplicationContextProvider.getApplicationContext(
        ).getBean("hibernateAuthUserAttributeDao")
        attributeList = authUserAttrbDao.query("getUserAttributeList",
                                               HashMap())

        aList = JSONArray()
        if attributeList.size() > 0:
            filtered = [
                attribName for attribName in attributeList
                if attribName not in self.ATTRIB_FILTER
            ]
            for a in filtered:
                aList.add(a)
        return aList
예제 #18
0
 def __activate__(self, context):
     self.log = context["log"]
     self.services = context["Services"]
     formData = context["formData"]
     oid = formData.get("oid")
     action = formData.get("action")
     self.authUserDao = ApplicationContextProvider.getApplicationContext().getBean("hibernateAuthUserDao")
     self.log.debug("grantAccess.py: Action = " + action)
     if action == 'get':
         result = self.__getUsers(oid)
     elif action == "getUserName":
         result = self.getUserName(formData.get("user"))
     elif action == "change":
         result = self.__change(context, oid, formData.get("new_owner"))
     else:
         result = '{"status":"bad request"}'
     
     self.__respond(context["response"], result)    
예제 #19
0
    def getUserName(self, userStr):
        """ userStr could be an identifier of a user, e.g. an email address not a username, 
            this function currently only verifies it against email address attribute stored in HibernateAuthUserAttribute table
            and return a real username if found, otherwise, return original query string
            Warning: this function does not check if a user exists
        """
        parameters = HashMap()
#         print "Checking user info by %s (could be email)" % userStr
        parameters.put("key", "email")
        parameters.put("value", userStr)
        authUserAttrbDao = ApplicationContextProvider.getApplicationContext().getBean("hibernateAuthUserAttributeDao")
        userObjectList = authUserAttrbDao.query("getUserAttributeByKeyAndValue", parameters)
        if userObjectList.size() > 0:
            userObject = userObjectList.get(0) #Check if this is a user with attributes?
            realUser = userObject.getUser()
            if realUser is not None:
                userStr = realUser.getUsername()
        return '{"realName":"' + userStr + '"}'
예제 #20
0
    def getUsers(self, k, v):
        """ Query HibernateUserAttribute with supported key:value pair against supported attributes 
            when query against username, it returns a JSON object as there could be only one user. 
            Otherwise returns a JSONArray of JSON which contains user's attributes but can be empty
        """
        if k == "username":
            return self.__getUserInfo(v)
        
        users = JSONArray()
        parameters = HashMap()

        parameters.put("key", k)
        parameters.put("value", v)
        authUserAttrbDao = ApplicationContextProvider.getApplicationContext().getBean("hibernateAuthUserAttributeDao")
        userObjectList = authUserAttrbDao.query("getUserAttributeByKeyAndValueDistinct", parameters)
        if userObjectList.size() > 0:
            for userObj in userObjectList:
                users.add(self.__constructUserAttribs(userObj[0], self.ATTRIB_FILTER))
        return users
예제 #21
0
    def __activate__(self, context):
        self.log = context["log"]
        self.services = context["Services"]
        formData = context["formData"]
        oid = formData.get("oid")
        action = formData.get("action")
        self.authUserDao = ApplicationContextProvider.getApplicationContext(
        ).getBean("hibernateAuthUserDao")
        self.log.debug("grantAccess.py: Action = " + action)
        if action == 'get':
            result = self.__getUsers(oid)
        elif action == "getUserName":
            result = self.getUserName(formData.get("user"))
        elif action == "change":
            result = self.__change(context, oid, formData.get("new_owner"))
        else:
            result = '{"status":"bad request"}'

        self.__respond(context["response"], result)
예제 #22
0
 def getUserName(self, userStr):
     """ userStr could be an identifier of a user, e.g. an email address not a username, 
         this function currently only verifies it against email address attribute stored in HibernateAuthUserAttribute table
         and return a real username if found, otherwise, return original query string
         Warning: this function does not check if a user exists
     """
     parameters = HashMap()
     #         print "Checking user info by %s (could be email)" % userStr
     parameters.put("key", "email")
     parameters.put("value", userStr)
     authUserAttrbDao = ApplicationContextProvider.getApplicationContext(
     ).getBean("hibernateAuthUserAttributeDao")
     userObjectList = authUserAttrbDao.query(
         "getUserAttributeByKeyAndValue", parameters)
     if userObjectList.size() > 0:
         userObject = userObjectList.get(
             0)  #Check if this is a user with attributes?
         realUser = userObject.getUser()
         if realUser is not None:
             userStr = realUser.getUsername()
     return '{"realName":"' + userStr + '"}'
예제 #23
0
    def getUsers(self, k, v):
        """ Query HibernateUserAttribute with supported key:value pair against supported attributes 
            when query against username, it returns a JSON object as there could be only one user. 
            Otherwise returns a JSONArray of JSON which contains user's attributes but can be empty
        """
        if k == "username":
            return self.__getUserInfo(v)

        users = JSONArray()
        parameters = HashMap()

        parameters.put("key", k)
        parameters.put("value", v)
        authUserAttrbDao = ApplicationContextProvider.getApplicationContext(
        ).getBean("hibernateAuthUserAttributeDao")
        userObjectList = authUserAttrbDao.query(
            "getUserAttributeByKeyAndValueDistinct", parameters)
        if userObjectList.size() > 0:
            for userObj in userObjectList:
                users.add(
                    self.__constructUserAttribs(userObj[0],
                                                self.ATTRIB_FILTER))
        return users
예제 #24
0
 def getViewers(self, oid, owner):
     accessControl = ApplicationContextProvider.getApplicationContext().getBean("fascinatorAccess")
     users = accessControl.getUsers(oid)
     if users.contains(owner):
        users.remove(owner)
     return users
 def __activate__(self, context):
     self.velocityContext = context
     self.log = self.vc("log")
     self.systemConfig = self.vc("systemConfig")        
     self.formData = context["formData"]
     self.assertionText = self.formData.get("assertion")
     self.session = self.vc("sessionState")
     self.response = self.vc("response")
     self.request = self.vc("request")
     method = self.request.getMethod()
     
     #checking access method
     if method != "POST":
         self.log.error("Page not accessed by a POST, method:%s" % method)
         return
     
     self.sharedKey = String(self.systemConfig.getString("", "rapidAafSso", "sharedKey"))
     self.aud = self.systemConfig.getString("", "rapidAafSso", "aud")
     self.iss = self.systemConfig.getString("", "rapidAafSso", "iss")
     
     #checking signature
     jwsObject = JWSObject.parse(self.assertionText)        
     verifier = MACVerifier(self.sharedKey.getBytes())                        
     verifiedSignature = jwsObject.verify(verifier)
     
     if (verifiedSignature):
         self.log.debug("Verified JWS signature!")
     else:            
         self.log.error("Invalid JWS signature!")                                    
         return
     
     self.log.debug(jwsObject.getPayload().toString())
     self.log.debug(self.session.toString())
         
     json = JsonSimple(jwsObject.getPayload().toString())
     aud = json.getString("", "aud")
     iss = json.getString("", "iss")
     nbf = json.getInteger(None, "nbf")
     exp = json.getInteger(None, "exp")
     jti = json.getString("", "jti")
       
     #checking aud
     if self.aud != aud:
         self.log.error("Invalid aud: '%s' expecting: '%s'" % (aud, self.aud))
         return  
     
     #checking iss
     if self.iss != iss:
         self.log.error("Invalid iss: '%s' expecting: '%s'" % (iss, self.iss))
         return
     
     #checking times
     now = Date().getTime() / 1000
     if now < nbf or now > exp:
         self.log.error("Invalid timings.")
         return
     
     #checking jti
     attributeDao = ApplicationContextProvider.getApplicationContext().getBean("hibernateAuthUserAttributeDao")
     params = HashMap()
     params.put("key", "jti")
     params.put("value", jti)
     attrList = attributeDao.query("getUserAttributeByKeyAndValue", params)
     if attrList.size() > 0:
         self.log.error("Possible replay attack, jti:'%s' found in DB." % jti)
         return        
     
     self.session.put("jwt", jwsObject.getPayload().toString())
     self.session.put("jwt_json", json)
     self.session.put("jwt_assertion", self.assertionText)
     self.session.put("jwt_exp", exp)        
     self.returnAddress = self.session.get("returnAddress")
     if self.returnAddress is None:
         self.log.debug("No return address, using portalPath.")
         self.returnAddress = self.vc("portalPath")
     self.log.debug("RapidAAF SSO login complete, redirect to: %s" % self.returnAddress)                        
     self.response.sendRedirect(self.returnAddress)            
예제 #26
0
    def __createNew(self):
        self.vc("log").debug("Creating a new package...")
        packageType, jsonConfigFile = self.__getPackageTypeAndJsonConfigFile()
        self.vc("log").debug("packageType = '{}'", packageType)
        self.vc("log").debug("jsonConfigFile = '{}'", jsonConfigFile)

        manifestHash = "%s.tfpackage" % uuid.uuid4()
        # store the manifest file for harvesting
        packageDir = FascinatorHome.getPathFile("packages")
        packageDir.mkdirs()
        manifestFile = File(packageDir, manifestHash)
        outStream = FileOutputStream(manifestFile)
        outWriter = OutputStreamWriter(outStream, "UTF-8")

        self.vc("sessionState").set("package/active", None)
        manifest = self.__getActiveManifest()
        manifest.setType(packageType)
        metaList = list(self.vc("formData").getValues("metaList"))
        jsonObj = manifest.getJsonObject()
        for metaName in metaList:
            value = self.vc("formData").get(metaName)
            jsonObj.put(metaName, value)
        if self.vc("formData").getValues("sequencesMetaList") != None:
            sequenceService = ApplicationContextProvider.getApplicationContext(
            ).getBean("sequenceService")
            sequencesMetaList = list(
                self.vc("formData").getValues("sequencesMetaList"))
            for sequenceInfo in sequencesMetaList:
                sequenceInfoJson = JsonSimple(sequenceInfo)
                sequenceIndex = sequenceService.getSequence(
                    sequenceInfoJson.getString(None, "sequenceName"))
                jsonObj.put(
                    sequenceInfoJson.getString(None, "metadataName"),
                    String.format(
                        sequenceInfoJson.getString(None, "stringFormat"),
                        sequenceIndex))
        self.vc("log").debug("json object created is: %r" % jsonObj)
        outWriter.write(manifest.toString(True))
        outWriter.close()
        # adding ability to set access plugin
        accessPlugin = self.vc("formData").get("access_plugin", "derby")
        if accessPlugin is not None:
            self.vc("page").authentication.set_access_plugin(accessPlugin)
        try:
            # harvest the package as an object
            username = self.vc("sessionState").get("username")
            if username is None:
                username = "******"  # necessary?
            harvester = None
            # set up config files, creating if necessary
            workflowsDir = FascinatorHome.getPathFile("harvest/workflows")
            configFile = self.__getFile(workflowsDir, jsonConfigFile)
            self.__getFile(workflowsDir, "packaging-rules.py")
            # run the harvest client with our packaging workflow config
            harvester = HarvestClient(configFile, manifestFile, username)
            harvester.start()
            manifestId = harvester.getUploadOid()
            harvester.shutdown()
        except Exception, ex:
            error = "Packager workflow failed: %s" % str(ex)
            self.vc("log").error(error, ex)
            if harvester is not None:
                harvester.shutdown()
            return '{ "status": "failed" }'