def run(self): name = prompt('Role Name') description = prompt('Role Description') _security_datastore = LocalProxy(lambda: current_app.extensions['security'].datastore) _security_datastore.create_role(name=name, description=description) db.session.commit() return
def delete(): email = g.current_user.email _security_datastore = LocalProxy(lambda: current_app.extensions['security'].datastore) _security_datastore.delete_user(g.current_user) _security_datastore.commit() return jsonify(dict(user=email, message='Successfully deleted user!'))
def run(self): default_roles = [('user', 'No Permissions'), ('admin', 'Comic specific permissions'), ('super', 'All permissions')] _security_datastore = LocalProxy(lambda: current_app.extensions['security'].datastore) for role in default_roles: _security_datastore.find_or_create_role(name=role[0], description=role[1]) db.session.commit() print 'Sucessfully added roles'
def user(): """Create circulation admin user.""" from werkzeug.local import LocalProxy from flask_security.utils import encrypt_password from invenio_db import db from invenio_oauth2server.models import Token _datastore = LocalProxy(lambda: app.extensions['security'].datastore) kwargs = dict( email='*****@*****.**', password='******', active=True ) kwargs['password'] = encrypt_password(kwargs['password']) user = _datastore.create_user(**kwargs) Token.create_personal( 'test-personal-{0}'.format(user.id), user.id, scopes=['webhooks:event'], is_internal=True, ).access_token db.session.commit()
def access_request(pid, record, template, **kwargs): """Create an access request.""" recid = int(pid.pid_value) datastore = LocalProxy( lambda: current_app.extensions['security'].datastore) # Record must be in restricted access mode. if record.get('access_right') != 'restricted' or \ not record.get('access_conditions'): abort(404) # Record must have an owner and owner must still exists. owners = record.get('owners', []) record_owners = [datastore.find_user(id=owner_id) for owner_id in owners] if not record_owners: abort(404) sender = None initialdata = dict() # Prepare initial form data if current_user.is_authenticated: sender = current_user initialdata['email'] = current_user.email if current_user.profile: initialdata['full_name'] = current_user.profile.full_name # Normal form validation form = AccessRequestForm(formdata=request.form, **initialdata) if form.validate_on_submit(): accreq = AccessRequest.create( recid=recid, receiver=record_owners[0], sender_full_name=form.data['full_name'], sender_email=form.data['email'], justification=form.data['justification'], sender=sender ) db.session.commit() if accreq.status == RequestStatus.EMAIL_VALIDATION: flash(_( "Email confirmation needed: We have sent you an email to " "verify your address. Please check the email and follow the " "instructions to complete the access request."), category='info') else: flash(_("Access request submitted."), category='info') return redirect(url_for('invenio_records_ui.recid', pid_value=recid)) return render_template( template, pid=pid, record=record, form=form, owners=record_owners, )
def delete_account(): delete_user_account_form = DeleteUserAccountForm() if delete_user_account_form.validate_on_submit(): user_temp = User.query.get(current_user.id) logout_user() _security_datastore = LocalProxy(lambda: current_app.extensions['security'].datastore) _security_datastore.delete_user(user_temp) _security_datastore.commit() return redirect(url_for('dashboard.index'))
def test_local_proxies_with_callables(): """Use a callable with a local proxy""" foo = 42 ls = LocalProxy(lambda: foo) assert ls == 42 foo = [23] ls.append(42) assert ls == [23, 42] assert foo == [23, 42]
def account_edit_own_password(): form = forms.MembersEditPassword() _security = LocalProxy(lambda: current_app.extensions['security']) _datastore = LocalProxy(lambda: _security.datastore) if form.validate_on_submit(): update_password(current_user, request.form['password']) _datastore.commit() flash("your password was updated", "confirmation") return redirect(request.url) return render_template('my_account/edit_password.html', form=form)
def generate_response(name, template, **kwargs): """ Handle the general response with template rendering, etc""" nav_menu_bar = LocalProxy(get_nav_menu_items) nav_menu_bar.set_active(name) body = render_template(template, current_date=time.ctime(), **kwargs) response = make_response(body) # ;-) response.headers['X-Powered-By'] = 'Not-PHP/1.0' if 'pcb_drill_session' not in session: session['pcb_drill_session'] = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S.%f') return response
def run(self): email = prompt('Email') # user = users.first(email=email) user = User.query.filter_by(email=email).first() if user: _security_datastore = LocalProxy(lambda: current_app.extensions['security'].datastore) admin_role = _security_datastore.find_role('admin') _security_datastore.add_role_to_user(user, admin_role) db.session.commit() print '\nUser given admin role sucessfully' return print '\nNo user found'
def test_local_proxy(): """Tests some proxy operations""" foo = [] ls = LocalProxy(lambda: foo) ls.append(42) ls.append(23) ls[1:] = [1, 2, 3] assert foo == [42, 1, 2, 3] assert repr(foo) == repr(ls) assert foo[0] == 42 foo += [1] assert list(foo) == [42, 1, 2, 3, 1]
def create_user_with_role(username, rolename): _datastore = LocalProxy( lambda: current_app.extensions['security'].datastore) user, role = _datastore._prepare_role_modify_args(username, rolename) if not user: user = create_test_user(email=username, password='******') if not role: role = _datastore.create_role(name=rolename) _datastore.add_role_to_user(user, role) return user
def user_registered_signal_handler(app, user, confirm_token): """Executed imediately after user registers a new account. Adds a default 'user' role to the new user :param app: Flask application object :param user: Newly registered Flask-Login User object :param confirm_token: Users confirm token """ _security_datastore = LocalProxy(lambda: app.extensions["security"].datastore) default_role = _security_datastore.find_role("user") _security_datastore.add_role_to_user(user, default_role) db.session.commit() Bundle.refresh_user_bundle(user, current_wednesday()) Bundle.refresh_user_bundle(user, next_wednesday()) Bundle.refresh_user_bundle(user, two_wednesdays())
def access_token(app, db): _datastore = LocalProxy(lambda: app.extensions['security'].datastore) kwargs = dict(email='*****@*****.**', password='******', active=True) kwargs['password'] = encrypt_password(kwargs['password']) user = _datastore.create_user(**kwargs) db.session.commit() token = Token.create_personal( 'test-personal-{0}'.format(user.id), user.id, scopes=['webhooks:event'], is_internal=True, ).access_token db.session.commit() yield token
# -*- coding: utf-8 -*- import os from werkzeug.local import LocalProxy from flask import current_app, request, jsonify, render_template, send_file, session, redirect from ..core import AppError from .. import factory from .. import errors from .. import settings from .. import app_user_manager from ..helpers.flask_helper import _endpoint_url _logger = LocalProxy(lambda: current_app.logger) def create_app(): settings_override = { 'USER_ENABLE_REGISTRATION': False, 'SQLALCHEMY_POOL_SIZE': 5, } app = factory.create_app(__name__, __path__, settings_override, logger_name='backend') app.errorhandler(AppError)(on_app_error) app.errorhandler(Exception)(unhandle_error) app.errorhandler(404)(on_404) app.errorhandler(500)(on_500) from .manager_login import manager_do_login app_user_manager.init_user_manager(app, manager_do_login)
ResetPasswordError, PasswordlessLoginError from flask_security.forms import LoginForm, RegisterForm, ForgotPasswordForm, \ ResetPasswordForm, SendConfirmationForm, PasswordlessLoginForm from flask_security.passwordless import send_login_instructions, login_by_token from flask_security.recoverable import reset_by_token, \ send_reset_password_instructions from flask_security.signals import user_registered from flask_security.utils import get_url, get_post_login_redirect, do_flash, \ get_message, config_value, login_user, logout_user, \ anonymous_user_required, url_for_security as url_for # Convenient references _security = LocalProxy(lambda: app.extensions['security']) _datastore = LocalProxy(lambda: _security.datastore) _logger = LocalProxy(lambda: app.logger) def _json_auth_ok(user): return jsonify({ "meta": { "code": 200 }, "response": { "user": { "id": str(user.id), "authentication_token": user.get_auth_token() } }
# # This file is part of Invenio. # Copyright (C) 2017-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # from .signals import secret_key_changed """Invenio-DB utility functions.""" from flask import current_app from sqlalchemy.engine import reflection from werkzeug.local import LocalProxy from .shared import db _db = LocalProxy(lambda: current_app.extensions['sqlalchemy'].db) def rebuild_encrypted_properties(old_key, model, properties): """Rebuild a model's EncryptedType properties when the SECRET_KEY is changed. :param old_key: old SECRET_KEY. :param model: the affected db model. :param properties: list of properties to rebuild. """ inspector = reflection.Inspector.from_engine(db.engine) primary_key_names = inspector.get_primary_keys(model.__tablename__) new_secret_key = current_app.secret_key db.session.expunge_all() try:
def get_cart_class(): key = 'cart' return LocalProxy(import_shop_object(key))
from flask_babelex import lazy_gettext as _ from invenio_drafts_resources.services.records.schema import RecordSchema from marshmallow import ValidationError, fields, post_dump, validates from marshmallow_utils.fields import NestedAttribute from marshmallow_utils.permissions import FieldPermissionsMixin from marshmallow_utils.schemas import IdentifierSchema from werkzeug.local import LocalProxy from .access import AccessSchema from .files import FilesSchema from .metadata import MetadataSchema from .parent import RDMParentSchema from .pids import PIDSchema from .versions import VersionsSchema record_pids_schemes = LocalProxy( lambda: current_app.config["RDM_RECORDS_RECORD_PID_SCHEMES"]) class RDMRecordSchema(RecordSchema, FieldPermissionsMixin): """Record schema.""" field_load_permissions = { 'files': 'update_draft', } # ATTENTION: In this schema you should be using the ``NestedAttribute`` # instead of Marshmallow's ``fields.Nested``. Using NestedAttribute # ensures that the nested schema will receive the system field instead of # the record dict (i.e. record.myattr instead of record['myattr']). pids = fields.Dict(keys=fields.String(), values=fields.Nested(PIDSchema))
# # Swiss Open Access Repository is free software; you can redistribute it # and/or modify it under the terms of the MIT License; see LICENSE file for # more details. """Utility methods to help find, authenticate or register a remote user.""" from __future__ import absolute_import, print_function from urllib.parse import urlparse import uritools from flask import current_app, request from slugify import slugify from werkzeug.local import LocalProxy _security = LocalProxy(lambda: current_app.extensions['security']) _datastore = LocalProxy(lambda: _security.datastore) def get_account_info(attributes, remote_app): """Return account info for remote user. :param attributes: (dict) dictionary of data returned by identity provider. :param remote_app: (str) Identity provider key. :returns: (dict) A dictionary representing user to create or update. """ mappings = current_app.config['SHIBBOLETH_IDENTITY_PROVIDERS'][remote_app][ 'mappings'] # Map data according to configuration
def _lookup_req_object(name): top = _request_ctx_stack.top if top is None: raise RuntimeError(_request_ctx_err_msg) return getattr(top, name) def _lookup_app_object(name): top = _app_ctx_stack.top if top is None: raise RuntimeError(_app_ctx_err_msg) return getattr(top, name) def _find_app(): top = _app_ctx_stack.top if top is None: raise RuntimeError(_app_ctx_err_msg) return top.app # context locals _request_ctx_stack = LocalStack() _app_ctx_stack = LocalStack() current_app = LocalProxy(_find_app) request = LocalProxy(partial(_lookup_req_object, 'request')) session = LocalProxy(partial(_lookup_req_object, 'session')) g = LocalProxy(partial(_lookup_app_object, 'g'))
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Helper proxy to the state object.""" from flask import current_app from werkzeug.local import LocalProxy current_accounts = LocalProxy( lambda: current_app.extensions['invenio-accounts']) """Proxy to the current Invenio-Accounts extension.""" current_security = LocalProxy(lambda: current_app.extensions['security']) """Proxy to the Flask-Security extension.""" current_datastore = LocalProxy( lambda: current_app.extensions['security'].datastore) """Proxy to the current Flask-Security user datastore."""
def authentication_header_handler(apikey, required_scopes=None): try: identity = from_auth_header(apikey) validate(identity) except Exception: login_failure_count.inc() logger.debug("Failed to validate identity header value", exc_info=True) return None return {"uid": identity} def bearer_token_handler(token): try: identity = from_bearer_token(token) validate(identity) except Exception: login_failure_count.inc() logger.debug("Failed to validate bearer token value", exc_info=True) return None return {"uid": identity} def _get_identity(): return connexion.context["user"] current_identity = LocalProxy(_get_identity)
import base64 import jwt import mongoengine import sys import requests from flask import _request_ctx_stack, jsonify, request from functools import wraps from werkzeug.local import LocalProxy from app.app_config import AUTH0_KEY, AUTH0_AUDIENCE from app.constants.response_constants import ResponseConstants as ReCon from app.constants.route_constants import RouteConstants as RoCon from app.non_db_models.action_response import ActionResponse from app.models.user_profiles import UserProfiles current_user = LocalProxy(lambda: _request_ctx_stack.top.current_user) def authenticate(error): response = jsonify(error) response.status_code = 401 return response def requires_authentication(f): @wraps(f) def decorated(*args, **kwargs): auth = request.headers.get(RoCon.HTTP_HEADER_AUTH, None) response = ActionResponse(action_name='authenticate_api') if not auth:
import logging import os.path from builtins import KeyError import flask from flask import Response as response from flask import abort, redirect from flask_mako import TemplateError, render_template from werkzeug.exceptions import Forbidden as HTTPForbidden from werkzeug.exceptions import Unauthorized as HTTPUnauthorized from werkzeug.local import LocalProxy log = logging.getLogger(__name__) config = LocalProxy(lambda: flask.g.request_context['config']) error_document_template = ''' <html> <body> <p>An error occurred in %(prefix)s</p> <p>Error code: %(code)s</p> <p>%(message)s</p> </body> </html> ''' def url(controller, action=None): urlstr = '/{}/'.format(controller) if action != 'index' and action:
from flask import current_app from flask_caching import Cache from flask_sqlalchemy import SQLAlchemy from raven.contrib.flask import Sentry from werkzeug.local import LocalProxy cache = Cache(config={'CACHE_TYPE': 'simple'}) db = SQLAlchemy() sentry = Sentry() interpreter = LocalProxy(lambda: current_app.extensions['interpreter']) def init_app(app): cache.init_app(app) db.init_app(app) sentry.init_app(app)
csrf_cookie_handler, default_want_json, get_config, hash_data, localize_callback, send_mail, string_types, url_for_security, verify_and_update_password, verify_hash, ) from .views import create_blueprint, default_render_json from .cache import VerifyHashCache # Convenient references _security = LocalProxy(lambda: current_app.extensions["security"]) local_cache = Local() # List of authentication mechanisms supported. AUTHN_MECHANISMS = ("basic", "session", "token") #: Default Flask-Security configuration _default_config = { "BLUEPRINT_NAME": "security", "CLI_ROLES_NAME": "roles", "CLI_USERS_NAME": "users", "URL_PREFIX": None, "SUBDOMAIN": None, "FLASH_MESSAGES": True, "I18N_DOMAIN": "flask_security",
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Helper proxy to the state object.""" from __future__ import absolute_import, print_function from flask import current_app from werkzeug.local import LocalProxy current_deposit = LocalProxy(lambda: current_app.extensions['invenio-deposit']) """Helper proxy to access state object."""
import flask from flask import Response, current_app, jsonify, redirect, request, \ send_file, url_for from flask_restful import Resource from flask_restful.utils import cors from werkzeug.local import LocalProxy from werkzeug.utils import secure_filename from .api import IIIFImageAPIWrapper from .decorators import api_decorator, error_handler from .signals import iiif_after_info_request, iiif_after_process_request, \ iiif_before_info_request, iiif_before_process_request from .utils import datetime_to_float, should_cache current_iiif = LocalProxy(lambda: current_app.extensions['iiif']) class IIIFImageBase(Resource): """IIIF Image Base.""" def get(self, version, uuid): """Get IIIF Image Base. .. note:: It will redirect to ``iiifimageinfo`` endpoint with status code 303. """ return redirect(url_for('iiifimageinfo', version=version, uuid=uuid), code=303)
except MKAuthException: # Suppress cookie validation errors from other sites cookies auth_logger.debug('Exception while checking cookie %s: %s' % (cookie_name, traceback.format_exc())) except Exception: auth_logger.debug('Exception while checking cookie %s: %s' % (cookie_name, traceback.format_exc())) return None def set_auth_type(_auth_type): # type: (str) -> None local.auth_type = _auth_type auth_type = LocalProxy(lambda: local.auth_type) # type: Union[str, LocalProxy] @page_registry.register_page("login") class LoginPage(Page): def __init__(self): # type: () -> None super(LoginPage, self).__init__() self._no_html_output = False def set_no_html_output(self, no_html_output): # type: (bool) -> None self._no_html_output = no_html_output def page(self): # type: () -> None
def post(self): """ Create a new user """ request_json = request.get_json(force=True) # Required args for all users try: username = request_json['username'] password = request_json['password'] role_type = request_json['role_type'] except KeyError as e: abort(400, message="Missing required key: {}".format(e)) # If it's a student if role_type == 'student': try: user_token = request_json['user_token'] except KeyError as e: abort(400, message="Student missing required key: {}".format(e)) try: student = Student.query.filter_by(user_token=user_token).one() existing_user = User.query.filter_by(id=student.user_id).first() if existing_user: abort(400, message="This student already belongs to a user") user = User(username, password, role_type) db.session.add(user) db.session.flush() student.user_id = user.id db.session.add(student) db.session.commit() # Log the user in _jwt = LocalProxy(lambda: current_app.extensions['jwt']) identity = _jwt.authentication_callback(username, password) access_token = _jwt.jwt_encode_callback(identity) return _jwt.auth_response_callback(access_token, identity) except NoResultFound: abort(400, message="student user token not found") except IntegrityError: db.session.rollback() abort(400, message="Username already exists") # Add if it's a parent elif role_type == 'parent': try: first_name = request_json['first_name'] last_name = request_json['last_name'] email = request_json['email'] except KeyError as e: abort(400, message="Parent missing required key: {}".format(e)) try: user = User(username, password, role_type) db.session.add(user) db.session.flush() parent = Parent(user_id=user.id, first_name=first_name, last_name=last_name, email=email) db.session.add(parent) db.session.commit() # Log the user in _jwt = LocalProxy(lambda: current_app.extensions['jwt']) identity = _jwt.authentication_callback(username, password) access_token = _jwt.jwt_encode_callback(identity) return _jwt.auth_response_callback(access_token, identity) except IntegrityError: db.session.rollback() abort(400, message="Username already exists") else: abort(400, message="Role type must be parent or student")
if DB_EXTENSION_KEY not in app.extensions: app.extensions[DB_EXTENSION_KEY] = db_session app.db = db_session @app.teardown_appcontext def remove_db_session(exception=None): """Terminates all connections, transactions or stale, in session and checks them back into pool""" db_session.remove() # A little too advanced maybe? skip? def _get_db(): """ Returns ------- sqlalchemy.orm.Session session obj stored in global Flask App. """ if has_app_context(): assert ( DB_EXTENSION_KEY in current_app.extensions ), "`db_session` might not have been registered with the current app" return current_app.extensions[DB_EXTENSION_KEY] raise RuntimeError("No application context found.") db = LocalProxy(_get_db)
Adds simple file handling for different providers to your application. Provides the following providers out of the box: * Local file storeage * Amazon Simple File Storage (requires ``boto`` to be installed) """ from urllib.parse import urljoin from flask import current_app, send_from_directory from flask_store.exceptions import NotConfiguredError from importlib import import_module from werkzeug.local import LocalProxy DEFAULT_PROVIDER = 'flask_store.providers.local.LocalProvider' Provider = LocalProxy(lambda: store_provider()) def store_provider(): """ Returns the default provider class as defined in the application configuration. Returns ------- class The provider class """ store = current_app.extensions['store'] return store.store.Provider
class ArticleForm(WebDepositForm): """Article form.""" # # Fields # doi = fields.TextField( label=_("Digital Object Identifier"), placeholder=_("e.g. 10.1234/foo.bar..."), widget_classes="form-control", icon='fa fa-barcode fa-fw', validators=[ doi_syntax_validator, ], filters=[ strip_string, strip_prefixes("doi:", "http://dx.doi.org/"), ], processors=[ missing_doi_warning, ], ) publication_date = fields.Date( label=_('Publication date'), icon='fa fa-calendar fa-fw', description=_('Required. Format: YYYY-MM-DD.'), default=date.today(), validators=[validators.DataRequired()], widget=date_widget, widget_classes='input-sm', export_key='imprint.date', ) title = fields.TextField( label=_('Title'), export_key='title.title', icon='fa fa-book fa-fw', widget_classes="form-control", validators=[validators.DataRequired()], ) authors = fields.DynamicFieldList( fields.FormField( AuthorInlineForm, widget=ExtendedListWidget( item_widget=ItemWidget(), html_tag='div', ), ), label=_('Authors'), add_label=_('Add another author'), icon='fa fa-user fa-fw', min_entries=1, widget_classes='', export_key='authors', validators=[ validators.DataRequired(), list_length( min_num=1, element_filter=filter_empty_helper(), ) ], ) abstract = fields.TextAreaField( label=_("Description"), description=_('Required.'), default='', icon='fa fa-pencil fa-fw', validators=[ validators.DataRequired(), ], widget=CKEditorWidget( toolbar=[ ['PasteText', 'PasteFromWord'], [ 'Bold', 'Italic', 'Strike', '-', 'Subscript', 'Superscript', ], ['NumberedList', 'BulletedList'], ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'RemoveFormat'], ['SpecialChar', 'ScientificChar'], ['Source'], ['Maximize'], ], disableNativeSpellChecker=False, extraPlugins='scientificchar', removePlugins='elementspath', ), filters=[ sanitize_html(), strip_string, ], export_key='abstract.summary', ) journal_title = fields.TextField( label=_("Journal title"), description=_("Optional."), validators=[ required_if( 'journal_volume', [ lambda x: bool(x.strip()), ], # non-empty message=_("Journal title is required if you specify either " "volume, issue or pages.")), required_if( 'journal_issue', [ lambda x: bool(x.strip()), ], # non-empty message=_("Journal title is required if you specify either " "volume, issue or pages.")), required_if( 'journal_pages', [ lambda x: bool(x.strip()), ], # non-empty message=_("Journal title is required if you specify either " "volume, issue or pages.")), ], export_key='journal_info.title', widget_classes='form-control', ) journal_volume = fields.TextField( label=_("Volume"), description=_("Optional."), export_key='journal_info.volume', widget_classes='form-control', ) journal_issue = fields.TextField( label=_("Issue"), description=_("Optional."), export_key='journal_info.issue', widget_classes='form-control', ) journal_pages = fields.TextField( label=_("Pages"), description=_("Optional."), export_key='journal_info.pagination', widget_classes='form-control', ) language = fields.SelectField( choices=LocalProxy( lambda: language_list_long(enabled_langs_only=False)), default='english', icon='fa fa-globe fa-fw', widget_classes='form-control', ) keywords = fields.DynamicFieldList( fields.TextField( widget_classes='form-control', autocomplete=keywords_autocomplete, widget=ColumnInput(class_="col-xs-10"), ), label=_('Keywords'), add_label=_('Add another keyword'), icon='fa fa-tags fa-fw', widget_classes='', min_entries=1, ) notes = fields.TextAreaField( label=_("Notes"), description=_('Optional.'), default='', validators=[validators.optional()], filters=[ strip_string, ], widget_classes='form-control', icon='fa fa-pencil fa-fw', export_key='comment', ) plupload_file = fields.FileUploadField(label="", widget=plupload_widget, export_key=False) # # Form configuration # _title = _('New article') _subtitle = _('Instructions: (i) Press "Save" to save your upload for ' 'editing later, as many times you like. (ii) Upload or ' 'remove extra files in the bottom of the form. (iii) When ' 'ready, press "Submit" to finalize your upload.') groups = [ ('Basic Information', [ 'doi', 'publication_date', 'title', 'authors', 'abstract', ], { 'indication': 'required', }), ('Journal', ['journal_title', 'journal_volume', 'journal_issue', 'journal_pages'], { 'indication': 'required' }), ('Additional information', ['language', 'keywords', 'notes'], { 'indication': 'optional', }) ] field_sizes = { 'plupload_file': 'col-md-12', }
def get_order_class(): key = 'order' return LocalProxy(import_shop_object(key))
def test_linters_permissions(teacher_user, student_user, test_client, logged_in, assignment_real_works, request, error_template, session, monkeypatch_celery): assignment, single_work = assignment_real_works linter, cfgs = 'Flake8', '' student_user2 = LocalProxy( session.query(m.User).filter_by(name="Student2").one) data = {'name': linter, 'cfg': cfgs} assig_id = assignment.id with logged_in(student_user): test_client.req( 'post', f'/api/v1/assignments/{assig_id}/linter', 403, data=data, result=error_template, ) with logged_in(teacher_user): test_client.req( 'post', f'/api/v1/assignments/{assig_id}/linter', 200, data=data, ) with logged_in(student_user): test_client.req( 'get', f'/api/v1/assignments/{assig_id}/linters/', 403, result=error_template, ) code_id = session.query(m.File.id).filter( m.File.work_id == single_work['id'], m.File.parent != None, # NOQA m.File.name != '__init__.py', ).first()[0] with logged_in(student_user): test_client.req( 'get', f'/api/v1/code/{code_id}', 200, query={'type': 'linter-feedback'}, ) with logged_in(student_user2): # Other student cannot view linter feedback test_client.req( 'get', f'/api/v1/code/{code_id}', 403, query={'type': 'linter-feedback'}, ) with logged_in(teacher_user): linter_result = test_client.req( 'get', f'/api/v1/assignments/{assig_id}/linters/', 200, ) assert any('id' in l for l in linter_result) with logged_in(student_user): for linter in linter_result: if 'id' not in linter: continue test_client.req( 'delete', f'/api/v1/linters/{linter["id"]}', 403, result=error_template, ) with logged_in(teacher_user): for linter in linter_result: if 'id' not in linter: continue test_client.req( 'get', f'/api/v1/linters/{linter["id"]}', 200, )
Alternatively return :class:`~flask.Flask` application object when no blueprint is activated during request. """ return current_app.blueprints.get(request.blueprint, current_app._get_current_object()) # pylint: disable=W0212 def _lookup_breadcrumb_root_path(): """Backend function for breadcrumb_root_path proxy.""" return current_app.config.get('BREADCRUMBS_ROOT') # Proxies # pylint: disable-msg=C0103 #: A proxy for the current function. current_function = LocalProxy(_lookup_current_function) #: A proxy for the current blueprint or application object. current_blueprint = LocalProxy(_lookup_current_blueprint) #: A proxy for breadcrumbs root element path. breadcrumb_root_path = LocalProxy(_lookup_breadcrumb_root_path) #: A proxy for detecting current breadcrumb path. current_path = LocalProxy(Breadcrumbs.current_path) #: A proxy for current breadcrumbs list. current_breadcrumbs = LocalProxy(Breadcrumbs.breadcrumbs) # pylint: enable-msg=C0103
# Copyright (C) 2018 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Zenodo is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Proxies for Zenodo stats module.""" from __future__ import absolute_import, print_function from flask import current_app from werkzeug.local import LocalProxy current_stats_search_client = LocalProxy( lambda: current_app.extensions['zenodo-stats'].search_client) """Proxy to Elasticsearch client used for statistics queries."""
self.ratelimit["storage_url"] = self.app.redis_url def get_flask_dict(self): flattened = {} for cpk in ["cache", "mail", "sendgrid", "app", "ratelimit"]: if cpk in self.keys(): for i in self[cpk]: if cpk == "app": key = i.upper() else: key = "{}_{}".format(cpk, i).upper() flattened[key] = self[cpk][i] # These values are used by flask-cloudy. for key in [ "provider", "key", "secret", "container", "server", "server_url" ]: if key in self.storage: flattened[f"STORAGE_{key}".upper()] = self.storage[key] return flattened def ensure_trailing_slash(d, key): """ Add a slash to the end of a dictionary entry if it doesn't already have one. """ if key in d and d[key] and d[key][-1] != "/": d[key] = d[key] + "/" config = LocalProxy(lambda: current_app.config["THROAT_CONFIG"])
from flask_principal import Principal, RoleNeed, UserNeed, Identity, \ identity_loaded from itsdangerous import URLSafeTimedSerializer from passlib.context import CryptContext from werkzeug.datastructures import ImmutableList from werkzeug.local import LocalProxy from werkzeug.security import safe_str_cmp from .utils import config_value as cv, get_config, md5, url_for_security, string_types from .views import create_blueprint from .forms import LoginForm, ConfirmRegisterForm, RegisterForm, \ ForgotPasswordForm, ChangePasswordForm, ResetPasswordForm, \ SendConfirmationForm, PasswordlessLoginForm # Convenient references _security = LocalProxy(lambda: current_app.extensions['security']) #: Default Flask-Security configuration _default_config = { 'BLUEPRINT_NAME': 'security', 'URL_PREFIX': None, 'SUBDOMAIN': None, 'FLASH_MESSAGES': True, 'PASSWORD_HASH': 'plaintext', 'PASSWORD_SALT': None, 'LOGIN_URL': '/login', 'LOGOUT_URL': '/logout', 'REGISTER_URL': '/register', 'RESET_URL': '/reset', 'CHANGE_URL': '/change',
from flask import url_for, flash, current_app, request, session, redirect, \ render_template from flask.ext.login import login_user as _login_user, \ logout_user as _logout_user from flask.ext.principal import Identity, AnonymousIdentity, identity_changed from werkzeug.local import LocalProxy from .core import current_user from .signals import user_registered, reset_password_instructions_sent, \ login_instructions_sent # Convenient references _security = LocalProxy(lambda: current_app.extensions['security']) _datastore = LocalProxy(lambda: _security.datastore) _pwd_context = LocalProxy(lambda: _security.pwd_context) _logger = LocalProxy(lambda: current_app.logger) def anonymous_user_required(f): @wraps(f) def wrapper(*args, **kwargs): if current_user.is_authenticated(): return redirect(get_url(_security.post_login_view)) return f(*args, **kwargs) return wrapper
def parse_manifest_json(self) -> None: try: with open(self.manifest_file, "r") as f: # the manifest includes non-entry files we only need entries in # templates full_manifest = json.load(f) self.manifest = full_manifest.get("entrypoints", {}) except Exception: # pylint: disable=broad-except pass def get_manifest_files(self, bundle: str, asset_type: str) -> List[str]: if self.app and self.app.debug: self.parse_manifest_json() return self.manifest.get(bundle, {}).get(asset_type, []) APP_DIR = os.path.dirname(__file__) appbuilder = AppBuilder(update_perms=False) cache_manager = CacheManager() celery_app = celery.Celery() db = SQLA() _event_logger: dict = {} event_logger = LocalProxy(lambda: _event_logger.get("event_logger")) feature_flag_manager = FeatureFlagManager() jinja_context_manager = JinjaContextManager() manifest_processor = UIManifestProcessor(APP_DIR) migrate = Migrate() results_backend_manager = ResultsBackendManager() security_manager = LocalProxy(lambda: appbuilder.sm) talisman = Talisman()
from werkzeug.local import LocalProxy from functools import wraps from flask import (session, current_app, request, has_request_context, _request_ctx_stack) from flask_login.signals import user_logged_in, user_login_confirmed, user_logged_out from flask_login.config import COOKIE_NAME, EXEMPT_METHODS current_user = LocalProxy(lambda: _get_user()) def _get_endpoint(): endpoint = request.endpoint try: return endpoint.split('.')[0] except Exception as e: return 'user' def login_user(user, remember=False, duration=None, force=False, fresh=True): if not force and not user.is_active: return False user_id = getattr(user, current_app.login_manager.id_attribute)() session[_get_endpoint() + '_user_id'] = user_id session[_get_endpoint() + '_fresh'] = fresh # 存放浏览器和ip加密信息 session[_get_endpoint() + '_id'] = current_app.login_manager._session_identifier_generator() if remember: session[_get_endpoint() + '_remember'] = 'set' if duration is not None: try:
write concern timeout limit to 2500 milliseconds. """ db = g._database = MongoClient( MFLIX_DB_URI, # TODO: Connection Pooling # Set the maximum connection pool size to 50 active connections. maxPoolSize=50, # TODO: Timeouts # Set the write timeout limit to 2500 milliseconds. wTimeoutMS=2500)[MFLIX_DB_NAME] return db # Use LocalProxy to read the global db instance with just `db` db = LocalProxy(get_db) def get_movies_by_country(countries): """ Finds and returns movies by country. Returns a list of dictionaries, each dictionary contains a title and an _id. """ try: """ Ticket: Projection Write a query that matches movies with the countries in the "countries" list, but only returns the title and _id of each movie. Remember that in MongoDB, the $in operator can be used with a list to
def _save_filing( client_request: LocalProxy, # pylint: disable=too-many-return-statements,too-many-branches business_identifier: str, user: User, filing_id: int ) -> Tuple[Union[Business, RegistrationBootstrap], Filing, dict, int]: """Save the filing to the ledger. If not successful, a dict of errors is returned. Returns: { Business: business model object found for the identifier provided Filing: filing model object for the submitted filing dict: a dict of errors int: the HTTPStatus error code @TODO refactor to a set of single putpose routines } """ json_input = client_request.get_json() if not json_input: return None, None, {'message': f'No filing json data in body of post for {business_identifier}.'}, \ HTTPStatus.BAD_REQUEST if business_identifier.startswith('T'): # bootstrap filing bootstrap = RegistrationBootstrap.find_by_identifier( business_identifier) business = None if not bootstrap: return None, None, { 'message': f'{business_identifier} not found' }, HTTPStatus.NOT_FOUND if client_request.method == 'PUT': rv = db.session.query(Filing). \ filter(Filing.temp_reg == business_identifier). \ filter(Filing.id == filing_id). \ one_or_none() if not rv: return None, None, { 'message': f'{business_identifier} no filings found' }, HTTPStatus.NOT_FOUND filing = rv else: filing = Filing() filing.temp_reg = bootstrap.identifier if not json_input['filing'].get('business'): json_input['filing']['business'] = {} json_input['filing']['business'][ 'identifier'] = bootstrap.identifier else: # regular filing for a business business = Business.find_by_identifier(business_identifier) if not business: return None, None, { 'message': f'{business_identifier} not found' }, HTTPStatus.NOT_FOUND if client_request.method == 'PUT': rv = db.session.query(Business, Filing). \ filter(Business.id == Filing.business_id). \ filter(Business.identifier == business_identifier). \ filter(Filing.id == filing_id). \ one_or_none() if not rv: return None, None, { 'message': f'{business_identifier} no filings found' }, HTTPStatus.NOT_FOUND filing = rv[1] else: filing = Filing() filing.business_id = business.id try: filing.submitter_id = user.id filing.filing_json = json_input filing.source = filing.filing_json['filing']['header'].get( 'source', Filing.Source.LEAR.value) if filing.source == Filing.Source.COLIN.value: try: filing.filing_date = datetime.datetime.fromisoformat( filing.filing_json['filing']['header']['date']) for colin_id in filing.filing_json['filing']['header'][ 'colinIds']: colin_event_id = ColinEventId() colin_event_id.colin_event_id = colin_id filing.colin_event_ids.append(colin_event_id) except KeyError: current_app.logger.error( 'Business:%s missing filing/header values, unable to save', business.identifier) return None, None, { 'message': 'missing filing/header values' }, HTTPStatus.BAD_REQUEST else: filing.filing_date = datetime.datetime.utcnow() # for any legal type, set effective date as set in json; otherwise leave as default filing.effective_date = \ datetime.datetime.fromisoformat(filing.filing_json['filing']['header']['effectiveDate']) \ if filing.filing_json['filing']['header'].get('effectiveDate', None) else datetime.datetime.utcnow() filing.save() except BusinessException as err: return None, None, {'error': err.error}, err.status_code return business or bootstrap, filing, None, None
def insert_record(query, args=()): local_proxy_db = LocalProxy(get_db) local_proxy_db.execute(query, args) local_proxy_db.commit() return
class RoleCreationError(Exception): """Raised when an error occurs when creating a role """ #: App logger for convenience logger = LocalProxy(lambda: current_app.logger) #: Authentication provider auth_provider = LocalProxy(lambda: current_app.auth_provider) #: Login manager login_manager = LocalProxy(lambda: current_app.login_manager) #: Password encyption context pwd_context = LocalProxy(lambda: current_app.pwd_context) #: User datastore user_datastore = LocalProxy(lambda: getattr(current_app, current_app.config[USER_DATASTORE_KEY])) def roles_required(*args): """View decorator which specifies that a user must have all the specified roles. Example:: @app.route('/dashboard') @roles_required('admin', 'editor') def dashboard(): return 'Dashboard' The current user must have both the `admin` role and `editor` role in order
for el in google_objects, twitter_objects: log.debug(el) return google_objects, twitter_objects def get_interested_identities(): objects = getattr(g, 'objects', None) if objects is None: objects = g.objects = load_interested_identities( open(g_identities_source_path, 'r'), open(t_identities_source_path, 'r')) return objects interested_identities = LocalProxy(get_interested_identities) @app.route('/') def main(): state = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in xrange(32)) session['state'] = state return render_template('main.html', GOOGLE_CLIENT_ID=GOOGLE_CLIENT_ID, STATE=state) @app.route('/ttr_auth', methods=['POST', 'GET']) def ttr_auth():