def deleteProject(self): activeAuthToken = AuthModule.validateCookie() activeUserData = DivcoDataStore.getUserByLoginSession(activeAuthToken) rawData = flask.request.form projectID = int(rawData.get("projectID")) DivcoDataStore.clearProject(projectID) return jsonResponse({ "msg" : "projectDeleted" }, activeAuthToken)
def doSignup(self): rawData = flask.request.form name = rawData.get("name") email = rawData.get("email").lower() password = rawData.get("password") DivcoDataStore.createNewUser(name, email, password) activeUser = {"msg" : "user created"} return jsonResponse(activeUser)
def createNewProject(self): activeAuthToken = AuthModule.validateCookie() activeUserData = DivcoDataStore.getUserByLoginSession(activeAuthToken) rawData = flask.request.form name = rawData.get("name") pID = DivcoDataStore.createNewProject(activeUserData.key.id, name) return jsonResponse({ "msg" : "projectCreated", "debug" : pID }, activeAuthToken)
def getAllUserProject(self, userID): activeQuery = DSC.query(kind='projectMeta') activeQuery.add_filter('ownerUserList', '=', userID) userProjectList = activeQuery.fetch(limit=100) resultList = [] for item in userProjectList: itemPID = item["projectID"] newestItem = DivcoDataStore.getNewestEntryFromProjectHistory(itemPID) if newestItem != None: lastUpdate = str(datetime.datetime.fromtimestamp(newestItem["ts"] / 1000).strftime(r"%Y-%m-%d %H:%M:%S")) else: lastUpdate = "" exportItem = {} exportItem["projectID"] = itemPID exportItem["projectName"] = item["name"] exportItem["userRole"] = "Owner" exportItem["lastUpdated"] = lastUpdate exportItem["completion"] = "" resultList.append(exportItem) activeQuery = DSC.query(kind='projectMeta') activeQuery.add_filter('assoUserList', '=', userID) userProjectList = activeQuery.fetch(limit=100) for item in userProjectList: itemPID = item["projectID"] newestItem = DivcoDataStore.getNewestEntryFromProjectHistory(itemPID) if newestItem != None: lastUpdate = str(datetime.datetime.fromtimestamp(newestItem["ts"] / 1000).strftime(r"%Y-%m-%d %H:%M:%S")) else: lastUpdate = "" exportItem = {} exportItem["projectID"] = itemPID exportItem["projectName"] = item["name"] exportItem["userRole"] = "User" exportItem["lastUpdated"] = lastUpdate exportItem["completion"] = "" resultList.append(exportItem) return resultList
def getProjectList(self): activeAuthToken = AuthModule.validateCookie() activeUserData = DivcoDataStore.getUserByLoginSession(activeAuthToken) projectList = self.getAllUserProject(activeUserData.key.id) return jsonResponse(projectList, activeAuthToken)
def hackspace(): rawData = flask.request.form projectID = 11 updateJsonString = json.dumps({"tileIDList": [5], "layerID": 2}) entryType = "updateTile" returnMessage = DivcoDataStore.addToProjectHistory(projectID, entryType, updateJsonString) print(updateJsonString) response = {} response["result"] = returnMessage["status"] return jsonResponse(response) ## DO ONCE FOR SERVER SETUP # DivcoDataStore.initDivco() # CREATE NEW PROJECT # CLEAR AND RESET PROJECT # DivcoDataStore.initDivco() # doReset = True # if doReset: ## TEST FLOW # entryType = "createTile" # rawEntryArgs = r'{"label":"tile_1","parentID":null}' # DivcoDataStore.addToProjectHistory(pID, entryType, rawEntryArgs) # entryType = "createTile" # rawEntryArgs = r'{"label":"tile_2","parentID":1}' # DivcoDataStore.addToProjectHistory(pID, entryType, rawEntryArgs) # entryType = "updateTile" # rawEntryArgs = r'{"tileID":1,"label":"TILE_1","status":3}' # DivcoDataStore.addToProjectHistory(pID, entryType, rawEntryArgs) # entryType = "deleteTile" # rawEntryArgs = r'{"tileID":2}' # DivcoDataStore.addToProjectHistory(pID, entryType, rawEntryArgs) # entryType = "createTile" # rawEntryArgs = r'{"label":"tile_3","parentID":1}' # DivcoDataStore.addToProjectHistory(pID, entryType, rawEntryArgs) # entryType = "createTile" # rawEntryArgs = r'{"label":"tile_4","parentID":1}' # DivcoDataStore.addToProjectHistory(pID, entryType, rawEntryArgs) # entryType = "createTile" # rawEntryArgs = r'{"label":"tile_5","parentID":1}' # DivcoDataStore.addToProjectHistory(pID, entryType, rawEntryArgs) # entryType = "reorderTile" # rawEntryArgs = r'{"tileID":5,"order":1}' # DivcoDataStore.addToProjectHistory(pID, entryType, rawEntryArgs) response = {} return jsonResponse(response)
def getProjectUserList(pID): authToken = AuthModule.validateCookie() userList = DivcoDataStore.getProjectUserList(pID) response = {} response["data"] = userList return jsonResponse(response, authToken)
def jsonResponse(responseDict, authToken=None): response = flask.Response(json.dumps(responseDict, sort_keys=True), content_type="application/json") response.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' response.headers['Access-Control-Allow-Methods'] = 'POST, GET' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Request-Headers'] = 'Origin, Content-Type' response.headers['Vary'] = 'Origin' if authToken == "": response.set_cookie("DIVCO_AUTH_TOKEN", "", expires=0, samesite="Strict") elif authToken: expiration = datetime.datetime.now() + datetime.timedelta(days=2) DivcoDataStore.refreshLoginSession(authToken, expiration) response.set_cookie("DIVCO_AUTH_TOKEN", authToken, expires=expiration.timestamp(), samesite="Strict") return response
def createTile(): authToken = AuthModule.validateCookie() rawData = flask.request.form projectID = int(rawData.get("projectID")) updateJsonString = rawData.get("tileData") entryType = "createTile" returnMessage = DivcoDataStore.addToProjectHistory(projectID, entryType, updateJsonString) transTileChange = map(lambda node: DivcoDataStore.getTransFormat(node), returnMessage["tileChange"]) response = {} response["result"] = returnMessage["status"] response["dataChange"] = list(transTileChange) return jsonResponse(response, authToken)
def csvResponse(filename, csvData, authToken=None): response = flask.Response(csvData, content_type="text/csv; charset=utf-8") response.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' response.headers['Access-Control-Allow-Methods'] = 'POST, GET' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Request-Headers'] = 'Origin, Content-Type' response.headers['Content-Disposition'] = 'attachment; filename=' + filename response.headers['Vary'] = 'Origin' if authToken == "": response.set_cookie("DIVCO_AUTH_TOKEN", "", expires=0, samesite="Strict") elif authToken: expiration = datetime.datetime.now() + datetime.timedelta(hours=2) DivcoDataStore.refreshLoginSession(authToken, expiration) response.set_cookie("DIVCO_AUTH_TOKEN", authToken, expires=expiration.timestamp(), samesite="Strict") return response
def exportProject(pID): authToken = AuthModule.validateCookie() projectHistoryList = DivcoDataStore.getCompleteProjectHistory(pID) output = io.StringIO() writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC) writer.writerows(projectHistoryList) data = output.getvalue() return csvResponse("p" + str(pID) + ".csv", data, authToken)
def getData(): authToken = AuthModule.validateCookie() projectID = int(flask.request.args.get('projectID', '')) tileID = int(flask.request.args.get('tileID', '')) currentRoot = DivcoDataStore.getTileDataNode(projectID, tileID) divcoTileData = DivcoDataStore.getTileDataTree( projectID, tileID, currentRoot["stepCounter"] + 4) currentNode = DivcoDataStore.getTileDataNode(projectID, tileID) parentPath = currentNode["parentPath"] for pathTileID in parentPath: if pathTileID != tileID: pathNode = DivcoDataStore.getTileDataNode(projectID, pathTileID) divcoTileData.append(DivcoDataStore.getTransFormat(pathNode)) response = {} response["crumbPath"] = parentPath response["data"] = divcoTileData return jsonResponse(response, authToken)
def getUserData(self): authToken = AuthModule.validateCookie(True) if authToken != None: activeUserData = DivcoDataStore.getUserByLoginSession(authToken) if activeUserData: activeUser = {"userID": activeUserData.key.id, "userName" : activeUserData["name"]} else: activeUser = {} else: activeUser = {} return jsonResponse(activeUser, authToken)
def removeUserFromProject(pID): authToken = AuthModule.validateCookie() rawData = flask.request.form email = rawData.get("email") response = {} try: result = DivcoDataStore.removeUserFromProject(pID, email) response["result"] = result except ValueError as err: response["errorMsg"] = str(err) return jsonResponse(response, authToken)
def doLogin(self): rawData = flask.request.form email = rawData.get("email") password = rawData.get("password") activeUser = DivcoDataStore.getUserByCredentials(email.lower(), password) if activeUser == None: flask.abort(401) randomComponent = str(secrets.token_hex(16)) dateComponent = datetime.datetime.now() userComponent = str(activeUser) inputString = userComponent + randomComponent + str(dateComponent) sha256Generator = hashlib.sha256() sha256Generator.update(inputString.encode('utf-8')) authToken = sha256Generator.hexdigest() DivcoDataStore.createLoginSession(activeUser.get("userID"), authToken) return jsonResponse(activeUser, authToken)
def updateTile(): authToken = AuthModule.validateCookie() rawData = flask.request.form projectID = int(rawData.get("projectID")) updateJsonString = rawData.get("tileData") entryType = "updateTile" returnMessage = DivcoDataStore.addToProjectHistory(projectID, entryType, updateJsonString) response = {} response["result"] = returnMessage["status"] return jsonResponse(response, authToken)
def importProject(pID): authToken = AuthModule.validateCookie() DivcoDataStore.clearProject(pID) activeUserData = DivcoDataStore.getUserByLoginSession(authToken) DivcoDataStore.createNewProject(activeUserData.key.id, "Stub", pID) rawData = flask.request.form projectHistory = rawData.get("projectHistory") maxUsedTileID = 0 reader = csv.reader(io.StringIO(projectHistory)) next(reader) for i, row in enumerate(reader): entryType = row[1] entryArgs = row[2] entryTileID = json.loads(entryArgs).get("tileID") if entryTileID: maxUsedTileID = max(entryTileID, maxUsedTileID) if i % 20 == 0: print(i, entryType, entryArgs) DivcoDataStore.addToProjectHistory(pID, entryType, entryArgs) with DSC.transaction(): projectMetaItem = DSC.get(DSC.key('projectMeta', pID)) projectMetaItem.update({'tileCounter': maxUsedTileID}) DSC.put(projectMetaItem) response = {} response["debug"] = projectHistory return jsonResponse(response)
def doLogout(self): activeAuthToken = AuthModule.validateCookie(True) DivcoDataStore.clearLoginSession(activeAuthToken) return jsonResponse({"msg": "user logged out."}, authToken="")