Python flask.request.user() Examples
The following are 30
code examples of flask.request.user().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask.request
, or try the search function
.
Example #1
Source File: views.py From flux-ci with MIT License | 6 votes |
def build(): repo_id = request.args.get('repo_id', '') ref_name = request.args.get('ref', '') if not repo_id or not ref_name: return abort(400) if not request.user.can_manage: return abort(403) commit = '0' * 32 repo = Repository.get(id=repo_id) build = Build( repo=repo, commit_sha=commit, num=repo.build_count, ref=ref_name, status=Build.Status_Queued, date_queued=datetime.now(), date_started=None, date_finished=None) repo.build_count += 1 models.commit() enqueue(build) return redirect(repo.url())
Example #2
Source File: oauth1.py From BhagavadGita with GNU General Public License v3.0 | 6 votes |
def tokengetter(self, f): """Register a function as the access token getter. The function accepts `client_key` and `token` parameters, and it returns an access token object contains: - client: Client associated with this token - user: User associated with this token - token: Access token - secret: Access token secret - realms: Realms with this access token Implement the token getter:: @oauth.tokengetter def get_access_token(client_key, token): return AccessToken.get(client_key=client_key, token=token) """ self._tokengetter = f return f
Example #3
Source File: oauth1.py From BhagavadGita with GNU General Public License v3.0 | 6 votes |
def verifiergetter(self, f): """Register a function as the verifier getter. The return verifier object should at least contain a user object which is the current user. The implemented code looks like:: @oauth.verifiergetter def load_verifier(verifier, token): data = Verifier.get(verifier) if data.request_token == token: # check verifier for safety return data return data """ self._verifiergetter = f return f
Example #4
Source File: router.py From maple-file with BSD 3-Clause "New" or "Revised" License | 6 votes |
def delete(self, pk): ''' 删除图片 ''' user = request.user image = Image.query.filter_by(id=pk, user=user).get_or_404('图片不存在') serializer = ImageSerializer(image) img_path = os.path.join(current_app.config['UPLOAD_FOLDER_ROOT'], image.url) # 删除原图 if os.path.exists(img_path): os.remove(img_path) # 删除缩略图 thumb_path = os.path.join(current_app.config['UPLOAD_FOLDER_ROOT'], image.url.replace('photo', 'thumb')) if os.path.exists(thumb_path): os.remove(thumb_path) image.delete() return HTTP.OK(data=serializer.data)
Example #5
Source File: oauth1.py From BhagavadGita with GNU General Public License v3.0 | 6 votes |
def verifiersetter(self, f): """Register a function as the verifier setter. A verifier is better together with request token, but it is not required. A verifier is used together with request token for exchanging access token, it has an expire time, in this case, it would be a better design if you put them in a cache. The implemented code looks like:: @oauth.verifiersetter def save_verifier(verifier, token, *args, **kwargs): data = Verifier( verifier=verifier['oauth_verifier'], request_token=token, user=get_current_user() ) return data.save() """ self._verifiersetter = f return f
Example #6
Source File: router.py From maple-file with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get(self): ''' 获取图片列表 ''' query_dict = request.data user = request.user page, number = self.page_info keys = ['name', 'description'] order_by = gen_order_by(query_dict, keys) filter_dict = gen_filter_dict(query_dict, keys, user=user) album = query_dict.pop('album', None) if album is not None: filter_dict.update(album__id=album) images = Image.query.filter_by( **filter_dict).order_by(*order_by).paginate(page, number) serializer = ImageSerializer(images.items, True) pageinfo = PageInfo(images) return HTTP.OK(data=serializer.data, pageinfo=pageinfo)
Example #7
Source File: router.py From maple-file with BSD 3-Clause "New" or "Revised" License | 6 votes |
def post(self): ''' 新建相册 ''' post_data = request.data user = request.user name = post_data.pop('name', None) description = post_data.pop('description', None) if name is None: return HTTP.BAD_REQUEST(message='相册名称不能为空') album = Album(name=name, user=user) if description is not None: album.description = description album.save() serializer = AlbumSerializer(album) return HTTP.OK(data=serializer.data)
Example #8
Source File: oauth1.py From BhagavadGita with GNU General Public License v3.0 | 6 votes |
def save_access_token(self, token, request): """Save access token to database. A tokensetter is required, which accepts a token and request parameters:: def tokensetter(token, request): access_token = Token( client=request.client, user=request.user, token=token['oauth_token'], secret=token['oauth_token_secret'], realms=token['oauth_authorized_realms'], ) return access_token.save() """ log.debug('Save access token %r', token) self._tokensetter(token, request)
Example #9
Source File: oauth1.py From BhagavadGita with GNU General Public License v3.0 | 6 votes |
def save_verifier(self, token, verifier, request): """Save verifier to database. A verifiersetter is required. It would be better to combine request token and verifier together:: def verifiersetter(token, verifier, request): tok = Grant.query.filter_by(token=token).first() tok.verifier = verifier['oauth_verifier'] tok.user = get_current_user() return tok.save() .. admonition:: Note: A user is required on verifier, remember to attach current user to verifier. """ log.debug('Save verifier %r for %r', verifier, token) self._verifiersetter(token=token, verifier=verifier, request=request)
Example #10
Source File: router.py From maple-file with BSD 3-Clause "New" or "Revised" License | 6 votes |
def put(self, pk): ''' 修改图片信息 ''' post_data = request.data user = request.user name = post_data.pop('name', None) description = post_data.pop('description', None) image = Image.query.filter_by(id=pk, user=user).get_or_404('图片不存在') if name is not None: image.name = name image.url = os.path.join(image.path, name) if description is not None: image.description = description image.save() serializer = ImageSerializer(image) return HTTP.OK(data=serializer.data)
Example #11
Source File: filepath.py From maple-blog with GNU General Public License v3.0 | 6 votes |
def get(self, bucket): data = request.data user = request.user page, number = self.pageinfo bucket = user.buckets.filter_by( name=bucket).get_or_404("bucket not found") path = request.data.get("path", "/") params = filter_maybe(data, { "name": "name__contains", }) rootpath = bucket.get_root_path(path) paths = rootpath.child_paths.filter_by(**params).paginate(page, number) serializer = FilePathSerializer(paths) return HTTP.OK(data=serializer.data)
Example #12
Source File: test_auth.py From asgard-api with MIT License | 6 votes |
def test_jwt_return_401_if_user_is_not_linked_to_account(self): """ If user tries to access account without being associated to this account """ test_client = application.test_client() with application.app_context(): jwt_token = jwt_encode(self.user, self.account_with_no_user) auth_header = { "Authorization": "JWT {}".format(jwt_token.decode("utf-8")) } r = test_client.get("/v2/apps", headers=auth_header) self.assertEqual(401, r.status_code) self.assertEqual( "Permission Denied to access this account", json.loads(r.data)["msg"], )
Example #13
Source File: test_auth.py From asgard-api with MIT License | 6 votes |
def test_add_default_account_on_first_jwt_token(self): """ Depois do processo de login, o token JWT conterá o account_id da conta padrão do usuário. """ test_client = application.test_client() MagicMock() with application.app_context(), patch.object( routes, "check_authentication_successful", return_value={"email": self.user.email}, ), patch.object( routes.jwt_auth, "jwt_encode_callback" ) as jwt_auth_mock: test_client.get("/authenticate/google") user = UserDB( tx_name=USER_WITH_MULTIPLE_ACCOUNTS_NAME, tx_email=USER_WITH_MULTIPLE_ACCOUNTS_EMAIL, ) jwt_auth_mock.assert_called_once_with( jwt_generate_user_info(user, self.account_dev) )
Example #14
Source File: views.py From flux-ci with MIT License | 6 votes |
def view_build(path): build = get_target_for(path) if not isinstance(build, Build): return abort(404) restart = request.args.get('restart', '').strip().lower() == 'true' if restart: if build.status != Build.Status_Building: build.delete_build() build.status = Build.Status_Queued build.date_started = None build.date_finished = None models.commit() enqueue(build) return redirect(build.url()) stop = request.args.get('stop', '').strip().lower() == 'true' if stop: if build.status == Build.Status_Queued: build.status = Build.Status_Stopped elif build.status == Build.Status_Building: terminate_build(build) return redirect(build.url()) return render_template('view_build.html', user=request.user, build=build)
Example #15
Source File: views.py From flux-ci with MIT License | 6 votes |
def remove_keypair(path): if not request.user.can_manage: return abort(403) repo = get_target_for(path) if not isinstance(repo, Repository): return abort(404) session['errors'] = [] private_key_path = utils.get_repo_private_key_path(repo) public_key_path = utils.get_repo_public_key_path(repo) try: file_utils.delete(private_key_path) file_utils.delete(public_key_path) utils.flash('SSH keypair removed.') except BaseException as exc: app.logger.info(exc) session['errors'].append('Could not remove SSH keypair.') return redirect(url_for('edit_repo', repo_id = repo.id))
Example #16
Source File: views.py From flux-ci with MIT License | 6 votes |
def overrides_delete(path): if not request.user.can_manage: return abort(403) separator = "/" repo_path, overrides_path = file_utils.split_url_path(path) repo = get_target_for(repo_path) if not isinstance(repo, Repository): return abort(404) return_path_parts = path.split(separator) return_path = separator.join(return_path_parts[:-1]) cwd = os.path.join(utils.get_override_path(repo), overrides_path.replace('/', os.sep)) session['errors'] = [] try: file_utils.delete(cwd) utils.flash('Object was deleted.') except BaseException as exc: app.logger.info(exc) session['errors'].append('Could not delete \'' + return_path_parts[-1] + '\'.') return redirect(url_for('overrides_list', path = return_path))
Example #17
Source File: utils.py From flux-ci with MIT License | 6 votes |
def requires_auth(func): ''' Decorator for view functions that require basic authentication. ''' @functools.wraps(func) def wrapper(*args, **kwargs): ip = request.remote_addr token_string = session.get('flux_login_token') token = models.LoginToken.select(lambda t: t.token == token_string).first() if not token or token.ip != ip or token.expired(): if token and token.expired(): flash("Your login session has expired.") token.delete() return redirect(url_for('login')) request.login_token = token request.user = token.user return func(*args, **kwargs) return wrapper
Example #18
Source File: oauth2.py From BhagavadGita with GNU General Public License v3.0 | 6 votes |
def tokensetter(self, f): """Register a function to save the bearer token. The setter accepts two parameters at least, one is token, the other is request:: @oauth.tokensetter def set_token(token, request, *args, **kwargs): save_token(token, request.client, request.user) The parameter token is a dict, that looks like:: { u'access_token': u'6JwgO77PApxsFCU8Quz0pnL9s23016', u'token_type': u'Bearer', u'expires_in': 3600, u'scope': u'email address' } The request is an object, that contains an user object and a client object. """ self._tokensetter = f return f
Example #19
Source File: views.py From squealy with MIT License | 6 votes |
def handle_cors(response): if not response: response = flask.Response() cors_allowed_headers = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with'] response.headers['Access-Control-Allow-Origin'] = "http://localhost:8080" response.headers['Access-Control-Allow-Methods'] = ",".join(["GET","POST","OPTIONS"]) response.headers['Access-Control-Allow-Headers'] = ",".join(cors_allowed_headers) return response
Example #20
Source File: test_auth.py From asgard-api with MIT License | 6 votes |
def test_token_populate_default_account_if_request_account_is_empty(self): with application.test_client() as client: r = client.get( "/v2/apps", headers=self.auth_header(USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY), ) self.assertEqual(200, r.status_code) self.assertEqual( USER_WITH_MULTIPLE_ACCOUNTS_EMAIL, request.user.tx_email ) self.assertEqual( self.account_dev.id, request.user.current_account.id ) self.assertEqual( self.account_dev.namespace, request.user.current_account.namespace, ) self.assertEqual( self.account_dev.owner, request.user.current_account.owner )
Example #21
Source File: test_auth.py From asgard-api with MIT License | 6 votes |
def test_jwt_populate_default_account_if_request_account_is_empty(self): """ Como quem gera o token JWT é o server e ele *sempre* coloca account_id (Um user sem nennhuma account associada não se loga), esse request nunca vai acontecer. Não acontece pois é impossivel gerar um JWT válido sem ter a SECRET_KEY que só o server tem. """ test_client = application.test_client() with application.app_context(): jwt_token = jwt_auth.jwt_encode_callback( {"email": "user@host.com.br"} ) auth_header = { "Authorization": "JWT {}".format(jwt_token.decode("utf-8")) } r = test_client.get("/v2/apps", headers=auth_header) self.assertEqual(200, r.status_code) self.assertEqual(3, r.user.current_account)
Example #22
Source File: test_auth.py From asgard-api with MIT License | 6 votes |
def test_jwt_auth_with_token_from_session_if_headers_not_present(self): """ Se não encontrarmos o token JWT no header, olhamos na flask session procurando por ele. """ test_client = application.test_client() with application.app_context(), patch.object( routes, "check_authentication_successful", return_value={"email": self.user.email}, ): jwt_token = jwt_encode(self.user, self.account_dev) with test_client.session_transaction() as flask_session: flask_session["jwt"] = jwt_token response = test_client.get("/v2/apps") self.assertEqual(200, response.status_code)
Example #23
Source File: views.py From flux-ci with MIT License | 5 votes |
def overrides_edit(path): if not request.user.can_manage: return abort(403) separator = "/" context = {} errors = [] repo_path, context['overrides_path'] = file_utils.split_url_path(path) context['repo'] = get_target_for(repo_path) if not isinstance(context['repo'], Repository): return abort(404) file_path = os.path.join(utils.get_override_path(context['repo']), context['overrides_path'].replace('/', os.sep)) if request.method == 'POST': override_content = request.form.get('override_content') try: file_utils.write_file(file_path, override_content) utils.flash('Changes in file was saved.') except BaseException as exc: app.logger.info(exc) errors.append('Could not write into file.') dir_path_parts = path.split("/") context['dir_path'] = separator.join(dir_path_parts[:-1]) try: context['content'] = file_utils.read_file(file_path) except BaseException as exc: app.logger.info(exc) errors.append('Could not read file.') return render_template('overrides_edit.html', user=request.user, **context, errors=errors)
Example #24
Source File: oauth1.py From BhagavadGita with GNU General Public License v3.0 | 5 votes |
def require_oauth(self, *realms, **kwargs): """Protect resource with specified scopes.""" def wrapper(f): @wraps(f) def decorated(*args, **kwargs): for func in self._before_request_funcs: func() if hasattr(request, 'oauth') and request.oauth: return f(*args, **kwargs) server = self.server uri, http_method, body, headers = extract_params() try: valid, req = server.validate_protected_resource_request( uri, http_method, body, headers, realms) except Exception as e: log.warn('Exception: %r', e) e.urlencoded = urlencode([('error', 'unknown')]) e.status_code = 400 return _error_response(e) for func in self._after_request_funcs: valid, req = func(valid, req) if not valid: return abort(401) # alias user for convenience req.user = req.access_token.user request.oauth = req return f(*args, **kwargs) return decorated return wrapper
Example #25
Source File: oauth2.py From BhagavadGita with GNU General Public License v3.0 | 5 votes |
def grantsetter(self, f): """Register a function to save the grant code. The function accepts `client_id`, `code`, `request` and more:: @oauth.grantsetter def set_grant(client_id, code, request, *args, **kwargs): save_grant(client_id, code, request.user, request.scopes) """ self._grantsetter = f return f
Example #26
Source File: views.py From flux-ci with MIT License | 5 votes |
def overrides_upload(path): if not request.user.can_manage: return abort(403) separator = "/" context = {} errors = [] + session.pop('errors', []) repo_path, context['overrides_path'] = file_utils.split_url_path(path) repo = get_target_for(repo_path) if not isinstance(repo, Repository): return abort(404) context['list_path'] = url_for('overrides_list', path = path) cwd = os.path.join(utils.get_override_path(repo), context['overrides_path'].replace('/', os.sep)) if request.method == 'POST': session['errors'] = [] files = request.files.getlist('upload_file') if not files: utils.flash('No file was uploaded.') else: file_uploads = [] for file in files: filepath = os.path.join(cwd, secure_filename(file.filename)) try: file.save(filepath) file_uploads.append("File '{}' was uploaded.".format(file.filename)) except BaseException as exc: app.logger.info(exc) session['errors'].append("Could not upload '{}'.".format(file.filename)) utils.flash(" ".join(file_uploads)) if not session['errors']: return redirect(url_for('overrides_list', path = path)) dir_path_parts = path.split("/") context['dir_path'] = separator.join(dir_path_parts[:-1]) return render_template('overrides_upload.html', user=request.user, **context, errors=errors)
Example #27
Source File: oauth1.py From BhagavadGita with GNU General Public License v3.0 | 5 votes |
def validate_verifier(self, client_key, token, verifier, request): """Validate verifier exists.""" log.debug('Validate verifier %r for %r', verifier, client_key) data = self._verifiergetter(verifier=verifier, token=token) if not data: return False if not hasattr(data, 'user'): log.debug('Verifier should has user attribute') return False request.user = data.user if hasattr(data, 'client_key'): return data.client_key == client_key return True
Example #28
Source File: account.py From asgard-api with MIT License | 5 votes |
def me(): return json.dumps( jwt_generate_user_info(request.user, request.user.current_account) )
Example #29
Source File: account.py From asgard-api with MIT License | 5 votes |
def change_account(acc_id): account_ids = [acc.id for acc in request.user.accounts] try: user_info = jwt_generate_user_info( request.user, request.user.accounts[account_ids.index(acc_id)] ) jwt_token = jwt_auth.jwt_encode_callback(user_info) return _generate_repsonse(user_info, jwt_token.decode("utf8")) except ValueError: pass return make_response( json.dumps({"msg": "Not associated with account"}), 401 )
Example #30
Source File: views.py From flux-ci with MIT License | 5 votes |
def overrides_list(path): if not request.user.can_manage: return abort(403) separator = "/" errors = [] errors = errors + session.pop('errors', []) context = {} repo_path, context['overrides_path'] = file_utils.split_url_path(path) context['repo'] = get_target_for(repo_path) context['list_path'] = url_for('overrides_list', path = path) context['edit_path'] = url_for('overrides_edit', path = path) context['delete_path'] = url_for('overrides_delete', path = path) context['download_path'] = url_for('overrides_download', path = path) context['upload_path'] = url_for('overrides_upload', path = path) if context['overrides_path'] != '' and context['overrides_path'] != None: context['parent_name'] = separator.join(context['overrides_path'].split(separator)[:-1]) context['parent_path'] = url_for('overrides_list', path = separator.join(path.split(separator)[:-1])) if not isinstance(context['repo'], Repository): return abort(404) try: cwd = os.path.join(utils.get_override_path(context['repo']), context['overrides_path'].replace('/', os.sep)) utils.makedirs(os.path.dirname(cwd)) context['files'] = file_utils.list_folder(cwd) except BaseException as exc: app.logger.info(exc) errors.append('Could not read overrides for this repository.') return render_template('overrides_list.html', user=request.user, **context, errors=errors)