def exchange_for_tokens(): provider = request.args.get('provider') or '' if provider == GOOGLE_OAUTH: auth = GoogleOAuth().exchange_for_tokens(request) else: auth = None email = auth.email if not email: return make_response(errors=auth.note, status_code=400) token = create_access_token(identity=dict(email=email)) user = User.find_one(email=email) if not user: user = User( email=email, token=token, credentials={provider: auth.credential}, ) err = user.validate() if err: return make_response(errors=err, status_code=400) user, err = user.save() if err: return make_response(errors=err, status_code=400) else: user.credentials.update({provider: auth.credential}) user, err = user.save() if err: return make_response(errors=err, status_code=400) return make_response(user)
def wiki_verify(version: int): """ 审核一个版本 即从某个版本复制一份,同时设置verified为True """ old_one: WikiPageVersion = db.session.query(WikiPageVersion).filter_by( id=version).one_or_none() if not old_one: return make_response(-1, message="版本不存在") old_one.verified = True new_one = WikiPageVersion(wikipage_id=old_one.wikipage_id, uid=session.get("uid"), title=old_one.title, content=old_one.content, verified=True, base=old_one.id, navigation_id=old_one.navigation_id, comment=f"审核自 {old_one.time} 的版本 {old_one.id}") db.session.add(new_one) db.session.commit() page: WikiPage = db.session.query(WikiPage).filter_by( id=new_one.wikipage_id).one() page.cached_newest_version = new_one.id db.session.commit() return make_response(0, message="操作完成", id=new_one.id)
def wiki_new_version(page: int, version: int, content: str, navigation_id: int, comment: str = ""): """ 发布某个页面的新版本 page: 页面ID version: 前序版本ID content: 新的内容 """ page_version: WikiPageVersion = db.session.query( WikiPageVersion, ).filter_by(id=version).one_or_none() if not page_version: return make_response(-1, message="版本不存在") if page_version.wikipage_id != page: return make_response(-1, message="此版本不对应于指定的页面") new_version = WikiPageVersion(wikipage_id=page, uid=session.get("uid"), title=page_version.title, content=content, verified=False, base=page_version.id, navigation_id=navigation_id, comment=comment) db.session.add(new_version) db.session.commit() return make_response(0, message=f"您的版本已经提交成功,请前往该页面的版本列表查看并等待管理员审核。")
def api_finish_problemset(challengeID: int, problemsetID: int): """ 申请完成一个挑战下的某个习题集 challengeID 挑战ID problemsetID 习题集ID """ if not permission_manager.has_permission( session.get("uid"), f"challenge.access.{challengeID}"): return make_response(-1, message="你没有权限访问该挑战") challenge: Challenge = db.session.query(Challenge.problemset_list).filter( Challenge.id == challengeID).one_or_none() if not challenge: return make_response(-1, message="该挑战不存在") if problemsetID not in challenge.problemset_list: return make_response(-1, message="该习题集ID不在该挑战之下") problemset: ProblemSet = db.session.query( ProblemSet.problems).filter(ProblemSet.id == problemsetID).one() for problem in problemset.problems: submission = db.session.query(Submission.id).filter( expr.and_(Submission.uid == session.get("uid"), Submission.problem_id == problem, Submission.status == "accepted")).one_or_none() if not submission: return make_response(-1, message="在该习题集之下,你尚存题目未完成.") permission_manager.add_permission( session.get("uid"), f"challenge.finish.{challengeID}.{problemsetID}") return make_response(0, message="操作完成")
def login(): ''' 登陆请求 @@@ ### 说明 登陆请求 ### 请求 | 字段 | 字段类型 | 可选/必选 | 字段描述 | | username | string | M | 登陆用户名 | | password | string | M | 密码 | ### 返回 | 字段 | 字段类型 | 字段描述 | @@@ ''' username = g.args.get('username', None) password = g.args.get('password', None) if username is None or password is None: return make_response(code=1, msg='用户名或密码非法') res = dbse.query(User).filter(User.name == username).first() if res is None: return make_response(code=1, msg='用户不存在') if res.name == username and res.password == password: token = create_token({'userid': res.id, 'username': res.name}) return make_response(code=0, data={'token': token}) else: return make_response(code=1, msg='用户名或密码错误')
def api_feed_toggle_top_state(feedID: int): feed: Feed = db.session.query(Feed).filter_by(id=feedID).one_or_none() if not feed: return make_response(-1, message="该feed不存在") feed.top = not feed.top db.session.commit() return make_response(0, message="操作完成", topped=feed.top)
def main(event, context): if validate_request(required_keys, event['queryStringParameters']): try: org_id = event['queryStringParameters']['organization_id'] service_id = event['queryStringParameters']['service_id'] username = event['queryStringParameters']['username'] free_call_details = usage_service.get_free_call_details( username, org_id, service_id) return_value = make_response( status_code=StatusCode.SUCCESS_GET_CODE, header=HEADER_POST_RESPONSE, body=json.dumps(free_call_details)) except Exception as e: logger.error(e) return_value = make_response( status_code=StatusCode.SERVER_ERROR_CODE, header=HEADER_POST_RESPONSE, body=json.dumps({"error": StatusMessage.SERVER_ERROR_MSG})) else: logger.error( f"Request validation failed for {event['queryStringParameters']}") return_value = make_response( status_code=StatusCode.BAD_PARAMETERS_CODE, header=HEADER_POST_RESPONSE, body=json.dumps({"error": StatusMessage.BAD_PARAMETER})) return return_value
def check_login(): identity_data = get_jwt_identity() email=identity_data.get('email') or '' user = User.find_one(email=email) if not user: return make_response(message='user not found', status_code=400) return make_response(user, status_code=200)
def api_get_challenge_detail(challengeID: int): """ 查询挑战详情 { "name":"名称", "id":ID, "description":描述, "level":等级, "hasFinished":是否完成 "problemsetList":[ { "name":"名称", "hasFinished":"是否完成", "id":"ID" } ] } """ if not permission_manager.has_permission( session.get("uid"), f"challenge.access.{challengeID}"): return make_response(-1, message="你没有权限访问该挑战") challenge: Challenge = db.session.query(Challenge).filter( Challenge.id == challengeID).one_or_none() if not challenge: return make_response(-1, message="该挑战不存在") result = { "name": challenge.name, "id": challenge.id, "description": challenge.description, "hasFinished": permission_manager.has_permission( session.get("uid"), f"challenge.finish.{challengeID}.all"), "level": challenge.level, "problemsetList": [] } for problemset in challenge.problemset_list: current = db.session.query( ProblemSet.id, ProblemSet.name).filter(ProblemSet.id == problemset).one() result["problemsetList"].append({ "name": current.name, "id": current.id, "hasFinished": permission_manager.has_permission( session.get("uid"), f"challenge.finish.{challengeID}.{problemset}") }) return make_response(0, data=result)
def remote_judge_remove_account(accountID: str): remote_account: RemoteAccount = db.session.query(RemoteAccount).filter( RemoteAccount.account_id == accountID).one_or_none() if not remote_account: return make_response(-1, message="错误的用户ID") if remote_account.uid != int(session.get("uid")): return make_response(-1, message="你只能更改自己的Remote Judge账户") db.session.delete(remote_account) db.session.commit() return make_response(0, message="删除成功")
def problemtodo_remove(problemID: int): if not session.get("uid", None): return make_response(-1, message="请先登录") if db.session.query(ProblemTodo).filter_by( problem_id=problemID, uid=session.get("uid")).limit(1).count() == 0: return make_response(-1, message="此题目不在您的题单内") db.session.query(ProblemTodo).filter_by(uid=session.get("uid"), problem_id=problemID).delete() db.session.commit() return make_response(0, message="操作完成")
def api_problemtag_update(id: str, display: str, color: str): """ 更新某个tag """ # db.session.query(Tag).filter_by(id=id).delete() tag = db.session.query(Tag).filter_by(id=id).one_or_none() if not tag: return make_response(-1, message="Tag不存在") tag.display = display tag.color = color db.session.commit() return make_response(0, message="操作完成")
def delete(self): data = self.utils.request_form_to_dict() try: addr_id = int(data["addr_id"]) uid = int(data["uid"]) except: return make_response(message=u"faile") status = self.models.Ship_address.delete_address(addr_id=addr_id, uid=uid) if status: return make_response() else: return make_response(message=u"faile")
def problemtodo_add(problemID: int): if not session.get("uid", None): return make_response(-1, message="请先登录") if db.session.query(ProblemTodo).filter_by( problem_id=problemID, uid=session.get("uid")).limit(1).count(): return make_response(-1, message="此题目已经在您的题单内") if db.session.query(ProblemTodo).filter_by( uid=session.get("uid")).count() >= config.MAX_PROBLEMTODO_COUNT: return make_response(-1, message="已经达到了您的待做题目数上限") db.session.add(ProblemTodo(uid=session.get("uid"), problem_id=problemID)) db.session.commit() return make_response(0, message="操作完成")
def api_problemset_join_private_problemset(id: int, code: str): problemset: ProblemSet = db.session.query( ProblemSet.invitation_code).filter(ProblemSet.id == id).one_or_none() if not problemset: return make_response(-1, message="ID不存在") if code != problemset.invitation_code: return make_response(-1, message="邀请码错误") if not session.get("uid"): return make_response(-1, message="请先登录") permission_manager.add_permission(session.get("uid"), f"problemset.use.{id}") return make_response(0, message="ok")
def api_get_challenge_remove(id: int): """ 删除挑战 """ challenge: Challenge = db.session.query(Challenge).filter( Challenge.id == id).one_or_none() if not challenge: return make_response(-1, message="挑战不存在") db.session.delete(challenge) db.session.commit() return make_response(0, message="操作完成")
def api_problemtag_update_problem(problemID: int, tags: typing.List[int]): uid = int(session.get("uid", -1)) problem = db.session.query( Problem.uploader_id).filter_by(id=problemID).one() if not permission_manager.has_permission( uid, "problem.manage") and uid != problem.uploader_id: return make_response(-1, message="你没有权限执行此操作") db.session.query(ProblemTag).filter( ProblemTag.problem_id == problemID).delete() db.session.add_all( (ProblemTag(problem_id=problemID, tag_id=item) for item in tags)) db.session.commit() return make_response(0, message="操作完成")
def api_problemset_remove(id): problemset: ProblemSet = db.session.query(ProblemSet).filter( ProblemSet.id == id).one_or_none() if not problemset: return make_response(-1, message="非法ID") if not permission_manager.has_permission( session.get("uid"), "problemset.manage") and problemset.owner_uid != int( session.get("uid")): return make_response(-1, message="你没有权限进行此操作") db.session.delete(problemset) db.session.commit() return make_response(0, message="删除成功")
def remote_judge_update_session(uuid: str, account_id: str, session: dict): """ 登录后更新session """ print(locals()) # print(kwargs) if uuid not in config.JUDGERS: return make_response(-1, message="未认证评测机") account: RemoteAccount = db.session.query(RemoteAccount).filter( RemoteAccount.account_id == account_id).one() account.session = encode_json(session) db.session.commit() return make_response(0, message="done")
def remote_judge_create_submission(uuid: str, client_session_id: str, code: str, language: str, uid: int, hj2_problem_id: str, public: bool, message: str, contest_id: int = -1, contest_problem_id: int = -1): print(locals()) """ 评测端向远程OJ提交代码成功后,创建相应的提交记录 """ if uuid not in config.JUDGERS: return make_response(-1, message="未认证评测机") import datetime if contest_id != -1: contest: Contest = Contest.by_id(contest_id) submission: Submission = Submission( uid=uid, language=language, problem_id=contest.problems[contest_problem_id]["id"], submit_time=datetime.datetime.now(), public=False, code=code, status="waiting", contest_id=contest_id) else: submission: Submission = Submission( uid=uid, language=language, problem_id=hj2_problem_id, submit_time=datetime.datetime.now(), public=public, code=code, status="waiting", ) db.session.add(submission) db.session.commit() print("Submit done. ", submission.id) emit("server_response", { "ok": True, "data": { "submission_id": submission.id } }, room=client_session_id, namespace="/ws/remote_judge") return make_response(0, data={"submission_id": submission.id})
def api_problemtag_create(id: str): """ 创建tag """ # db.session.query(Tag).filter_by(id=id).delete() if db.session.query(Tag).filter_by(id=id).one_or_none(): return make_response(-1, message="此Tag已经存在") tag = Tag(id=id, display="新建Tag", color="") db.session.add(tag) db.session.commit() return make_response(0, display=tag.display, color=tag.color, message="操作完成")
def remote_judge_update(ok: bool, data: dict, uuid: str, client_session_id: str): """ 提交时状态更新,评测端调用 """ if uuid not in config.JUDGERS: return make_response(-1, message="未认证评测机") emit("server_response", { "ok": ok, "data": data }, room=client_session_id, namespace="/ws/remote_judge") return make_response(0, message="done")
def remote_judge_update_fetch(ok: bool, uuid: str, client_session_id: str, hj2_problem_id: str, result: dict = None, message: str = ""): """ 更新添加题目状态,评测端调用 """ if uuid not in config.JUDGERS: return make_response(-1, message="未认证评测机") if not ok: emit("server_response", { "ok": False, "message": message }, room=client_session_id, namespace="/ws/remote_judge") db.session.query(Problem).filter(Problem.id == hj2_problem_id).delete() return make_response(0, message="done") problem: Problem = db.session.query(Problem).filter( Problem.id == hj2_problem_id).one() # print(result) problem.title = result["title"] problem.background = "内存限制: {} MB\n\n时间限制: {} ms\n\n".format( result["memoryLimit"], result["timeLimit"]) + result["background"] problem.content = result["content"] problem.hint = result["hint"] problem.input_format = result["inputFormat"] problem.output_format = result["outputFormat"] problem.remote_judge_oj = result["remoteOJ"] problem.remote_problem_id = result["remoteProblemID"] problem.example = result["examples"] problem.problem_type = "remote_judge" problem.downloads = [] problem.extra_parameter = [] problem.files = [] problem.provides = [] problem.subtasks = [] db.session.commit() emit("server_response", { "ok": ok, "problemID": hj2_problem_id, "message": "添加成功" }, room=client_session_id, namespace="/ws/remote_judge") return make_response(0, message="done")
def web_assign_user_to_ticket(request): result = {'success': False} #if True: try: user, token = check_auth(request) ticket_id = request.POST['ticket_id'] email = request.POST['email'] unassign = False try: unassign = str2bool(request.POST['unassign']) except: pass assign_user_to_ticket( user = user, ticket_id = ticket_id, email = email, unassign = unassign, ) result['ticket_id'] = ticket_id result['success'] = True except: pass return make_response(result)
def web_create_task(request): """ Get all of the organizations that the user has access to """ result = {'user': None} result['success'] = False #if True: try: user, token = check_auth(request) project_id = request.POST['project_id'] title = request.POST['title'] contents = request.POST['contents'] assigned_id = request.POST['assigned_id'] due = request.POST['due'] task = create_new_task( user = user, project_id = project_id, title = title, contents = contents, assigned_id = assigned_id, due = due, ) result['task_id'] = task.id; result['success'] = True except: pass return make_response(result)
def web_complete_task(request): """ Complete a task """ result = {'user': None} result['success'] = False #if True: try: user, token = check_auth(request) task_id = request.POST['task_id'] task = complete_task(user, task_id); result['task_id'] = task.id result['success'] = True except: pass return make_response(result)
def api_problemtag_remove(id: str): """ 删除某个tag """ db.session.query(Tag).filter_by(id=id).delete() db.session.commit() return make_response(0, message="操作完成")
def admin_get_question_types(request): result = {'success': False} try: #if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') question_types = QuestionTypes.get_all(DBSession) ret_question_types = [] for question_type_id, question_type_text, question_type_description \ in question_types: ret_question_types.append({ 'question_type_id': question_type_id, 'question_type_text': question_type_text, 'question_type_description': question_type_description, }) result['question_types'] = ret_question_types result['success'] = True except: pass return make_response(result)
def web_update_ticket_title(request): result = {'success': False} #if True: try: user, token = check_auth(request) ticket_id = request.POST['ticket_id'] title = request.POST['title'] update_ticket_title( user = user, ticket_id = ticket_id, title = title, ) result['ticket_id'] = ticket_id result['success'] = True except: pass return make_response(result)
def web_close_ticket(request): """ Create a new ticket """ result = {'user': None} result['success'] = False #if True: try: user, token = check_auth(request) ticket_id = request.POST['ticket_id'] ticket = close_ticket(user, ticket_id); result['ticket_id'] = ticket.id result['success'] = True except: pass return make_response(result)
def wiki_config_navigation_remove(id: int): """ 移除导航栏物品 """ db.session.query(WikiNavigationItem).filter_by(id=id).delete() db.session.commit() return make_response(0, message="操作完成")
def web_create_project(request): """ Create a new project """ result = {'user': None} #if True: try: user, token = check_auth(request) name = request.POST['name'] description = request.POST['description'] project = create_new_project( user= user, name = name, description = description, ) result['project_id'] = project.id result['success'] = True except: pass return make_response(result)
def web_assign_user_to_project(request): """ Assign a user to a project """ result = {} #if True: try: user, token = check_auth(request) project_id = int(request.POST['project_id']) email = request.POST['email'] target_user, assignment = assign_user_to_project( user = user, project_id = project_id, email = email, ) if assignment != None: result['assignment_id'] = assignment.id else: result['assignment_id'] = -1; result['project_id'] = project_id result['user_id'] = target_user.id result['success'] = True except: pass return make_response(result)
def web_add_user(request): result = {'success': False} #if True: try: user, token = check_auth(request) organization_id = request.POST['organization_id'] user_type_id = request.POST['user_type_id'] first = request.POST['first'] last = request.POST['last'] email = request.POST['email'] password = request.POST['password'] new_user = add_user( user = user, organization_id = organization_id, user_type_id = user_type_id, first = first, last = last, email = email, password = password, ) result['new_user_id'] = new_user.id result['success'] = True except: pass return make_response(result)
def web_update_ticket_contents(request): result = {'success': False} #if True: try: user, token = check_auth(request) ticket_id = request.POST['ticket_id'] contents = request.POST['contents'] update_ticket_contents( user_id = user.id, ticket_id = ticket_id, contents = contents, ) result['ticket_id'] = ticket_id result['success'] = True except: pass return make_response(result)
def web_authenticate(request): """ End-point to authenticate user, and return a login token """ result = {'user': None} result['success'] = False #if True: try: try: email = request.GET['email'] password = request.GET['password'] except: result['error_text'] = 'Missing Field' result['error_code'] = 1 raise Exception('error') user, token = do_login(email, password) if user == None or token == None: result['error_text'] = 'Invalid Credentials' result['error_code'] = 2 raise Exception('error') result['token'] = token result['user'] = user result['success'] = True except: pass return make_response(result)
def get(self): """ One may either provide a CSV string of `tags` desired, or else provide duplicate query string `tag` values which the API will then put together in a CSV list as needed by IbPy :return: JSON dict of dicts """ choices = {"AccountType", "NetLiquidation", "TotalCashValue", "SettledCash", "AccruedCash", "BuyingPower", "EquityWithLoanValue", "PreviousDayEquityWithLoanValue", "GrossPositionValue", "RegTEquity", "RegTMargin", "SMA", "InitMarginReq", "MaintMarginReq", "AvailableFunds", "ExcessLiquidity", "Cushion", "FullInitMarginReq", "FullMaintMarginReq", "FullAvailableFunds", "FullExcessLiquidity", "LookAheadNextChange", "LookAheadInitMarginReq", "LookAheadMaintMarginReq", "LookAheadAvailableFunds", "LookAheadExcessLiquidity", "HighestSeverity", "DayTradesRemaining", "Leverage"} parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('tags', type=str, help='CSV list of tags from this set: {}'.format(choices), trim=True) parser.add_argument('tag', type=str, action='append', help='Account information you want to see: {error_msg}', trim=True, choices=choices, default=[]) # NOTE beware that flask will reject GET requests if there's a Content-Type in the header with an error: # "message": "The browser (or proxy) sent a request that this server could not understand." args = parser.parse_args() # Make a master list of tags from all possible arguments tags = args['tag'] tags += args['tags'].split(',') if args['tags'] is not None else [] if len(tags) == 0: # No tags were passed, so throw an error return dict(message=dict(tags='Must provide 1 or more `tag` args, and/or a CSV `tags` arg')), 400 # Reduce and re-validate tags = set(tags) if not tags.issubset(choices): return dict(message=dict(tags='All tags must be from this set: {}'.format(choices))), 400 # re-create CSV list tags = ','.join(list(tags)) # debug('TAGS: {}'.format(tags)) return utils.make_response(sync.get_account_summary(tags))
def post(self): """ Places an order with placeOrder(). This requires enough args to create a Contract & and Order: https://www.interactivebrokers.com/en/software/api/apiguide/java/java_socketclient_properties.htm To allow bracketed, a JSON list may be posted in the body with each list object being an order. Arg parsing does not happen in this case http://interactivebrokers.github.io/tws-api/bracket_order.html Note: This implies the JSON list starts with an order to open a position followed by 1-2 orders for closing that position (profit taker, loss stopper) """ # Detect a JSON object being posted # Convert to not-unicode all_args = request.json all_args = json.dumps(all_args) all_args = json.loads(all_args, object_hook=utils.json_object_hook) # If there was no JSON object, then use query string params if all_args is None: parser = parsers.order_parser.copy() for arg in parsers.contract_parser.args: parser.add_argument(arg) args = parser.parse_args() all_args = {k: v for k, v in request.values.iteritems()} # update with validated data for k, v in args.iteritems(): all_args[k] = v return utils.make_response(sync.place_order(all_args))
def post(self): # Detect a JSON object being posted # Convert to not-unicode all_args = request.json all_args = json.dumps(all_args) all_args = json.loads(all_args, object_hook=utils.json_object_hook) return utils.make_response(sync.place_order_oca(all_args))
def get(self): cid = int(request.args.get("cid", 0)) page = int(request.args.get("page", 1)) order = request.args.get("order", 'hot') print cid,page result = self.utils.get_category_list(cid=cid,limit=g.configure.list_item_number,page=page,order=order) return make_response(result, current_page=page)
def admin_get_languages(request): result = {'success': False} #try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') languages = Languages.get_all(DBSession) ret_languages = [] for language_code, name in languages: ret_languages.append({ 'name': name, 'code': language_code, }) result['languages'] = ret_languages result['success'] = True #except: # pass admin_log("HTTP: admin/get_languages.json => {0}".format(json.dumps(result))) return make_response(result)
def admin_get_question_types(request): result = {'success': False} #try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') question_types = QuestionTypes.get_all(DBSession) ret_question_types = [] for question_type_id, question_type_text, question_type_description \ in question_types: ret_question_types.append({ 'question_type_id': question_type_id, 'question_type_text': question_type_text, 'question_type_description': question_type_description, }) result['question_types'] = ret_question_types result['success'] = True #except: # pass admin_log("HTTP: admin/get_question_types.json => {0}".format(json.dumps(result))) return make_response(result)
def admin_publish_story(request): result = {'success': False} ##try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') try: title = request.POST['title'] tags = request.POST['tags'] top_text = request.POST['top_text'] banner_media_id = request.POST['banner_media_id'] contents = request.POST['contents'].encode('UTF-8') top_left_lat = float(request.POST['top_left_lat']) top_left_lng = float(request.POST['top_left_lng']) bottom_right_lat = float(request.POST['bottom_right_lat']) bottom_right_lng = float(request.POST['bottom_right_lng']) language_code = request.POST['language_code'] #use_fense = request.POST['use_fense'] except: result['error_text'] = """\ One or more of the following fields is missing or invalid: title, tags, \ top_text, banner_media_id, contents, top_left_lat, top_left_lng, \ bottom_right_lat, bottom_right_lng, language_code. \ """ raise Exception('invalid/missing field') story = Stories.create_from_http( session = DBSession, token = user.token, title = title, tags = tags, top_text = top_text, media_id = banner_media_id, contents = contents, top_left_lat = top_left_lat, top_left_lng = top_left_lng, bottom_right_lat = bottom_right_lat, bottom_right_lng = bottom_right_lng, #use_fence = use_fense, language_code = language_code, ) result['story_unique_id'] = story.story_unique_id result['success'] = True ##except: ## pass admin_log("HTTP: admin/publish_story.json => {0}".format(json.dumps(result))) return make_response(result)
def admin_update_question(request): result = {'success': False} if True: #try: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') if True: #try: language_code = request.POST['language_code'] question_text = request.POST['question_text'] description = request.POST['description'] question_type = request.POST['question_type'] #except: result['error_text'] = """\ One or more of the following fields is missing or invalid: language_code, \ question_text, description, question_type. \ """ raise Exception('missing field') # answers is a json array of strings answers = [] #try: if True: answers = json.loads(request.POST['answers']) #except: # pass # back fill with empty strings for i in range(len(answers),10): answers.append('') question = Questions.update_from_http( session = DBSession, token = user.token, language_code = language_code, question_text = question_text, description = description, question_type = question_type, answers = answers, ) result['question_id'] = question.question_id result['success'] = True #except: # pass admin_log("HTTP: admin/updatequestion.json => {0}".format(json.dumps(result))) return make_response(result)
def dictionary(): if(request.method == 'GET'): key = request.args.get('key') try: result = dict[key] except KeyError: abort(404) return make_response(result) elif(request.method == 'POST'): data = json.loads(request.data) try: key = data['key'] value = data['value'] except KeyError: abort(400) if(dict.get(key) != None): abort(409) else: dict.update({key : value}) return make_response(value) elif(request.method == 'PUT'): data = json.loads(request.data) try: key = data['key'] value = data['value'] except KeyError: abort(400) if(dict.get(key) == None): abort(404) else: dict[key] = value return make_response(value) elif(request.method == 'DELETE'): data = json.loads(request.data) try: key = data['key'] except KeyError: abort(404) if(dict.get(key) != None): dict.pop(key) return make_response(None)
def admin_update_assignment(request): result = {'success': False} #try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') if True: #try: assignment_id = request.POST['assignment_id'] #client_id = request.POST['client_id'] life_time = int(request.POST['life_time']) #questions = json.loads(request.POST['questions']) top_left_lat = float(request.POST['top_left_lat']) top_left_lng = float(request.POST['top_left_lng']) bottom_right_lat = float(request.POST['bottom_right_lat']) bottom_right_lng = float(request.POST['bottom_right_lng']) #use_fence = boolean(request.POST['use_fence']) #except: result['error_text'] = """\ One or more of the following fields is missing or invalid: life_time, \ top_left_lat, top_left_lng, bottom_right_lat, bottom_right_lng. \ """ raise Exception('invalid/missing field') # create assignment assignment = Assignments.update_assignment( session = DBSession, assignment_id = assignment_id, life_time = life_time, top_left_lat = top_left_lat, top_left_lng = top_left_lng, bottom_right_lat = bottom_right_lat, bottom_right_lng = bottom_right_lng, #use_fence = use_fence, ) result['assignment_id'] = assignment.assignment_id result['success'] = True #except: # pass admin_log("HTTP: admin/update_assignment.json => {0}".format(json.dumps(result))) return make_response(result)
def admin_create_user(request): result = {'success': False} ##try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') #try: user_type_text = request.POST['user_type'] user_name = request.POST['user_name'] # password = request.POST['password'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] organization = request.POST['organization'] #except: result['error_text'] = """\ One or more of the following fields is missing or invalid: user_type, \ user_name, password, first_name, last_name, email, organization. \ """ raise Exception('invalid/missing field') user_type = UserTypes.get_from_name(DBSession, user_type_text) user = Users.create_new_user( session = DBSession, user_type_id = user_type.user_type_id, client_id = str(uuid.uuid4()), ) user = Users.verify_user( session = DBSession, client_id = user.client_id, user_name = user_name, # password = password, first_name = first_name, last_name = last_name, email = email, ) result['user_id'] = user.user_id result['success'] = True ##except: ## pass return make_response(result)
def admin_get_my_collection(request): result = {'success': False} ##try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') # #try: # if True: # name = request.POST['name'] # description = request.POST['description'] # tags = request.POST['tags'] # #except: # result['error_text'] = """\ #One or more of the following fields is missing or invalid: name, \ #description, tags. \ #""" # raise Exception('Missing or invalid field.') collections = Collections.get_all_from_http( session = DBSession, token = user.token, ) ret_collections = [] for collection_id, user_id, collection_datetime, name, description, \ tags, enabled in collections: ret_collections.append({ 'collection_id': collection_id, 'collection_datetime': str(collection_datetime), 'name': name, 'decription': description, 'tags': tags, 'enabled': enabled, }) result['collections'] = ret_collections result['success'] = True ##except: ## pass admin_log("HTTP: admin/get_my_collections.json => {0}".format(json.dumps(result))) return make_response(result)
def admin_create_message(request): result = {'success': False} #try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') try: to_client_id = request.POST['to_client_id'] subject = request.POST['subject'] text = request.POST['text'] except: result['error_text'] = """\ One or more of the following fields is missing or invalid: to_client_id, \ subject, text. """ raise Exception('invalid/missing field') parent_message_id = None try: parent_message_id = request.POST['parent_message_id'] except: pass message = Messages.create_message_from_http( session = DBSession, from_token = user.token, to_client_id = to_client_id, subject = subject, text = text, parent_message_id = parent_message_id, ) if message != None: result['message_id'] = message.message_id result['success'] = True #except: # pass admin_log("HTTP: admin/create_message.json => {0}".format(json.dumps(result))) return make_response(result)
def get_messages(request): result = {'success': False} # try: if True: client_id = None try: client_id = request.GET['client_id'] except: result['error_text'] = "Missing or invalid field." raise Exception("missing/invalid field") messages = Messages.get_messages_from_client_id(DBSession, client_id) ret_messages = [] for message_id, from_user_id,to_user_id,message_datetime, \ parent_message_id,subject,text, was_read,from_organization, \ from_first_name,from_last_name in messages: ret_messages.append({ 'message_id': message_id, 'from_user_id': from_user_id, 'to_user_id': to_user_id, 'from_organization': from_organization, 'from_first_name': from_first_name, 'from_last_name': from_last_name, 'message_datetime': str(message_datetime), 'parent_message_id': parent_message_id, 'subject': subject, 'text': text, 'was_read': was_read, }) result['messages'] = ret_messages result['success'] = True # except: # pass event_type = 'http_request' event_details = { 'client_id': client_id, 'method': 'get_messages.json', 'message_count': len(ret_messages), 'result': result, } client_log = EventLogs.log(DBSession,client_id,event_type,json.dumps(event_details)) return make_response(result)
def get_local_posts(request): result = {'success': False} status_code = 200 #try: if True: success, error_text, language_code, lat, lng, \ client = client_utils.register_client(request) if success == False: raise Exception(error_text) try: start = 0 if 'start' in request.GET: start = int(float(request.GET['start'])) count = 75 if 'count' in request.GET: count = int(float(request.GET['count'])) except: status_code = 403 raise Exception("Invalid input.") posts = client_utils.get_approved_posts( client_id = client.client_id, language_code = language_code, lat = lat, lng = lng, start = start, count = count, ) result['posts'] = posts result['success'] = True #except Exception, e: # status_code = 400 # result['error_text'] = str(e) client_utils.log_client_action( client = client, url = 'get_approved_posts.json', lat = lat, lng = lng, request = request, result = result, success = success, ) return utils.make_response(result, status_code)
def register(): form = RegisterForm(request.form) if request.method == 'POST': if form.validate_on_submit(): # if form.validate_username(): try: user = form.save() except IntegrityError as e: return make_response(422, message='User name is existed') login_user(user) return url_for('busad.upload') try: return render_template('register.html', title='Register', form=form) except TemplateNotFound: abort(404)
def login(): form = LoginForm() if request.method == 'POST': if form.validate_on_submit(): user, authenticated = User.authenticate(form.username.data, form.password.data) if user and authenticated: login_user(user, remember=form.remember_me.data) return url_for('map.devices_on_map') else: return make_response(422, message='Incorrect username or password.') return render_template('login.html', title='Sign In', form=form)
def web_database_dump(request): result = {'success': False} #if True: try: user, token = check_auth(request) result['database'] = export_database(user.id) result['success'] = True except: pass return make_response(result)
def admin_register_post_view(request): result = {'success': False} ##try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') #try: post_id = request.POST['post_id'] #except: result['error_text'] = """\ One or more of the following fields is missing or invalid: post_id. \ """ raise Exception('invalid/missing field') post = Posts.get_from_post_id( session = DBSession, post_id = post_id, ) notification = Notifications.create_notification( session = DBSession, user_id = post.user_id, notification_type = 'post_viewed', payload = json.dumps({ 'organization': user.organization, }) ) result['post_id'] = post_id result['notification_id'] = notification.notification_id result['success'] = True ##except: ## pass admin_log("HTTP: admin/register_post_view.json => {0}".format(json.dumps(result))) return make_response(result)
def web_create_ticket(request): """ Create a new ticket """ result = {'user': None} result['success'] = False #if True: try: user, token = check_auth(request) project_id = request.POST['project_id'] title = request.POST['title'] contents = request.POST['contents'] assigned_id = request.POST['assigned_user_id'] ticket_type_id = None #1 # request.POST['ticket_type_id'] if title.strip()== '': raise Exception('no title') if assigned_id == '' or assigned_id == None \ or not assigned_id.isdigit(): assigned_id = None ticket = create_new_ticket( user = user, project_id = project_id, ticket_type_id = ticket_type_id, title = title, contents = contents, assigned_id = assigned_id, ) if ticket == None: raise Exception('ticket creation error') result['ticket_id'] = ticket.id result['success'] = True except: pass return make_response(result)
def web_create_ticket_comment(request): """ Get all of the organizations that the user has access to """ #result = {'user': None} result = {'success': False} if True: #try: user, token = check_auth(request) #author_id = request.POST['author_id'] #project_id = request.POST['project_id'] ticket_id = request.POST['ticket_id'] contents = request.POST['contents'] close = False try: close = str2bool(request.POST['close']) except: pass if contents.strip() == '': raise Exception('no contents to comment') ticket = get_ticket(user.id, ticket_id) if ticket == None: raise Exception('invalid ticket id') ticket_comment = create_new_ticket_comment( user = user, ticket_id = ticket_id, contents = contents, close = close, ) result['ticket_comment_id'] = ticket_comment.id result['success'] = True #except: # pass return make_response(result)
def admin_create_collection(request): result = {'success': False} #try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') #try: if True: name = request.POST['name'] description = request.POST['description'] tags = request.POST['tags'] #except: # result['error_text'] = """\ #One or more of the following fields is missing or invalid: name, \ #description, tags. \ #""" # raise Exception('Missing or invalid field.') collection = Collections.create_new_collection_from_http( session = DBSession, token = user.token, name = name, description = description, tags = tags, ) result['collection_id'] = collection.collection_id result['success'] = True #except: # pass admin_log("HTTP: admin/create_collection.json => {0}".format(json.dumps(result))) return make_response(result)
def admin_remove_post_from_collection(request): result = {'success': False} #try: if True: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') #try: if True: collection_id = int(request.POST['collection_id']) post_id = int(request.POST['post_id']) #except: result['error_text'] = """\ One or more of the following fields is missing or invalid: collection_id, \ post_id. \ """ raise Exception('Missing or invalid field.') successfully_removed = Collections.remove_post_from_collection( session = DBSession, collection_id = collection_id, post_id = post_id, ) if successfully_removed: result['post_id'] = post_id result['collection_id'] = collection_id result['success'] = True else: result['error_text'] = 'Post does not exist within collection.' #except: # pass admin_log("HTTP: admin/remove_post_from_collection.json => {0}".format(json.dumps(result))) return make_response(result)
def admin_get_client_logs(request): """ Returns all of the event logs in the system. Optionally by client_id. """ result = {'succes' :False} try: token = None valid_token = False valid, user = check_token(request) if valid == False: result['error_text'] = "Missing or invalid 'token' field in request." raise Exception('invalid/missing token') client_id = None try: client_id = request.GET['client_id'] except: pass logs = EventLogs.get_all(DBSession) ret_logs = [] for log in logs: ret_logs.append({ 'event_log_id': log.event_log_id, 'user_id': log.user_id, 'event_type': log.event_type, 'event_datetime': str(log.event_datetime), 'details': json.loads(log.details), }) result['logs'] = ret_logs result['success'] = True except: pass return make_response(result)