def send_email(): response = Response() response.headers['Content-Type'] = 'application/json' response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Headers'] = '*' if request.method == 'OPTIONS': return response elif request.method == 'POST': message = json.loads(request.get_data(as_text = True)) name = message.get('name') token = message.get('token', '') if name is None: return response_json(code=1, message='Name is required') result = confirm_token(token) if result is False: return response_json(code=2, message='Token is not available, plz check your latest email') email = result['email'] if is_token_unused(token): # 先确定下是不是志愿者列表中的token 并且是否注册过 没问题的话开始做图片 update_status(email, 2) update_name(email,name) try: wc.write_to_pic(name,email,token) return_json = {'code': 0, 'message': 'You have submitted your information successful, the certificate is sent to you, please check your email', 'data': None} response.data = return_msg(return_json) return response except Exception as e: # 发送邮件或者创建图片错误 可能是邮件有问题 logger.error(e) return response_json(4, str(e)) else: return response_json(3, 'You have submitted your information successful, please check your email')
def get_collection(identifier): """ Retrieve the collection with uuid <identifier>. Args: identifier (str): uuid for the wanted collection Returns: flask.Request: json structure for the collection """ entry = utils.req_get_entry("collections", identifier) if not entry: flask.abort(status=404) # only show editors if owner/admin if not flask.g.current_user or ( not utils.req_has_permission("DATA_MANAGEMENT") and flask.g.current_user["_id"] not in entry["editors"]): flask.current_app.logger.debug( "Not allowed to access editors field %s", flask.g.current_user) del entry["editors"] else: entry["editors"] = utils.user_uuid_data(entry["editors"], flask.g.db) # return {_id, _title} for datasets entry["datasets"] = [ flask.g.db.datasets.find_one({"_id": dataset}, {"title": 1}) for dataset in entry["datasets"] ] return utils.response_json({"collection": entry})
def predict(model_name: str) -> Response: # pylint: disable=unused-variable logging.info('This is an info message') if request.method == "OPTIONS": return Response(response="", status=200) data = request.get_json() model = model_name.lower() output = response_json(data, model) posts = demo_db.posts post_data = { "response_data": output, "slug": "", "model": model_name, "request_data": data } result_id = posts.insert_one(post_data).inserted_id myquery = {"_id": result_id} slug = int_to_slug(result_id) newvalues = {"$set": {"slug": slug}} output['slug'] = slug posts.update_one(myquery, newvalues) return json.dumps(output).encode('utf8') return jsonify(output)
def show_operator(request): try: if request.method != 'POST': form = PhoneForm(request.GET) else: form = PhoneForm(request.POST) if form.is_valid(): phone = form.cleaned_data['phone'] operator = Operator.find(phone) if operator: response = { 'status': 0, 'message': 'ok', 'phone': phone, 'operator': operator.name, 'region': operator.region, 'mobile': operator.mobile, } else: raise OperatorNotFoundException else: raise WrongNumberException except (OperatorNotFoundException, WrongNumberException), e: return response_json({'status': 1, 'message': e.msg})
def gen_new_api_key(identifier: str = None): """ Generate a new API key for the provided or current user. Args: identifier (str): The user identifier. Returns: flask.Response: The new API key """ if identifier != flask.g.current_user["_id"]: perm_status = utils.req_check_permissions(["USER_MANAGEMENT"]) if perm_status != 200: flask.abort(status=perm_status) user_data = utils.req_get_entry("users", identifier) if not user_data: flask.abort(status=404) apikey = utils.gen_api_key() new_hash = utils.gen_api_key_hash(apikey.key, apikey.salt) new_values = {"api_key": new_hash, "api_salt": apikey.salt} user_data.update(new_values) result = flask.g.db["users"].update_one({"_id": identifier}, {"$set": new_values}) if not result.acknowledged: flask.current_app.logger.error("Updating API key for user %s failed", identifier) flask.Response(status=500) else: utils.make_log("user", "edit", "New API key", user_data) return utils.response_json({"key": apikey.key})
def get_current_user_info(): """ List basic information about the current user. Returns: flask.Response: json structure for the user """ data = flask.g.current_user outstructure = { "_id": "", "affiliation": "", "auth_ids": [], "email": "", "contact": "", "name": "", "orcid": "", "permissions": [], "url": "", } if data: for field in outstructure: outstructure[field] = data[field] outstructure["permissions"] = utils.prepare_permissions( outstructure["permissions"]) return utils.response_json({"user": outstructure})
def get_user_actions(identifier: str): """ Get a list of actions (changes) by the user entry with ``identifier``. Can be accessed by actual user and USER_MANAGEMENT. Args: identifier (str): The user identifier. Returns: flask.Response: Information about the user as json. """ if identifier != (flask.g.current_user["_id"] or None): perm_status = utils.req_check_permissions(["USER_MANAGEMENT"]) if perm_status != 200: flask.abort(status=perm_status) # only report a list of actions, not the actual data user_logs = list(flask.g.db["logs"].find({"user": identifier}, {"user": 0})) for entry in user_logs: entry["entry_id"] = entry["data"]["_id"] del entry["data"] return utils.response_json({"logs": user_logs})
def get_user_actions(identifier: str = None): """ Get a list of actions (changes) by the user entry with uuid ``identifier``. Can be accessed by actual user and admin (USER_MANAGEMENT). Args: identifier (str): The uuid of the user. Returns: flask.Response: Information about the user as json. """ if identifier is None: identifier = str(flask.g.current_user['_id']) if str(flask.g.current_user['_id']) != identifier and not has_permission( 'USER_MANAGEMENT'): flask.abort(403) try: user_uuid = utils.str_to_uuid(identifier) except ValueError: flask.abort(status=404) # only report a list of actions, not the actual data user_logs = list(flask.g.db['logs'].find({'user': user_uuid}, {'user': 0})) for entry in user_logs: entry['entry_id'] = entry['data']['_id'] del entry['data'] return utils.response_json({'logs': user_logs})
def get_user_data(identifier: str): """ Get information about a user. Args: identifier (str): The user identifier. Returns: flask.Response: Information about the user as json. """ perm_status = utils.req_check_permissions(["USER_MANAGEMENT"]) if perm_status != 200: flask.abort(status=perm_status) user_info = utils.req_get_entry("users", identifier) if not user_info: flask.abort(status=404) # The hash and salt should never leave the system del user_info["api_key"] del user_info["api_salt"] user_info["permissions"] = utils.prepare_permissions( user_info["permissions"]) return utils.response_json({"user": user_info})
def show_operator(request): try: if request.method != 'POST': form = PhoneForm(request.GET) else: form = PhoneForm(request.POST) if form.is_valid(): phone = form.cleaned_data['phone'] operator = Operator.find(phone) if not operator: operator = Operator.find_by_range(phone) if operator: response = { 'status': 0, 'message': 'ok', 'phone': phone, 'operator': operator.name, 'region': operator.region, 'region_code': operator.region_code, 'mobile': operator.mobile, 'country': operator.country, } else: raise OperatorNotFoundException else: raise InvalidNumberException except (OperatorNotFoundException, InvalidNumberException), e: return response_json({'status': 1, 'message': e.msg, 'code':e.code})
def list_collection(): """Provide a simplified list of all available collections.""" results = list(flask.g.db["collections"].find(projection={ "title": 1, "_id": 1, "tags": 1, "properties": 1 })) return utils.response_json({"collections": results})
def list_user_data(): """List all datasets belonging to current user.""" user_orders = list( flask.g.db["orders"].find({"editors": flask.session["user_id"]}, {"datasets": 1}) ) uuids = list(ds for entry in user_orders for ds in entry["datasets"]) user_datasets = list(flask.g.db["datasets"].find({"_id": {"$in": uuids}})) return utils.response_json({"datasets": user_datasets})
def get_dataset_data_structure(): """ Get an empty dataset entry. Returns: flask.Response: JSON structure of a dataset. """ empty_dataset = structure.dataset() empty_dataset["_id"] = "" return utils.response_json({"dataset": empty_dataset})
def get_collection_data_structure(): """ Get an empty collection entry. Returns: flask.Response: JSON structure of a collection. """ empty_collection = structure.collection() empty_collection["_id"] = "" return utils.response_json({"collection": empty_collection})
def get_user_data_structure(): """ Get an empty user entry. Returns: flask.Response: JSON structure of a user. """ empty_user = structure.user() empty_user["_id"] = "" return utils.response_json({"user": empty_user})
def get_user_data_structure(): """ Get an empty user entry. Returns: flask.Response: JSON structure with a list of users. """ empty_user = structure.user() empty_user['_id'] = '' return utils.response_json({'user': empty_user})
def add_dataset(identifier: str): # pylint: disable=too-many-branches """ Add a dataset to the given order. Args: identifier (str): The order to add the dataset to. """ order = utils.req_get_entry("orders", identifier) if not order: flask.abort(status=404) if (not utils.req_has_permission("DATA_MANAGEMENT") and flask.g.current_user["_id"] not in order["editors"]): flask.abort(status=403) new_dataset = structure.dataset() jsondata = flask.request.json if not jsondata or "dataset" not in jsondata or not isinstance( jsondata["dataset"], dict): flask.abort(status=400) indata = jsondata["dataset"] validation = utils.basic_check_indata(indata, new_dataset, ["_id"]) if not validation.result: flask.abort(status=validation.status) indata = utils.prepare_for_db(indata) new_dataset.update(indata) ds_result = utils.req_commit_to_db("datasets", "add", new_dataset) if not ds_result.log or not ds_result.data: flask.abort(status=500) order_result = flask.g.db["orders"].update_one( {"_id": order["_id"]}, {"$push": { "datasets": new_dataset["_id"] }}) if not order_result.acknowledged: flask.current_app.logger.error("Failed to add dataset %s to order %s", new_dataset["_id"], order["_id"]) flask.abort(status=500) order["datasets"].append(new_dataset["_id"]) utils.req_make_log_new( data_type="order", action="edit", comment="Dataset added", data=order, ) return utils.response_json({"_id": ds_result.ins_id})
def add_user(): """ Add a user. Returns: flask.Response: Information about the user as json. """ perm_status = utils.req_check_permissions(["USER_ADD"]) if perm_status != 200: flask.abort(status=perm_status) new_user = structure.user() jsondata = flask.request.json if not jsondata.get("user") or not isinstance(jsondata["user"], dict): flask.abort(status=400) indata = jsondata["user"] validation = utils.basic_check_indata( indata, new_user, ("_id", "api_key", "api_salt", "auth_ids")) if not validation.result: flask.abort(status=validation.status) indata = utils.prepare_for_db(indata) if not indata: flask.abort(status=400) if "email" not in indata: flask.current_app.logger.debug("Email must be set") flask.abort(status=400) old_user = flask.g.db["users"].find_one({"email": indata["email"]}) if old_user: flask.current_app.logger.debug("User already exists") flask.abort(status=400) if not utils.req_has_permission( "USER_MANAGEMENT") and "permissions" in indata: flask.current_app.logger.debug( "USER_MANAGEMENT required for permissions") flask.abort(403) new_user.update(indata) new_user["auth_ids"] = [new_user["email"]] result = utils.req_commit_to_db("users", "add", new_user) if not result.log or not result.data: flask.abort(status=500) return utils.response_json({"_id": result.ins_id})
def get_dataset(identifier): """ Retrieve the dataset with uuid <identifier>. Args: identifier (str): uuid for the wanted dataset Returns: flask.Response: json structure for the dataset """ result = build_dataset_info(identifier) if not result: return flask.Response(status=404) return utils.response_json({"dataset": result})
def on_move(sid, data): game_id = ObjectId(data.get("gameId")) move = data.get("move") game = GAME_DB.games.find_one({'_id': game_id}) if not game: print("Game not found.") return response_json(404, "Game not found.") turn = 'w' if len(game['moves']) % 2 == 0 else 'b' if turn == 'w' and sid != game['wSid'] or turn == 'b' and sid != game[ 'bSid']: print("Not your move.") return response_json(400, "Not your move.") wT, bT = updatePlayersTime(game_id, turn) moveIsLegal = update_pgn(game_id, move) if not moveIsLegal: return response_json(400, "Illegal move.") game_data = {"move": move, "wt": wT, "bt": bT} if turn == 'w': SIO.emit('move', game_data, room=game['bSid']) else: SIO.emit('move', game_data, room=game['wSid'])
def list_orders(): """ List all orders visible to the current user. Returns: flask.Response: JSON structure with a list of orders. """ projection = {"_id": 1, "title": 1, "tags": 1, "properties": 1} if utils.req_has_permission("DATA_MANAGEMENT"): orders = list(flask.g.db["orders"].find(projection=projection)) else: orders = list(flask.g.db["orders"].find( {"editors": flask.g.current_user["_id"]}, projection=projection)) return utils.response_json({"orders": orders})
def list_users(): """List all users.""" perm_status = utils.req_check_permissions(["USER_SEARCH"]) if perm_status != 200: flask.abort(status=perm_status) fields = {"api_key": 0, "api_salt": 0} if not utils.req_has_permission("USER_MANAGEMENT"): fields["auth_ids"] = 0 fields["permissions"] = 0 result = tuple(flask.g.db["users"].find(projection=fields)) return utils.response_json({"users": result})
def add_user(): """ Add a user. Returns: flask.Response: Information about the user as json. """ if not has_permission('USER_ADD'): flask.abort(403) new_user = structure.user() try: indata = flask.json.loads(flask.request.data) except json.decoder.JSONDecodeError: flask.abort(status=400) validation = utils.basic_check_indata( indata, new_user, ('_id', 'api_key', 'api_salt', 'auth_ids')) if not validation.result: flask.abort(status=validation.status) if 'email' not in indata: flask.current_app.logger.debug('Email must be set') flask.abort(status=400) old_user = flask.g.db['users'].find_one({'email': indata['email']}) if old_user: flask.current_app.logger.debug('User already exists') flask.abort(status=400) if not has_permission('USER_MANAGEMENT') and 'permissions' in indata: flask.current_app.logger.debug( 'USER_MANAGEMENT required for permissions') flask.abort(403) new_user.update(indata) new_user['auth_ids'] = [f'{new_user["_id"]}::local'] result = flask.g.db['users'].insert_one(new_user) if not result.acknowledged: flask.current_app.logger.error('User Addition failed: %s', new_user['email']) flask.Response(status=500) else: utils.make_log('user', 'add', 'User added by admin', new_user) return utils.response_json({'_id': result.inserted_id})
def list_users(): """ List all users. Admin access should be required. """ if not has_permission('USER_SEARCH'): flask.abort(403) fields = {'api_key': 0, 'api_salt': 0} if not has_permission('USER_MANAGEMENT'): fields['auth_ids'] = 0 fields['permissions'] = 0 result = tuple(flask.g.db['users'].find(projection=fields)) return utils.response_json({'users': result})
def get_dataset_log(identifier: str = None): """ Get change logs for the user entry with uuid ``identifier``. Can be accessed by editors with DATA_EDIT and admin (DATA_MANAGEMENT). Logs for deleted datasets cannot be accessed. Args: identifier (str): The uuid of the dataset. Returns: flask.Response: Logs as json. """ perm_status = utils.req_check_permissions(["DATA_EDIT"]) if perm_status != 200: flask.abort(status=perm_status) dataset = utils.req_get_entry("datasets", identifier) if not dataset: flask.abort(status=404) order_data = flask.g.db["orders"].find_one({"datasets": dataset["_id"]}) if not order_data: flask.current_app.logger.error("Dataset without parent order: %s", dataset["_id"]) flask.abort(500) if ( not utils.req_has_permission("DATA_MANAGEMENT") and flask.g.current_user["_id"] not in order_data["editors"] ): flask.abort(403) dataset_logs = list( flask.g.db["logs"].find({"data_type": "dataset", "data._id": dataset["_id"]}) ) for log in dataset_logs: del log["data_type"] utils.incremental_logs(dataset_logs) return utils.response_json( {"entry_id": dataset["_id"], "data_type": "dataset", "logs": dataset_logs} )
def add_collection(): """ Add a collection. Returns: flask.Response: Json structure with the ``_id`` of the collection. """ perm_status = utils.req_check_permissions(["DATA_EDIT"]) if perm_status != 200: flask.abort(status=perm_status) # create new collection collection = structure.collection() jsondata = flask.request.json if not jsondata or "collection" not in jsondata or not isinstance( jsondata["collection"], dict): flask.abort(status=400) indata = jsondata["collection"] # indata validation validation = utils.basic_check_indata(indata, collection, prohibited=["_id"]) if not validation.result: flask.abort(status=validation.status) if not indata.get("editors"): indata["editors"] = [flask.g.current_user["_id"]] # add current user if missing and only DATA_EDIT elif (not utils.req_has_permission("DATA_MANAGEMENT") and str(flask.g.current_user["_id"]) not in indata["editors"]): indata["editors"].append(flask.g.current_user["_id"]) indata = utils.prepare_for_db(indata) collection.update(indata) # add to db result = utils.req_commit_to_db("collections", "add", collection) if not result.log or not result.data: flask.abort(status=500) return utils.response_json({"_id": result.ins_id})
def get_collection_log(identifier: str = None): """ Get change logs for the collection matching ``identifier``. Can be accessed by editors (with DATA_EDIT) and admin (DATA_MANAGEMENT). Deleted entries cannot be accessed. Args: identifier (str): The uuid of the collection. Returns: flask.Response: Logs as json. """ perm_status = utils.req_check_permissions(["DATA_EDIT"]) if perm_status != 200: flask.abort(status=perm_status) collection = utils.req_get_entry("collections", identifier) if not collection: flask.abort(status=404) if (not utils.req_has_permission("DATA_MANAGEMENT") and flask.g.current_user["_id"] not in collection["editors"]): flask.abort(403) collection_logs = list(flask.g.db["logs"].find({ "data_type": "collection", "data._id": collection["_id"] })) for log in collection_logs: del log["data_type"] utils.incremental_logs(collection_logs) return utils.response_json({ "entry_id": collection["_id"], "data_type": "collection", "logs": collection_logs, })
def get_user_log(identifier: str = None): """ Get change logs for the user entry with uuid ``identifier``. Can be accessed by actual user and admin (USER_MANAGEMENT). Args: identifier (str): The uuid of the user. Returns: flask.Response: Information about the user as json. """ if identifier is None: identifier = str(flask.g.current_user['_id']) if str(flask.g.current_user['_id']) != identifier and not has_permission( 'USER_MANAGEMENT'): flask.abort(403) try: user_uuid = utils.str_to_uuid(identifier) except ValueError: flask.abort(status=404) user_logs = list(flask.g.db['logs'].find({ 'data_type': 'user', 'data._id': user_uuid })) for log in user_logs: del log['data_type'] utils.incremental_logs(user_logs) return utils.response_json({ 'entry_id': user_uuid, 'data_type': 'user', 'logs': user_logs })
def get_order(identifier): """ Retrieve the order with the provided uuid. ``order['datasets']`` is returned as ``[{_id, title}, ...]``. Args: identifier (str): Uuid for the wanted order. Returns: flask.Response: JSON structure for the order. """ entry = utils.req_get_entry("orders", identifier) if not entry: flask.abort(status=404) if not (utils.req_has_permission("DATA_MANAGEMENT") or flask.g.current_user["_id"] in entry["editors"]): flask.abort(status=403) prepare_order_response(entry, flask.g.db) return utils.response_json({"order": entry})
def add_order(): """ Add an order. Returns: flask.Response: Json structure with ``_id`` of the added order. """ # create new order new_order = structure.order() jsondata = flask.request.json if not jsondata or "order" not in jsondata or not isinstance( jsondata["order"], dict): flask.abort(status=400) indata = jsondata["order"] validation = utils.basic_check_indata(indata, new_order, ["_id", "datasets"]) if not validation.result: flask.abort(status=validation.status) # add current user to editors if no editors are defined if not indata.get("editors"): indata["editors"] = [flask.g.current_user["_id"]] # add current user if missing and only DATA_EDIT elif (not utils.req_has_permission("DATA_MANAGEMENT") and str(flask.g.current_user["_id"]) not in indata["editors"]): indata["editors"].append(flask.g.current_user["_id"]) # convert all incoming uuids to uuid.UUID indata = utils.prepare_for_db(indata) new_order.update(indata) result = utils.req_commit_to_db("orders", "add", new_order) if not result.log or not result.data: flask.abort(status=500) return utils.response_json({"_id": result.ins_id})
def get_order_logs(identifier): """ List changes to the dataset. Logs will be sorted chronologically. The ``data`` in each log will be trimmed to only show the changed fields. Args: identifier (str): Uuid for the wanted order. Returns: flask.Response: Json structure for the logs. """ entry = utils.req_get_entry("orders", identifier) if not entry: flask.abort(status=404) if (not utils.req_has_permission("DATA_MANAGEMENT") and flask.g.current_user["_id"] not in entry["editors"]): flask.abort(status=403) order_logs = list(flask.g.db["logs"].find({ "data_type": "order", "data._id": entry["_id"] })) if not order_logs: flask.abort(status=404) for log in order_logs: del log["data_type"] utils.incremental_logs(order_logs) return utils.response_json({ "entry_id": entry["_id"], "data_type": "order", "logs": order_logs })
operator = Operator.find(phone) if not operator: operator = Operator.find_by_range(phone) if operator: response = { 'status': 0, 'message': 'ok', 'phone': phone, 'operator': operator.name, 'region': operator.region, 'region_code': operator.region_code, 'mobile': operator.mobile, 'country': operator.country, } else: raise OperatorNotFoundException else: raise InvalidNumberException except (OperatorNotFoundException, InvalidNumberException), e: return response_json({'status': 1, 'message': e.msg, 'code':e.code}) except Exception, e: return response_json({'status': 1, 'message': e}) return response_json(response)