def collection_get(self): if "Accept" in self.request.headers and "application/json" not in self.request.headers["Accept"]: return current_app.make_response(("application/json", 406, [("Content-Type", "text/plain")])) objs = self.get_collection() collection = self.collection_for_json(objs) if "If-None-Match" in self.request.headers and self.request.headers["If-None-Match"] == self.etag(collection): return current_app.make_response(("", 304, [("Etag", self.etag(collection))])) return self.json_success_response(collection, self.collection_last_modified())
def collection_post(self): if self.request.headers["Content-Type"] != "application/json": return current_app.make_response(("Content-Type must be application/json", 415, [])) obj = self.model() src = UnicodeSafeJsonWrapper(self.request.json) root_attribute = self.model._inflector.table_singular try: src = src[root_attribute] except KeyError, e: return current_app.make_response(('Required attribute "{0}" not found'.format(root_attribute), 400, []))
def collection_post(self): if self.request.headers['Content-Type'] != 'application/json': return current_app.make_response(( 'Content-Type must be application/json', 415,[])) obj = self.model() src = UnicodeSafeJsonWrapper(self.request.json) try: src = src[self.model_name] except KeyError, e: return current_app.make_response(( 'Required attribute "{0}" not found'.format(self.model_name), 400, []))
def related_objects(): obj_id = request.args['oid'] obj_type = request.args['otype'] far_type = request.args['related_model'] related_object_results = RelatedObjectResults(obj_id, obj_type, far_type) results = related_object_results.get_results() current_app.make_response(( 'application/json', 200, [('Content-Type', 'application/json')])) return as_json(results)
def export_file(export_to, filename, csv_string=None): """Export file to csv file or gdrive file""" if export_to == "gdrive": gfile = fa.create_gdrive_file(csv_string, filename) headers = [('Content-Type', 'application/json'), ] return current_app.make_response((json.dumps(gfile), 200, headers)) if export_to == "csv": headers = [ ("Content-Type", "text/csv"), ("Content-Disposition", "attachment"), ] return current_app.make_response((csv_string, 200, headers)) raise wzg_exceptions.BadRequest(app_errors.BAD_PARAMS)
def export_file(export_to, filename, csv_string=None): """Export file to csv file or gdrive file""" if export_to == "gdrive": gfile = fa.create_gdrive_file(csv_string, filename) headers = [('Content-Type', 'application/json'), ] return current_app.make_response((json.dumps(gfile), 200, headers)) if export_to == "csv": headers = [ ("Content-Type", "text/csv"), ("Content-Disposition", "attachment; filename='{}'".format(filename)), ] return current_app.make_response((csv_string, 200, headers)) raise BadRequest("Bad params")
def users(): """ Undocumented API path required for docker login when apache configured for auth See get_post_users() https://github.com/docker/docker-registry/blob/master/docker_registry/index.py """ if request.method == 'GET': response = current_app.make_response(json.dumps('OK')) response.headers['X-Docker-Registry-Standalone'] = True return response response = current_app.make_response((json.dumps('User Created'), 201)) response.headers['Content-Type'] = 'application/json' response.headers['X-Docker-Registry-Standalone'] = True return response
def get(self, id): obj = self.get_object(id) if obj is None: return self.not_found_response() if "Accept" in self.request.headers and "application/json" not in self.request.headers["Accept"]: return current_app.make_response(("application/json", 406, [("Content-Type", "text/plain")])) if not permissions.is_allowed_read(self.model.__name__, obj.context_id): raise Forbidden() object_for_json = self.object_for_json(obj) if "If-None-Match" in self.request.headers and self.request.headers["If-None-Match"] == self.etag( object_for_json ): return current_app.make_response(("", 304, [("Etag", self.etag(object_for_json))])) return self.json_success_response(object_for_json, self.modified_at(obj))
def collection_get(self): if 'Accept' in self.request.headers and \ 'application/json' not in self.request.headers['Accept']: return current_app.make_response(( 'application/json', 406, [('Content-Type', 'text/plain')])) objs = self.get_collection() collection = self.collection_for_json(objs) if 'If-None-Match' in self.request.headers and \ self.request.headers['If-None-Match'] == self.etag(collection): return current_app.make_response(( '', 304, [('Etag', self.etag(collection))])) return self.json_success_response( collection, self.collection_last_modified())
def handle_export_request(): try: with benchmark("handle export request"): data = parse_export_request() objects = data.get("objects") export_to = data.get("export_to") query_helper = QueryHelper(objects) ids_by_type = query_helper.get_ids() with benchmark("Generate CSV array"): converter = Converter(ids_by_type=ids_by_type) csv_data = converter.to_array() with benchmark("Generate CSV string"): csv_string = generate_csv_string(csv_data) with benchmark("Make response."): object_names = "_".join(converter.get_object_names()) filename = "{}.csv".format(object_names) if export_to == "gdrive": credentials = get_credentials() http_auth = credentials.authorize(httplib2.Http()) drive_service = discovery.build('drive', 'v3', http=http_auth) # make export to sheets file_metadata = { 'name': filename, 'mimeType': 'application/vnd.google-apps.spreadsheet' } media = http.MediaInMemoryUpload(csv_string, mimetype='text/csv', resumable=True) gfile = drive_service.files().create( body=file_metadata, media_body=media, fields='id, name, parents').execute() headers = [('Content-Type', 'application/json'), ] return current_app.make_response((json.dumps(gfile), 200, headers)) if export_to == "csv": headers = [ ("Content-Type", "text/csv"), ("Content-Disposition", "attachment; filename='{}'".format(filename)), ] return current_app.make_response((csv_string, 200, headers)) except BadQueryException as exception: raise BadRequest(exception.message) except: # pylint: disable=bare-except logger.exception("Export failed") raise BadRequest("Export failed due to server error.")
def put(self, id): obj = self.get_object(id) if obj is None: return self.not_found_response() if self.request.headers["Content-Type"] != "application/json": return current_app.make_response(("Content-Type must be application/json", 415, [])) header_error = self.validate_headers_for_put_or_delete(obj) if header_error: return header_error src = UnicodeSafeJsonWrapper(self.request.json) root_attribute = self.model._inflector.table_singular try: src = src[root_attribute] except KeyError, e: return current_app.make_response(('Required attribute "{0}" not found'.format(root_attribute), 400, []))
def get(self, id): obj = self.get_object(id) if obj is None: return self.not_found_response() if 'Accept' in self.request.headers and \ 'application/json' not in self.request.headers['Accept']: return current_app.make_response(( 'application/json', 406, [('Content-Type', 'text/plain')])) object_for_json = self.object_for_json(obj) if 'If-None-Match' in self.request.headers and \ self.request.headers['If-None-Match'] == self.etag(object_for_json): return current_app.make_response(( '', 304, [('Etag', self.etag(object_for_json))])) return self.json_success_response( self.object_for_json(obj), self.modified_at(obj))
def get(self, id): with benchmark("Query for object"): obj = self.get_object(id) if obj is None: return self.not_found_response() if 'Accept' in self.request.headers and \ 'text/html' not in self.request.headers['Accept']: return current_app.make_response(( 'text/html', 406, [('Content-Type', 'text/plain')])) if not permissions.is_allowed_read(self.model.__name__, obj.id, obj.context_id): raise Forbidden() if not permissions.is_allowed_view_object_page_for(obj): raise Forbidden() with benchmark("Render"): rendered_template = self.render_template_for_object(obj) # FIXME: Etag based on rendered output, or object itself? # if 'If-None-Match' in self.request.headers and \ # self.request.headers['If-None-Match'] == self.etag(object_for_json): # return current_app.make_response(( # '', 304, [('Etag', self.etag(object_for_json))])) return rendered_template
def repo_images(repo_id): """ Returns a json document containing a list of image IDs that are in the repository with the given repo_id. Adds the "X-Docker-Endpoints" header. :param repo_id: unique ID for the repository. May contain 0 or 1 of the "/" character. :type repo_id: basestring :return: json string containing a list of image IDs :rtype: basestring """ # a valid repository ID will have zero or one slash if len(repo_id.split('/')) > 2: raise exceptions.HTTPError(httplib.NOT_FOUND) images_in_repo = repository.get_images_for_repo(repo_id) response = current_app.make_response(images_in_repo) # use the configured endpoint if any, otherwise default to the host of # the current request. configured_endpoint = current_app.config.get(config.KEY_ENDPOINT) response.headers['X-Docker-Endpoints'] = configured_endpoint or request.host return response
def search(): terms = request.args.get('q') permission_type = request.args.get('__permission_type', 'read') permission_model = request.args.get('__permission_model', None) if terms is None: return current_app.make_response(( 'Query parameter "q" specifying search terms must be provided.', 400, [('Content-Type', 'text/plain')], )) should_group_by_type = request.args.get('group_by_type', '') should_group_by_type = should_group_by_type.lower() == 'true' should_just_count = request.args.get('counts_only', '') should_just_count = should_just_count.lower() == 'true' types = request.args.get('types', ''); types = [t.strip() for t in types.split(',') if len(t.strip()) > 0] if len(types) == 0: types = None if should_just_count: return do_counts(terms, types) if should_group_by_type: return group_by_type_search(terms, types) return basic_search(terms, types, permission_type, permission_model)
def put(self, id): obj = self.get_object(id) if obj is None: return self.not_found_response() if self.request.headers['Content-Type'] != 'application/json': return current_app.make_response(( 'Content-Type must be application/json', 415,[])) header_error = self.validate_headers_for_put_or_delete(obj) if header_error: return header_error src = UnicodeSafeJsonWrapper(self.request.json) try: src = src[self.model_name] except KeyError, e: return current_app.make_response(( 'Required attribute "{0}" not found'.format(self.model_name), 400, []))
def make_json_response(data, status_code=200, add_headers=None): """Make json response from response data. """ if data is not None: if current_app.config['AUDIT_VERBOSITY'] > 0: if status_code >= 400 and 'message' in data: g.audit_data['message'] = data['message'] if current_app.config.get('PRETTY_PRINT_JSON'): data = json.dumps(data, indent=4, sort_keys=True, default=_json_default) data += '\n' else: data = json.dumps(data, separators=(',', ':'), default=_json_default) else: data = "" response = current_app.make_response((data, status_code)) if add_headers: for header, value in add_headers: response.headers[header] = value response.headers['Content-Type'] = _JSON if is_authenticated(): response.headers['X-GD-Altai-Implementation'] = _IMPLEMENTATION return response
def show_raw_results(campaign_id): campaign = CampaignController.get(campaign_id) if 'lastUpdate' in request.args: time = datetime.datetime.utcfromtimestamp(float(request.args['lastUpdate'])) results = ResultsController.get_all_since_time(campaign_id, time) else: results = ResultsController.get_all(campaign_id) if len(results) > 0: first_result = results[0] timestamp = (first_result.date_added - datetime.datetime(1970, 1, 1)).total_seconds() else: timestamp = (datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() results_arr = [] for result in results: result_obj = msgpack.unpackb(result.data) dataset_obj = msgpack.unpackb(result.dataset.data) results_arr.append({'dataset': dataset_obj, 'result': result_obj}) data = msgpack.packb({'timestamp' : timestamp, 'results' : results_arr}) res = current_app.make_response(data) filename = safe_filename(campaign.title) + '_results_' + str(math.floor(timestamp)) + '.msgpack' res.headers.add('Content-Disposition', 'attachment;filename=' + filename) res.mimetype = 'application/octet-stream' return res
def auth_logout(): destroy_session() # TODO: is there a better way to unset cookies in Flask? response = current_app.make_response(redirect(url_for("spa_web.index"))) # response.set_cookie('aid', '', expires=0) return response
def logout(): logout_link = 'https://login.uniba.sk/logout.cgi?{}'.format(url_for('index', _external=True)) response = current_app.make_response(redirect(logout_link)) if 'COSIGN_SERVICE' in request.environ: response.set_cookie(request.environ['COSIGN_SERVICE'], value='', expires=1, path='/', secure=True) return response
def get(self): state = "" if 'orig_url' in request.args: # we'll later redirect the user back the page they were on after # logging in state = base64.urlsafe_b64encode(request.args['orig_url'].encode('utf-8')) # If we're in the PP world, try to log in based on that header. if current_app.config.get('PP_AUTH', False): email = request.headers.get('X-PP-USER') if email is None: return current_app.make_response(('Expected PP auth!', 401, {})) # All we need to do is make sure that the user exists in the # database for get_current_user() to find. user, _ = get_or_create(User, where={ 'email': email, }) return get_orig_url_redirect(state) # if refresh token available, log in without prompt if 'refresh_token' in request.cookies and 'refresh_email' in request.cookies: resp = auth_with_refresh_token(request.cookies) email = Fernet(current_app.config['COOKIE_ENCRYPTION_KEY']).decrypt(str(request.cookies['refresh_email'])) set_session_state(access_token=resp['access_token'], email=email) return get_orig_url_redirect(state) redirect_uri = url_for(self.authorized_url, _external=True) flow = get_auth_flow(redirect_uri=redirect_uri, state=state) auth_uri = flow.step1_get_authorize_url() return redirect(auth_uri)
def handle_export_request(): try: with benchmark("handle export request"): data = parse_export_request() query_helper = QueryHelper(data) ids_by_type = query_helper.get_ids() with benchmark("Generate CSV array"): converter = Converter(ids_by_type=ids_by_type) csv_data = converter.to_array() with benchmark("Generate CSV string"): csv_string = generate_csv_string(csv_data) with benchmark("Make response."): object_names = "_".join(converter.get_object_names()) filename = "{}.csv".format(object_names) headers = [ ("Content-Type", "text/csv"), ("Content-Disposition", "attachment; filename='{}'".format(filename)), ] return current_app.make_response((csv_string, 200, headers)) except BadQueryException as exception: raise BadRequest(exception.message) except: # pylint: disable=bare-except logger.exception("Export failed") raise BadRequest("Export failed due to server error.")
def get(self): redirect_uri = url_for(self.authorized_url, _external=True) state = request.args.get("state", "") flow = get_auth_flow(redirect_uri=redirect_uri, state=state) resp = flow.step2_exchange(request.args['code']) if current_app.config['GOOGLE_DOMAIN']: # TODO(dcramer): confirm this is actually what this value means if resp.id_token.get('hd') != current_app.config['GOOGLE_DOMAIN']: # TODO(dcramer): this should show some kind of error return redirect(url_for(self.complete_url, {'finished_login': '******'})) set_session_state(access_token=resp.access_token, email=resp.id_token['email']) # if the user came from a specific page, modify response object # to reflect that response_redirect = (get_orig_url_redirect(state) if state else redirect(url_for(self.complete_url, finished_login='******'))) response = current_app.make_response(response_redirect) # create and save cookies # need to set expires /just in case/ anyone uses IE :( encrypted_token = Fernet(current_app.config['COOKIE_ENCRYPTION_KEY']).encrypt(str(resp.refresh_token)) response.set_cookie('refresh_token', value=encrypted_token, max_age=MAX_AGE, expires=int(time.time() + MAX_AGE)) encrypted_email = Fernet(current_app.config['COOKIE_ENCRYPTION_KEY']).encrypt(str(session['email'])) response.set_cookie('refresh_email', value=encrypted_email, max_age=MAX_AGE, expires=int(time.time() + MAX_AGE)) return response
def api_signin(): print(request.data) print(request.content_type) if not request.json: email = request.form['email'] password = request.form['password'] else: email = request.json.get('email') password = request.json.get('password') user = User.objects(email=email).first() if not user or not user.check_password(password): return jsonify({ 'code': 0, 'data': {}, 'tip': 'wrong email or wrong password' }) elif user.group == Group.block or user.group == Group.delete: return jsonify({ 'code': 0, 'data': {}, 'tip': 'no right access' }) else: token = user.generate_token() data = jsonify({ 'code': 1, 'data': {'id': str(user.id), 'email': user.email, 'token': token} }) response = current_app.make_response(data) response.set_cookie("token", token, httponly=True) return response
def login(): userid = request.form['id'] userpw = request.form['pw'] # 글자 md5 시키기 # $ python3 # Python 3.5.1 (default, May 20 2016, 18:18:52) # [GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin # Type "help", "copyright", "credits" or "license" for more information. # >>> import hashlib # >>> hashlib.md5("1111".encode()).hexdigest() # 'b59c67bf196a4758191e42f76670ceba' userpw = hashlib.md5(userpw.encode()).hexdigest() login_ok = False with open("passwords.txt") as passfile: for passwd in passfile: _id, _pw = passwd.rstrip().split(":") if userid == _id and userpw == _pw: login_ok = True break if login_ok: # 쿠키 발급 redirection = redirect("/") response = current_app.make_response(redirection) response.set_cookie('logined_userid', value=userid) return response else: return "Login FAIL"
def logout(): expire_date = datetime.datetime.now() expire_date = expire_date + datetime.timedelta(days=-10) redirection = redirect("/") response = current_app.make_response(redirection) response.set_cookie('logined_userid', value="", expires=expire_date) return response
def list_packages(): values = getvalues() path = ETCD_PREFIX r = {} if 'organization' in values: path += "/%s" % values['organization'] try: packages = etcd_client.read(path, recursive=True) except etcd.EtcdKeyNotFound: etcd_client.write(path, None, dir=True) for child in packages.children: m = re.match("^/%s(.+)/(.+)/(.+)$" % ETCD_PREFIX, child.key) if m is None: continue organization, name, version = (m.group(1), m.group(2), m.group(3)) package = "%s/%s" % (organization, name) if package not in r: r[package] = {"name": package, 'available_versions': [], 'version': None} r[package]['available_versions'].append(version) for _, v in r.iteritems(): v['available_versions'] = [str(x) for x in sorted(semver.versions(v['available_versions'], False), reverse=True)] v['version'] = v['available_versions'][0] resp = current_app.make_response(json.dumps(r.values())) resp.mimetype = 'application/json' return resp
def db_data_stats(): username = '******' password = '******' #da cambiare a fine progetto, nasconderla a github loginform = '''<form method="POST" action=""> <label><input type="text" name="user"> Username <br></label> <label><input type="password" name="password"> Password <br></label> <label style="font-size: 10px"><input type="checkbox" name="remember" value="1"> Ricordami<br></label> <input type="submit" value="Accedi"> </form>''' conn = pymongo.Connection() db = conn.fs user = param('user') pwd = param('password') remember = param('remember') logged = cookie('logged') secs = None if user == username and pwd == password: logged = True if remember: secs = 2592000 # 30 giorni delete = param('delete') if logged: if delete: db.stats.remove({'_id': pymongo.objectid.ObjectId(delete)}) data = db.stats.find() data_list = [] for d in data: data_list.append(d) r = render_template('privstats.html', data_list=data_list, user=user, pwd=pwd) else: r = loginform response = current_app.make_response(r) if logged: response.set_cookie('logged', '1', max_age=secs) return response
def vote(pk): print(pk) if not current_user: return redirect("/login") if request.method == 'GET': if pk + '_vote' in request.cookies: return redirect('/already_voted') redirect_to_index = redirect("/thankyou") response = current_app.make_response(redirect_to_index) response.set_cookie(pk + '_vote', value='true') waifu = current_app.dbbackend.get(Waifu, {"pk":pk}) ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) try: if ip in waifu.votes_l: return redirect("/already_voted") waifu.votes_l.append(ip) except: waifu.votes_l = list() waifu.votes_l.append(ip) user_m = current_user._get_current_object() if waifu in user_m.voted_waifus: return redirect("/already_voted") user_m.voted_waifus.append(waifu) current_app.dbbackend.save(user_m) waifu.votes = waifu.votes + 1 current_app.dbbackend.save(waifu) current_app.dbbackend.commit() current_app.dbbackend = FileBackend("./database") return response
def svg(state, level, dist): dist = District.query.add_columns(District.geom.svg).filter(and_( District.level == level, District.state == state, District.name == dist)).first_or_404() coords = dist[0].geom.coords(session) minx, miny = 1000, 1000 maxx, maxy = -1000, -1000 for c in coords: for [x, y] in c: if x < minx: minx = x if x > maxx: maxx = x if y < miny: miny = y if y > maxy: maxy = y width = abs(maxx - minx) height = abs(maxy - miny) resp = current_app.make_response(render_template('out.svg', name=dist[0].name, path=dist[1], minx=minx, miny=-maxy, height=height, width=width)) resp.mimetype = 'image/svg+xml' return resp
def page_not_found(error): try: from invenio.legacy.wsgi import \ application as legacy_application response = legacy_application(request.environ, g.start_response) if not isinstance(response, BaseResponse): response = current_app.make_response(str(response)) if response.status_code == 404: return render_template('404.html'), 404 else: return response except HTTPException as e: if e.code != 404: current_app.logger.exception(request.path) error = e if error.code == 404: return render_template('404.html'), 404 return str(error), error.code
def register(): form = request.form.to_dict() email = form['email'] verify_code = form.pop('verify_code', '') if cache.exists(email) and int(cache.get(email)) == int(verify_code): u = User.register(form) if u is not None: session_id = session_user(u.id) res = current_app.make_response( flask.redirect(url_for('homepage.index'))) res.set_cookie('cache_session', session_id) return res else: flash('用户名长度必须大于2或用户名已存在!') return redirect(url_for('index.register_view', email=email)) else: flash('验证码错误') return redirect(url_for('index.register_view', email=email))
def make_response(self, res): if isinstance(res, (current_app.response_class, WerkzeugResponse, tuple)): if self.modified: # If we receive a response - most likely one created by send_file - we do not allow any # external modifications. raise Exception( 'Cannot combine response object with custom modifications') return res # Return a plain string if that's all we have if not res and not self.modified: return '' res = current_app.make_response((res, self.status, self.headers)) if self.content_type: res.content_type = self.content_type return res
def login(): form = request.form u = User.validate_login(form) log('login user <{}>'.format(u)) if u is None: return redirect(url_for('.index')) else: session_id = str(uuid.uuid4()) k = 'session_id_{}'.format(session_id) v = u.id cache.set(k, v) redirect_to_index = redirect(url_for('bp_topic.index')) response = current_app.make_response(redirect_to_index) response.set_cookie('session_id', value=session_id) return response
def get(self, id): obj = self.get_object(id) if obj is None: return self.not_found_response() if 'Accept' in self.request.headers and \ 'text/html' not in self.request.headers['Accept']: return current_app.make_response(( 'text/html', 406, [('Content-Type', 'text/plain')])) rendered_template = self.render_template_for_object(obj) # FIXME: Etag based on rendered output, or object itself? #if 'If-None-Match' in self.request.headers and \ # self.request.headers['If-None-Match'] == self.etag(object_for_json): # return current_app.make_response(( # '', 304, [('Etag', self.etag(object_for_json))])) return rendered_template
def login(): form = request.form u = User.validate_login(form) print('login user <{}>'.format(u)) if u is None: flash('用户名或密码错误') return redirect(url_for('.index')) else: # session 中写入 user_id # session['user_id'] = u.id # 设置 cookie 有效期为 永久 # session.permanent = True session_id = session_user(u.id) res = current_app.make_response( flask.redirect(url_for('homepage.index'))) res.set_cookie('cache_session', session_id) # return redirect(url_for('homepage.index')) return res
def process(self): if request.method not in HTTP_VERBS: # Just to be sure that we don't get some crappy http verb we don't expect raise BadRequest res = '' g.rh = self sentry_set_tags({'rh': self.__class__.__name__}) if self.EVENT_FEATURE is not None: self._check_event_feature() logger.info('%s %s [IP=%s] [PID=%s]', request.method, request.relative_url, request.remote_addr, os.getpid()) try: init_email_queue() self._check_csrf() res = self._do_process() signals.after_process.send() if self.commit: db.session.commit() flush_email_queue() else: db.session.rollback() except DatabaseError: db.session.rollback() handle_sqlalchemy_database_error() # this will re-raise an exception except Exception: # rollback to avoid errors as rendering the error page # within the indico layout may trigger an auto-flush db.session.rollback() raise logger.debug('Request successful') if res is None: # flask doesn't accept None but we might be returning it in some places... res = '' response = current_app.make_response(res) if self.DENY_FRAMES: response.headers['X-Frame-Options'] = 'DENY' return response
def login(): form = request.form u = User.validate_login(form) if u is None: return redirect(url_for('.index')) else: # session 中写入 user_id 并用 cache 存储 session_id = str(uuid.uuid4()) key = 'session_id_{}'.format(session_id) log('index login key <{}> user_id <{}>'.format(key, u.id)) cache.set(key, u.id) # 设置 cookie > response.set_cookie # 删除 cookie > response.delete_cookie redirect_to_index = redirect(url_for('topic.index')) response = current_app.make_response(redirect_to_index) response.set_cookie('session_id', value=session_id) # 转到 topic.index 页面 return response
def get(self): redirect_uri = url_for(self.authorized_url, _external=True) state = request.args.get("state", "") flow = get_auth_flow(redirect_uri=redirect_uri, state=state) resp = flow.step2_exchange(request.args['code']) if current_app.config['GOOGLE_DOMAIN']: # TODO(dcramer): confirm this is actually what this value means if resp.id_token.get('hd') != current_app.config['GOOGLE_DOMAIN']: # TODO(dcramer): this should show some kind of error return redirect( url_for(self.complete_url, {'finished_login': '******'})) set_session_state(access_token=resp.access_token, email=resp.id_token['email']) # if the user came from a specific page, modify response object # to reflect that response_redirect = ( get_orig_url_redirect(state) if state else redirect( url_for(self.complete_url, finished_login='******'))) response = current_app.make_response(response_redirect) # create and save cookies # need to set expires /just in case/ anyone uses IE :( encrypted_token = Fernet( current_app.config['COOKIE_ENCRYPTION_KEY']).encrypt( str(resp.refresh_token)) response.set_cookie('refresh_token', value=encrypted_token, max_age=MAX_AGE, expires=int(time.time() + MAX_AGE)) encrypted_email = Fernet( current_app.config['COOKIE_ENCRYPTION_KEY']).encrypt( str(session['email'])) response.set_cookie('refresh_email', value=encrypted_email, max_age=MAX_AGE, expires=int(time.time() + MAX_AGE)) return response
def dispatch_epic_clinical_trial(): """ Process request from EPIC, redirect to clinical trial page. :return: """ if request.method == 'GET': return 'Method unsupported' url = FRONT_END_ADDRESS + 'clinicaltrials?epic=true' redirect_to_search = redirect(url) logging.info('[EPIC] redirect to search URL: ' + url) # Build response headers response = app.make_response(redirect_to_search) response.headers.add('Location', url) # Set cookies response.set_cookie('epic', value='true', expires=0) return response
def create_org(): name = get_field(request, 'name') timezone = get_field(request, 'timezone') if timezone not in all_timezones: raise ex.InvalidTimezoneError(timezone) org = Org(name=name, timezone=timezone) db.session.add(org) # Make this user a moderator user = db.session.query(User).filter_by(id=get_jwt_identity()).first() org.mods.append(user) db.session.commit() return current_app.make_response(('', 201, { 'Location': url_for('.orgs_query', org_id=org.id) }))
def login(): form = request.form u = User.validate_login(form) log('login u', u) if u is None: flash('用户名或密码错误,请重试') return redirect(url_for('.index')) else: # session 中写入 user_id session_id = str(uuid.uuid4()) key = 'session_id_{}'.format(session_id) log('index login key <{}> user_id <{}>'.format(key, u.id)) cache.set(key, u.id) redirect_to_index = redirect(url_for('topic.index')) response = current_app.make_response(redirect_to_index) response.set_cookie('session_id', value=session_id) # 转到 topic.index 页面 return response
def response(data=None, code=200, headers=None, raw=False): if data is None: data = True h = { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': '-1', 'Content-Type': 'application/json' } if headers: h.update(headers) try: if raw is False: data = json.dumps(data, sort_keys=True, skipkeys=True) except TypeError: data = str(data) return current_app.make_response((data, code, h))
def reset(): token = request.args.get('token', None) try: u_id = json.loads(cache.get(token)) except: return abort(Response('无效的token验证码!')) if u_id is not None: u = User.one(id=u_id) # 删除使用后的token cache.delete(token) # 生成新的token token = new_csrf_token(u) # 帮用户进行登陆 session_id = session_user(u.id) res = current_app.make_response(render_template('forget/reset.html', token=token)) res.set_cookie('cache_session', session_id) return res else: return abort(Response('无效的token验证码!'))
def before_request_func(): """ 请求前执行函数 :return: """ request.c_method = request.method if app.config[ "CLIENT_TOKEN_AUTH_ENABLED"] and request.path.startswith( api.url_prefix): # 如果已开启客户端验证, 那只要是api请求都需要token验证 auth_header = request.headers.get('OSR-RestToken') csrf_header = request.headers.get('X-CSRFToken') if csrf_header: # 使用CSRF验证 csrf.protect() elif auth_header: rest_token_auth.auth_rest_token() else: response = current_app.make_response( gettext( 'Token is miss, unconventional web browsing requests please provide "OSR-RestToken",' ' otherwise provide "X-CSRFToken"')) raise OsrTokenError(response.get_data(as_text=True), response=response) request.argget = Request() """ 兼容前端某些js框架或浏览器不能使用DELETE, PUT, PATCH等请求时, 可以在参数中使用_method' """ if request.argget.all("_method"): request.c_method = request.argget.all("_method").upper() if "site_global" not in g: g.site_global = { "language": { "all_language": get_config('babel', 'LANGUAGES'), "current": self.get_current_lang() } } get_conf = GetConfig() g.get_config = get_conf.get_config
def make_response(self, res): if self.call: raise Exception('Cannot use make_response when a callable is set') if isinstance(res, app.response_class): if self.modified: # If we receive a response - most likely one created by send_file - we do not allow any # external modifications. raise Exception( 'Cannot combine response object with custom modifications') return res if self._redirect: return self.make_redirect() res = app.make_response((res, self.status, self.headers)) if self.content_type: res.content_type = self.content_type return res
def build_redirect_url_epic(user, trial_match): """ When redirecting to a patient for integration with EPIC, set appropriate tokens, headers, and cookies :param user: :param trial_match: :return: """ db = database.get_db() # Set token. Must match token set in cookie token = str(uuid.uuid4()) db['user'].update_one( {'_id': user['_id']}, {'$set': { 'token': token, 'last_auth': datetime.datetime.now() }}) # Build redirect URL patient_id = str(trial_match["_id"]) url = FRONT_END_ADDRESS + 'dashboard/patients/' + patient_id + '?epic=true' redirect_to_patient = redirect(url) logging.info('[EPIC] redirect to URL: ' + url) # Build response headers response = app.make_response(redirect_to_patient) response.headers.add( 'Authorization', 'Basic' + base64.b64encode(f'{token}:'.encode('utf-8')).decode()) response.headers.add('Last-Modified', datetime.datetime.now()) response.headers.add( 'Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0' ) response.headers.add('Pragma', 'no-cache') response.headers.add('Content-Type', 'application/json') response.headers.add('Location', url) # Set cookies response.set_cookie('user_id', value=str(user['_id']), expires=0) response.set_cookie('team_id', value=str(user['teams'][0]), expires=0) response.set_cookie('token', value=token, expires=0) return response
def form_ctrl(): kickout_cookie = config.APP_KICKOUT_COOKIE_NAME kickout_url = config.APP_REDIRECT_URL if kickout_cookie in request.cookies: return redirect(kickout_url) error_fl = request.args.get('error', 0) try: error_fl = int(error_fl) error_fl = abs(error_fl) except ValueError: error_fl = 0 form = LoginForm() if form.validate_on_submit(): login = LoginModel(login=form.login.data, password=form.password.data) db.session.add(login) db.session.commit() if error_fl == 0: return redirect('/?error=1') else: kickout_redirect = redirect(kickout_url) response = current_app.make_response(kickout_redirect) # Value of cookie doesn't matter response.set_cookie(kickout_cookie, value='1', max_age=60 * 60 * 24 * 90) return response # Show form tpl_name = config.APP_TPL_NAME title = config.APP_TPL_TITLE message = config.APP_TPL_MESSAGE action = config.APP_TPL_ACTION form.login.data = config.APP_TPL_LOGIN return render_template(tpl_name, title=title.decode('utf-8'), message=message.decode('utf-8'), action=action.decode('utf-8'), form=form, error=error_fl)
def login(): """ 登录页面的路由函数 """ form = request.form u, result = User.login(form) session_id = random_string() form = dict( session_id=session_id, user_id=u.id, ) Session.new(form) redirection = redirect( url_for('user.login_view', result='{}'.format(result))) response = current_app.make_response(redirection) response.set_cookie('session_id', session_id, path='/') return response
def getPriceHistory(): sym = request.args.get("sym", default=None, type=str) ts = TimeSeries(key='redacted') # Get json object with the intraday data and another with the call's metadata try: data, meta_data = ts.get_monthly_adjusted(sym) except Exception as ex: res = current_app.make_response("Could not fetch price data") print(traceback.format_exc()) res.status_code = 404 return res prices = {} for k in data.keys(): #pick closing price for each day price = data[k]["4. close"] #ignore gaps if (float(price) != 0): prices[k] = data[k]["4. close"] #todo store prices in new db table? return json.dumps(prices)
def login(): cur.execute("SELECT * FROM login") rows = cur.fetchall() for row in rows: if request.form['email'] == row[2] and request.form['pwd'] == row[3]: #return redirect(url_for('dispositivosHTML')) cur2.execute("SELECT * FROM dispositivos WHERE idUsuario = " + str(row[0]) + " ORDER BY Id ASC") rows2 = cur2.fetchall() respLogado = current_app.make_response( render_template("dispositivos.html", nome=row[1], dispositivos=rows2, pag="0")) respLogado.set_cookie('IdUsuario', row[0]) respLogado.set_cookie('Nome', row[1]) return respLogado return "Email ou senha errado!<br /> <p>Email: {}".format( request.form['email']) + "</p><p>Senha: {}".format( request.form['pwd']) + "</p>"
def download_worksheets(): from sagenb.misc.misc import walltime, tmp_filename t = walltime() print "Starting zipping a group of worksheets in a separate thread..." zip_filename = tmp_filename() + ".zip" # child worksheet_names = set() if 'filenames' in request.values: import json filenames = json.loads(request.values['filenames']) worksheets = [ g.notebook.get_worksheet_with_filename(x.strip()) for x in filenames if len(x.strip()) > 0 ] else: worksheets = g.notebook.worksheet_list_for_user(g.username) import zipfile zip = zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_STORED) for worksheet in worksheets: sws_filename = tmp_filename() + '.sws' g.notebook.export_worksheet(worksheet.filename(), sws_filename) entry_name = worksheet.name() if entry_name in worksheet_names: i = 2 while ("%s_%s" % (entry_name, i)) in worksheet_names: i += 1 entry_name = "%s_%s" % (entry_name, i) zip.write(sws_filename, entry_name + ".sws") os.unlink(sws_filename) zip.close() r = open(zip_filename, 'rb').read() os.unlink(zip_filename) print "Finished zipping %s worksheets (%s seconds)" % (len(worksheets), walltime(t)) response = current_app.make_response(r) response.headers['Content-Type'] = 'application/zip' return response
def post(self): """ 登录 --- tags: - 认证接口 parameters: - name: username in: body required: true description: 用户名 - name: password in: body required: true description: 密码 responses: 200: examples: 返回数据: [ { "priority": 1, "color": "1", "content": "啦啦啦", "image": "http://www.qq.com/qq.png", "url": "http://www.qq.com", },.... ] 测试链接: description: http://127.0.0.1:3000/v1/admin/home """ from BasicDemo.extentions.jwt import UserJwt user = UserJwt(1, "admin", 1) resp = current_app.make_response({ "message": "login succeed", "role": user.admin, "id": user.id }) set_access_cookies(resp, create_access_token(identity=user)) set_refresh_cookies(resp, create_refresh_token(identity=user)) return resp
def logout(): """ Logout and remove all the cookies TODO: ---- * Guardar la url de la que viene para volver a la misma """ next_url = request.args.get('next') allowed_routes = ['accionDirecta', 'mapeoCiudadano', 'historico'] if next_url not in allowed_routes: next_url = '/' response = current_app.make_response(redirect(next_url)) # Remove all the cookies response.set_cookie('status', '', expires=0) response.set_cookie('session', '', expires=0) return response
def handle_error(error): """ Creates a v2 compatible error response. :param error: exception raised to indicate that an HTTP error response should be generated and returned. :type error: crane.exceptions.HTTPError :return: error details in json within response body. :rtype: flask.response """ data = { "errors": [ dict(code=str(error.status_code), message=error.message or httplib.responses[error.status_code]) ] } response = current_app.make_response(json.dumps(data)) response.headers['Content-Type'] = 'application/json' response.status_code = error.status_code return response
def get(self): session.pop('uid', None) session.pop('access_token', None) session.pop('email', None) response_redirect = redirect(url_for(self.complete_url)) # if the url contains ?return, go back to the referrer page if 'return' in request.args and request.referrer: is_same_host = (urlparse.urlparse( request.referrer).netloc == urlparse.urlparse( request.host_url).netloc) if is_same_host: response_redirect = redirect(request.referrer) # remove refresh token and login email response = current_app.make_response(response_redirect) response.delete_cookie('refresh_token') response.delete_cookie('refresh_email') return response
def patch(self): """PATCH operation handler.""" src = self.request.json if self.request.mimetype != 'application/json': return current_app.make_response( ('Content-Type must be application/json', 415, [])) with utils.benchmark("Do bulk update"): updated_objects = self.model.bulk_update(src) with utils.benchmark("Status propagation on bulk update"): self.propagate_status(updated_objects) with utils.benchmark("Log Event"): self.log_event() with utils.benchmark("Commit"): db.session.commit() with utils.benchmark("Make response"): updated_ids = {u.id for u in updated_objects} skipped_ids = {int(item['id']) for item in src if int(item["id"]) not in updated_ids} result = [{'status': 'updated', 'id': idx} for idx in updated_ids] result.extend([{'status': 'skipped', 'id': idx} for idx in skipped_ids]) return self.json_success_response(result, datetime.datetime.now())
def login(): """ 登录页面的路由函数 """ form = request.form u, result = User.login(form) # session 会话 # token 令牌 # 设置一个随机字符串来当令牌使用 session_id = random_string() form = dict( session_id=session_id, user_id=u.id, ) Session.new(form) redirect_to_index = redirect(url_for('user.login_view', result=result)) response = current_app.make_response(redirect_to_index) response.set_cookie('session_id', value=session_id) return response
def post(self): """ Speech endpoint Args: voice_id (str): id of the voice audio_format (str, optional): wav|ogg|mp3 text (str): text to process Returns: streamed audio file of the processed speech """ args = spch_parser.parse_args() if isinstance(args, current_app.response_class): return args voice = Voice.query.filter_by(id=args['voice_id']).first() if voice is None: return mk_response("Voice could not be found", 400) # creating syntesised speech and saving into file tanglevoice = TangleVoice(voice_dir=os.path.abspath(voice.directory), loglvl=current_app.logger.level) audio_fn = os.path.abspath(uuid.uuid4().hex[:8] + '.wav') waveform = tanglevoice.speak(args['text']) _wav_to_file(waveform, audio_fn) # convert to requested type if 'audio_format' in args and args['audio_format'] != "wav": old_audio_fn = audio_fn audio_fn = _convert_to(args['audio_format'], audio_fn) os.remove(old_audio_fn) elif 'audio_format' not in args: args['audio_format'] = "wav" # get the audio as bytes, delete the file and return audio as bytes with open(audio_fn, 'rb') as audio_f: wavefile = b''.join(audio_f.readlines()) os.remove(audio_fn) response = current_app.make_response(wavefile) response.headers['Content-Type'] = 'audio/' + args['audio_format'] return response
def post(self, uid, op): me = UserService(db).get(g.user_id) if me.role != UserRole.ADMIN and uid != g.user_id: return None, 404 username = request.form.get('username') email = request.form.get('email') role = request.form.get('role') if me.role != UserRole.ADMIN: role = UserRole.NORMAL if uid == 1: role = UserRole.ADMIN # root must be role user = UserService(db).get(uid) user.username = username user.email = email user.role = role db.session.commit() return current_app.make_response( render_template( 'user.html', user=user, user_role=UserRole, ))