def f_panel(): if request.method == "GET": if "logged_in" in session: return render_template("panel.html") return redirect("/login") else: abort(405)
def event_text(): start_time = time() user_id = request.json['user_id'][:6] if request.json[ 'user_id'] is not None else str(None) if request.json['group_id'] is not None: user_id += '@%s' % request.json['group_id'][:4] print(user_id, '>', request.json['message']) try: reply_message = event_text_main(**request.json) except Exception as e: bots[request.json['bot_id']].reply_message(request.json['reply_token'], '愛醬出錯了!') e_type, e_value, e_traceback = sys.exc_info() bots['admin'].send_message( cfg['admin_line'], '<愛醬BUG>\ntype:%s\nvalue:%s\nfile:%s\nfunc:%s\nline:%s' % ( str(e_type), str(e_value), str(e_traceback.tb_frame.f_code.co_filename), str(e_traceback.tb_frame.f_code.co_name), str(e_traceback.tb_lineno), )) abort(400) if len(reply_message) == 0: abort(400) print(user_id, '<', reply_message, '(耗時%.3fs)' % (time() - start_time)) return ''
def f_actions_create(): if request.method == "GET": if "logged_in" in session: return render_template("action_form.html") return redirect("/login") else: abort(405) # Method Not Allowed
def f_history(): if request.method == "GET": action = actions.Action() history = action.history() return dumps(history) else: abort(405)
def delete_post(post_id): post = Post.query.get_or_404(post_id) if post.author != current_user: abort(403) # How to execute the delete command??? flash('Post has been deleted!', 'info') return redirect(url_for('home'))
def getLector(lectorId): lector = Lector.query.filter(Lector.id == lectorId).first() if lector is not None: return jsonify(lector.serialized()) else: abort(404)
def delete(self, contact_id): "delete contact" contact = models.Contact.query.get(contact_id) if not contact: abort(404, message="Contact {} doesn't exist".format(contact_id)) db.session.delete(contact) db.session.commit() return "", 204
def change_profile_pic(): s = current_identity if s == None: abort(404) avatar = b64decode(request.json['Avatar']) s.Avatar = avatar db.session.commit() return jsonify({'status': 'successful'}), 201
def f_actions(): if request.method == "GET": if "logged_in" in session: action = actions.Action() list_actions = action.show() return dumps(list_actions) abort(401) # Not Authorized (must authenticate) else: abort(405) # Method Not Allowed
def f_actions_run(action_id): if request.method == "GET": if "logged_in" in session: username = request.cookies.get("username") action = actions.Action() result = action.run(action_id, username) return str(result) return redirect("/login") else: abort(405) # Method Not Allowed
def f_actions_update(action_id): if request.method == "GET": if "logged_in" in session: api_uri = "http://127.0.0.1:5000/api/v1.0/actions" + "/" + action_id update_action = actions.Action() r = requests.get(api_uri) return render_template("action_form.html", action_data=r.text) return redirect("/login") else: abort(405) # Method Not Allowed
def deleteBell(id): if request.method != 'DELETE': abort(400) code = bellsContent.delete_with_id(id) if code == StatusCode.ok: return jsonify({}) return jsonify(ErrorHelper.make_response_for_code(code))
def genrePage(): """ Home page """ if request.args is not None and len(request.args) > 0: genre = request.args.get('genre') if genre is '': abort(400, messages.input_empty) return redirect(url_for('trackList', genre=genre)) genre_list = app_service.getGenreTypeList() return render_template(constants.enter_genre_template, genre_list=genre_list)
def trackList(genre): """ list the popular tracks """ try: content = app_service.listTopTracks(genre) return render_template(constants.track_list_page_template, genre=genre, content=content) except Exception as ex: print(str(ex)) abort(400, messages.general_error)
def give_points(self, event_id, user_id): event = self.events_col.find_one({"_id": ObjectId(event_id)}) points = event['points'] success = give_influence_points(points, user_id) if success.status_code > 299: if success.status_code < 500: abort(success.status_code, "Failed to give points to user, verify that user " + user_id + " exists.") else: abort(success.status_code, "Failed to give points to user.") return
def createLector(): json = {} if request.headers['Content-Type'] == 'application/json': json = request.get_json().copy() else: abort(400) lector, code = lectorsContent.create_from_json(json) if lector is None: return jsonify(ErrorHelper.make_response_for_code(code)) else: return jsonify(lector.serialized())
def recycling(): s = current_identity if not request.json or s == None: abort(400) print(request.json) if request.json['recyclable']: recyclable = request.json['recyclable'] bin_colour = recyclable_classes[recyclable] # Make request to server ## --------------------- ## HOST = '127.0.0.1' # The server's hostname or IP address PORT = 5000 # The port used by the server data = None with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((HOST, PORT)) bin_number = bin_code_numbers[bin_colour] sock.sendall((bin_number.encode())) data = sock.recv(1024) print('Received', data.decode()) sock.close() if data.decode() == 'False': abort(400) if bin_colour == "Blue": s.BlueRecycled += 1 if bin_colour == "Orange": s.OrangeRecycled += 1 if bin_colour == "Brown": s.BrownRecycled += 1 house_id = s.HouseID house = House.query.filter(House.id == house_id).first() if house != None: if bin_colour == "Blue": house.BlueRecycled += 1 if bin_colour == "Orange": house.OrangeRecycled += 2 if bin_colour == "Brown": house.BrownRecycled += 1 recyclable = Recycable.query.filter(Recycable.Name == recyclable).first() recyclable.TotalRecycled += 1 db.session.commit() time.sleep(5) return jsonify({'status': 'submitted', 'points': 1}), 200
def createLesson(group_id): json = {} if request.headers['Content-Type'] == 'application/json': json = request.get_json().copy() else: abort(400) json[Key.group_id] = group_id lesson, code = lessonsContent.create_from_json(json) if lesson is None: return jsonify(ErrorHelper.make_response_for_code(code)) else: return jsonify(lesson.serialized)
def callback(): signature = request.headers['X-Line-Signature'] body = request.get_data(as_text=True) app.logger.info("Request body: " + body) print(body) try: handler.handle(body, signature) except InvalidSignatureError: abort(400) return 'OK'
def update_post(post_id): post = Post.query.get_or_404(post_id) if post.author != current_user: abort(403) form = PostForm() if form.validate_on_submit(): post.save(form.title.data, form.content.data) flash('Post updated!', 'info') return redirect(url_for('post', post_id=post.id)) elif request.method == 'GET': form.title.data = post.title form.content.data = post.content return render_template('create_post.html', title='Update Post', form=form)
def put(self, contact_id): "update contact" args = parser.parse_args() contact = models.Contact.query.get(contact_id) if not contact: abort(404, message="Contact {} doesn't exist".format(contact_id)) if args.name: contact.name = args.name if args.email: contact.email = args.email if args.phone: contact.phone = args.phone db.session.commit() return marshal(contact, contact_fields), 201
def event_text(): start_time = time() try: reply_message = EventText(**request.json).run() except Exception as e: bots[request.json['bot_id']].reply_message(request.json['reply_token'], '愛醬出錯了!\n作者可能會察看此錯誤報告') bots['admin'].send_message(cfg['admin_line'], '<愛醬BUG>\n%s' % str(e)) raise e if len(reply_message) == 0: abort(400) return '\n'.join(reply_message)
def createGroup(): if request.method != 'POST': abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) json = request.get_json().copy() group, code = groupsContent.add_from_json(json) if code == StatusCode.ok: return jsonify(group.serialized()) return jsonify(ErrorHelper.make_response_for_code(code))
def f_index(): if request.method == "GET": if "logged_in" in session: return redirect("/panel") return redirect("/login") else: return abort(405)
def archive(self, id, token): event = self.events_col.find_one({"_id": ObjectId(id)}) if event is None: abort(404, self.event_not_found_error) allowed = is_allowed(token, event['organization_id'], 'closeEvent') if allowed: self.events_col.update_one({'_id': ObjectId(id)}, {"$set": { "available": False }}, upsert=True) self.update_search_service('available', False, id) return self.get_by_id(id) else: abort(401, self.authorization_error)
def Login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] try: user = User.query.filter(User.username == username).first() if not user: status_index = 'Usuário não cadastrados' return render_template('index.html', status_index=status_index) elif password == user.password: return f"{username} é um cadastrado!!!" elif password != user.password: status_index = 'Password inválido' return render_template('index.html', status_index=status_index) except NameError: return NameError else: abort(404)
def callback(secret, token): if token not in bots: bots[token] = LineBot(push=False, token=token) # get X-Line-Signature header value signature = request.headers['X-Line-Signature'] # get request body as text body = request.get_data(as_text=True) #logger.info("Request body: " + body) # handle webhook body try: getHandle(token, secret).handle(body, signature) except InvalidSignatureError: abort(400) return 'ok'
def make_prediction(): if request.json != None and 'recycable_image' in request.json: img = b64decode(request.json['recycable_image']) prediction = inference.make_inference(img) # file format: prediction_md5sum_date_time.jpg # TODO: when deploying the webapp, place data folder outside of web root directory to prevent remote code execution filename = str( current_identity.id) + '_' + prediction + "_" + md5(img).hexdigest( ) + "_" + datetime.now().strftime("%Y-%m-%d_%H-%M") + '.jpg' filepath = "data/" + filename with open(filepath, 'wb') as f: f.write(img) return jsonify({'prediction': prediction}), 200 else: abort(400)
def f_login(): if request.method == "GET": return render_template("login.html") elif request.method == "POST": username = request.form["username"] password = request.form["password"] user = users.User() status = user.login(username, password) if status == 0: session["logged_in"] = True response = make_response(redirect('/panel')) response.set_cookie('username', username) return response else: print("Status:", status) message = "Check Username and Password." return render_template("login.html", login_status=message) else: abort(405)
def f_login(): """ Processing request. """ # Verifies if the request was transmited via Proxy or not. client_ip = None if request.environ.get('HTTP_X_REAL_IP') is not None: client_ip = request.environ.get('HTTP_X_REAL_IP') else: client_ip = request.environ.get('REMOTE_ADDR') if request.method == 'GET': log.info('%s %s %s', "/login", "GET", client_ip) return render_template("login.html") elif request.method == 'POST': log.info('%s %s %s', "/login", "POST", client_ip) user_data = user_data_parser(request.headers.get('User-Agent')) username = request.form['username'] password = request.form['password'] db = mongodb.Connector() login = db.login(username, password) if login == 0: session_id = db.add_session(username, client_ip, user_data) if len(str(session_id)) == 24: fw = iptables.Worker() allow = fw.add_rule(client_ip) if allow == 0: log.info('%s %s %s', "login", "OK", client_ip) session["SessionID"] = str(session_id) return redirect("/welcome") else: msg = "Server Error (firewall)" return render_template("login.html", login_msg=msg) else: msg = "Server Error (session)" return render_template("login.html", login_msg=msg) elif login == 1 or login == 2: msg = "Wrong Credentials!" return render_template("login.html", login_msg=msg) else: msg = "Server Error (login)" return render_template("login.html", login_msg=msg) else: abort(405) # 405: Method Not Allowed
def update(self, id, field, value, token): event = self.events_col.find_one({"_id": ObjectId(id)}) if event is None: abort(404, self.event_not_found_error) # TODO: set correct action allowed = is_allowed(token, event['organization_id'], 'setNumberOfEventPoints') # TODO: validate with the Event obj if allowed: self.events_col.update_one({'_id': ObjectId(id)}, {"$set": { field: value }}, upsert=True) self.update_search_service(field, value, id) return self.get_by_id(id) else: abort(401, self.authorization_error)
def create(self, json_data, token): event = json_to_event(json_data) allowed = is_allowed(token, event['organization_id'], 'createEvent') if allowed: # add event event_id = str( self.events_col.insert_one(event.__original__).inserted_id) # link event to organization linking_to_organization = add_event_to_organization( event['organization_id'], event_id) if linking_to_organization.status_code > 299: self.events_col.remove({"_id": ObjectId(event_id)}) abort(linking_to_organization.status_code, self. event_created_organization_error) # or original content # send event to search service add_to_service = add_new_event_to_search(event, event_id) if add_to_service.status_code > 299: abort( add_to_service.status_code, self.event_to_search_service_error) # or original content # if we are this far, everything is fine result = {'event_id': event_id} return to_json(result) else: abort(401, self.authorization_error)
def createBell(): if request.method != 'POST': abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) json = request.get_json().copy() bell, code = bellsContent.add_from_json(json) if code is not None and code != StatusCode.ok: return jsonify(ErrorHelper.make_response_for_code(code)) if bell is None: abort(400) return jsonify(bell.serialized())
def register_student(): if not request.json: abort(400) StudentName = None HouseID = None email = None password = None try: StudentName = request.json['StudentName'] HouseID = request.json['HouseID'] email = request.json['Email'] password = request.json['Password'] except: abort(400) if Student.query.filter(Student.Email == email).first() != None: abort(403) avatar = None if request.json['Avatar']: avatar = request.json['Avatar'] avatar = b64decode(avatar) s = Student(StudentName=StudentName, HouseID=HouseID, Email=email, BrownRecycled=0, BlueRecycled=0, OrangeRecycled=0, TotalRecycled=0, Avatar=avatar) s.set_password(password) db.session.add(s) db.session.commit() return jsonify(s.as_dict()), 201
def f_actions(action_id=None): if request.method == "POST": # Create name = request.form.get("name") command = request.form.get("command") new_action = actions.Action() result = new_action.create(name, command) return str(result) elif request.method == "GET": # Read if action_id is None: created_actions = actions.Action() result = created_actions.show() return str(result) else: created_action = actions.Action() result = created_action.show(action_id) return str(result) elif request.method == "PUT": # Update if actions_id is not None: name = request.form.get("name") command = request.form.get("command") update_action = actions.Actions() result = update_action.update(action_id, name, command) return str(result) else: abort(400) # Bad Request elif request.method == "DELETE": # Delete if action_id is not None: delete_action = actions.Actions() result = delete_action.delete(action_id) return str(result) else: abort(400) # Bad Request else: abort(405) # Method Not Allowed
def get_by_id(self, id): event = self.events_col.find_one({"_id": ObjectId(id)}) if event is not None: return to_json(format_ObjectId(event)) else: abort(404, self.event_not_found_error)