async def get_steam_sharing_games(self, owngames: List[str]) -> List[Game]: profiles = list(filter(lambda x: "#" in x.user_name, self._own_friends)) logger.info(profiles) newgames: List[Game] = [] self._family_sharing_games = [] for i in profiles: othergames = await self._client.get_games(i.user_id) try: for game in othergames: hasit = any(f == str(game["appid"]) for f in owngames) or any( f.game_id == str(game["appid"]) for f in newgames) if not hasit: self._family_sharing_games.append(str(game["appid"])) newgame = Game( str(game["appid"]), game["name"], [], LicenseInfo(LicenseType.OtherUserLicense, i.user_name)) newgames.append(newgame) except (KeyError, ValueError): logger.exception("Can not parse backend response") raise UnknownBackendResponse() return newgames
def add_new_content(): # if session.get("name") is None: # abort(400) list_form_data = json.loads(request.get_data().decode("utf-8")) for form_data in list_form_data: form_data["site_name"] = form_data["site_name"].replace("\n", "") form_data["serial_number"] = form_data["serial_number"].replace( "\n", "") form_data["url"] = form_data["url"].replace("\n", "") form_data["remark"] = form_data["remark"].replace("\n", "") form_data["site_name"] = form_data["site_name"].replace("\t", "") form_data["serial_number"] = form_data["serial_number"].replace( "\t", "") form_data["url"] = form_data["url"].replace("\t", "") form_data["remark"] = form_data["remark"].replace("\t", "") # form_data["site_name"] = form_data["site_name"].replace(" ", "") form_data["serial_number"] = form_data["serial_number"].replace( " ", "") form_data["url"] = form_data["url"].replace(" ", "") ret = create_new_item(list_form_data) if ret == 1: logger.info("User " + session.get("name") + " add new items") return jsonify({ "status": 200, "message": "success", "url": "/setting" }) else: return jsonify({"status": 400, "message": ret})
def list_item(): # if session.get("token") is None: # return redirect("/login") if session.get("name") is None or session.get("department") is None: ret = query_user_info(rc4_decrypt(session.get("token"), rc4_key)) if ret == 2: return "The account doesn't exist" elif ret == 3: return "The account was blocked" else: session["name"] = ret[0] session["department"] = ret[1] if request.args.get("token") is not None: return redirect("setting") current_user = session.get("name") current_department = session.get("department") current_time = datetime.date.today().isoformat() get_item_list = query_data() logger.info("User " + current_user + " loads the item list of " + current_time) return render_template("/configuration.html", current_time=current_time, item_list=get_item_list, current_user=current_user, current_department=current_department)
def main(): """The main entrypoint for the plugin.""" try: api_token = dronecli.get('API_TOKEN') account_id = dronecli.get('PLUGIN_ACCOUNT_ID') esg_name = dronecli.get('PLUGIN_ESG_NAME') adjustment_type = dronecli.get('PLUGIN_ADJUSTMENT_TYPE', default='count') adjustment = dronecli.get('PLUGIN_ADJUSTMENT', default=1) plugin = SpotinstEsgScaler( api_token=api_token, account_id=account_id, esg_name=esg_name, adjustment_type=adjustment_type, adjustment=adjustment ) logger.info("The drone plugin has been initialized with: {}".format(plugin)) plugin.setup() except Exception as e: logger.error("Error while executing the plugin: {}".format(e)) raise e sys.exit(1)
def _preprocess(self, endpoint, options): """Prepare a query with common arguments.""" query = self._api_root query += endpoint query += "?accountId={}".format(self._account_id) query += ''.join({"&{}={}".format(k, v) for (k, v) in options.items()}) logger.info("Query path built: {}".format(query)) return query
def del_item(): # if session.get("name") is None: # abort(400) form_data = json.loads(request.get_data().decode("utf-8")) ret = delete_item(form_data) if ret == 1: logger.info("User " + session.get("name") + " delete items") return jsonify({"status": 200, "message": "success"}) else: return jsonify({"status": 400, "message": ret})
def setup(self): """Main plugin logic.""" self._compute_size() esg_adjust_req = self.request( method='put', url=self._preprocess(endpoint="/aws/ec2/group/{}/scale/up".format(self._esg_id), options=dict(adjustment=self._adjustment)) ) logger.info("Scale up request successful! {}".format(esg_adjust_req['items'][0]))
def login(): try: credential = Wavve.do_login(ModelSetting.get('id'), ModelSetting.get('pw')) logger.info('Wavve Credential : %s', credential) if credential is None: return False db.session.query(ModelSetting).filter_by( key='credential').with_for_update().first().value = credential db.session.commit() return True except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc())
def login(force=False): try: if ModelSetting.get('credential') == '' or force: credential = Wavve.do_login(ModelSetting.get('id'), ModelSetting.get('pw')) logger.info('Wavve Credential : %s', credential) if credential is None: return False ModelSetting.set('credential', credential) db.session.commit() else: pass return True except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc())
def modify(): # if session.get("name") is None: # abort(400) form_data = json.loads(request.get_data().decode("utf-8")) form_data["site_name"] = form_data["site_name"].replace("\n", "") form_data["serial_number"] = form_data["serial_number"].replace("\n", "") form_data["url"] = form_data["url"].replace("\n", "") form_data["remark"] = form_data["remark"].replace("\n", "") form_data["site_name"] = form_data["site_name"].replace("\t", "") form_data["serial_number"] = form_data["serial_number"].replace("\t", "") form_data["url"] = form_data["url"].replace("\t", "") form_data["remark"] = form_data["remark"].replace("\t", "") # form_data["site_name"] = form_data["site_name"].replace(" ", "") form_data["serial_number"] = form_data["serial_number"].replace(" ", "") form_data["url"] = form_data["url"].replace(" ", "") ret = modify_content(form_data) if ret == 1: logger.info("User " + session.get("name") + " submit modified items") return jsonify({"status": 200, "message": "success"}) else: return jsonify({"status": 400, "message": ret})
def _compute_size(self): """Compute the new size of the ESG based on the adjustment type and adjustment chosen.""" if self._adjustment_type == 'count': logger.info("Adding instances to the ESG {} ({}) from {} -> {}".format( self._esg_name, self._esg_id, self._esg_capacity['target'], self._esg_capacity['target'] + self._adjustment)) elif self._adjustment_type == 'double': self._adjustment = self._esg_capacity['target'] * 2 logger.info("Doubling the size of the ESG {} ({}) from {} -> {}".format( self._esg_name, self._esg_id, self._esg_capacity['target'], self._adjustment)) elif self._adjustment_type == 'half': self._adjustment = int(round(self._esg_capacity['target'] / 2)) + self._esg_capacity['target'] logger.info("Adding half the size of the ESG {} ({}) from {} -> {}".format( self._esg_name, self._esg_id, self._esg_capacity['target'], self._adjustment)) else: raise Exception("Adjustment type unkown, please use one of ['count', 'double', 'half']")
def login(): if request.method == "GET": token = request.args.get("token") if token is None: # The request is from user if session.get("token") is not None: # web server has session sso_url = flask_config[web_type].sso_url sso_headers = { "Content-Type": "application/json", "Token": session["token"] } sso_request_data = {"AppServer": 1001} sso_response = requests.post(sso_url + "/login", data=json.dumps(sso_request_data), headers=sso_headers) logger.info("Send token:" + session["token"]) ret = json.loads(sso_response.text) if ret["retCode"] == 1: # correct token, login success. logger.info("Login success:" + session["username"] + " from " + request.remote_addr) return redirect("/DailyReport") else: if ret["retCode"] == 4: logger.info("Can't match token, login needed:" + session["username"]) else: logger.info("Unknown Error:" + session["username"]) session.clear() return redirect(sso_url + "/login?AppServer=" + flask_config[web_type].local_url + "&srv_path=login") else: # web server doesn't have session return redirect(flask_config[web_type].sso_url + "/login?AppServer=" + flask_config[web_type].local_url + "&srv_path=login") else: # The request is from SSO sso_url = flask_config[web_type].sso_url sso_headers = {"Content-Type": "application/json", "Token": token} sso_request_data = {"AppServer": 1001} sso_response = requests.post(sso_url + "/login", data=json.dumps(sso_request_data), headers=sso_headers) logger.info("Send token:" + token) ret = json.loads(sso_response.text) if ret["retCode"] == 1: # correct token, login success. if (ret["department"] == "规划与建设管理部") | (ret["department"] == "建设公司"): session["department"] = "规划与建设管理部(建设公司)" elif (ret["department"] == "资产运营部") | (ret["department"] == "置业公司"): session["department"] = "资产运营部(置业公司)" else: session["department"] = ret["department"] session["token"] = token session["name"] = ret["name"] session["username"] = ret["username"] logger.info("Login success:" + session["username"] + " from " + request.remote_addr) return redirect("/DailyReport") else: if ret["retCode"] == 4: logger.info("Can't match token, login needed.") else: logger.info("Internal Server Error") session.clear() return redirect(sso_url + "/login?AppServer=" + flask_config[web_type].local_url + "&srv_path=login")
def sso_login(): if request.method == "GET": app_server = request.args.get("AppServer", None) srv_path = request.args.get("srv_path", "") if app_server is None: return "Hello World!" app_server = check_app_server(app_server) if app_server == 0: return "Hello World!" if session.get("token") is not None: return redirect(app_server + "/" + srv_path + "?token=" + session.get("token")) return render_template("login.html", app_server=app_server, srv_path=srv_path) elif request.method == "POST": token = request.headers.get("Token") if token is not None: # the header contains token token = rc4_decrypt(token, rc4_key) redis_ret = check_token(token) session.clear() if redis_ret == 1: # Token is valid ret = query_user_info(token) if ret == 2: return jsonify({ "status": 200, "retCode": 2 }) # The account doesn't exist elif ret == 3: return jsonify({ "status": 200, "retCode": 3 }) # The account was blocked else: logger.info("Login success:" + token.split(":")[0]) return jsonify({ "status": 200, "retCode": 1, "name": ret[0], "department": ret[1], "department_id": ret[2], "username": token.split(":")[0] }) # Matched correct token else: set_session_expired(token) return jsonify({ "status": 200, "retCode": 4 }) # No match, login needed else: # the header doesn't contains token form_data = json.loads(request.get_data().decode("utf-8")) if "username" not in form_data or "password" not in form_data: return jsonify({ "status": 200, "retCode": 5 }) # No match, need login username = form_data["username"] password = form_data["password"] if session.get("token") is not None: # maybe from cross_origin token = rc4_decrypt(session.get("token"), rc4_key) if token.split(":")[0] == username: redis_ret = check_token(token) if redis_ret == 1: logger.info("Send token to cross_origin:" + username) return jsonify({ "status": 200, "retCode": 1, "token": session.get("token") }) limit_counts = login_attempt_limit(username, method="get") if limit_counts >= 5: logger.info("Too many login attempts:" + username) return jsonify({"status": 200, "retCode": 6}) ret = query_login(username, password) logger.info("Attempt Login:"******"Internal Server Error") return jsonify({"status": 200, "retCode": 4}) logger.info( "Login fail: wrong account or password, current limit times=" + str(limit_counts)) return jsonify({ "status": 200, "retCode": 2, "limit_counts": limit_counts }) # Wrong username or password elif ret == 3: logger.info("Login fail: the account was blocked") return jsonify({ "status": 200, "retCode": 3 }) # The account was blocked elif ret == 1: token = username + ":" + session.sid redis_ret = set_token(token) token = rc4_encrypt(token, rc4_key) if redis_ret != 1: return jsonify({ "status": 200, "retCode": 7 }) # Server Error session["token"] = token logger.info("Create token:" + username) return jsonify({"status": 200, "retCode": 1, "token": token}) # Login success, create token else: return jsonify({"status": 200, "retCode": 4})