Python flask.g.get() Examples

The following are 30 code examples of flask.g.get(). 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.g , or try the search function .
Example #1
Source File: place.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
def name_for_changeset(self):
        address = self.address
        n = self.name
        if not address:
            return self.name
        if isinstance(address, list):
            d = {a['type']: a['name'] for a in address}
        elif isinstance(address, dict):
            d = address

        if d.get('country_code') == 'us':
            state = d.get('state')
            if state and n != state:
                return n + ', ' + state

        country = d.get('country')
        if country and self.name != country:
            return '{} ({})'.format(self.name, country)

        return self.name 
Example #2
Source File: auth.py    From eve-auth-jwt with MIT License 6 votes vote down vote up
def authorized(self, allowed_roles, resource, method):
        authorized = False

        if request.authorization:
            auth = request.authorization
            authorized = self.check_auth(auth.username, auth.password,
                                         allowed_roles, resource, method)
        else:
            try:
                access_token = request.args['access_token']
            except KeyError:
                access_token = request.headers.get('Authorization', '').partition(' ')[2]
            authorized = self.check_token(access_token, allowed_roles, resource, method)

        return authorized 
Example #3
Source File: auth.py    From huskar with MIT License 6 votes vote down vote up
def track_user_qps(response):
    if not request.endpoint:
        return response

    if g.get('auth'):
        name = g.auth.username
        kind = 'app' if g.auth.is_application else 'user'
    else:
        name = 'anonymous'
        kind = 'anonymous'
    tags = dict(kind=kind, name=name)
    if kind == 'app':
        tags.update(appid=name)
    monitor_client.increment('qps.all', tags=tags)
    monitor_client.increment('qps.url', tags=dict(
        endpoint=request.endpoint, method=request.method, **tags))

    return response 
Example #4
Source File: auth.py    From eve-auth-jwt with MIT License 6 votes vote down vote up
def check_token(self, token, allowed_roles, resource, method):
        """
        This function is called when a token is sent throught the access_token
        parameter or the Authorization header as specified in the oAuth 2 specification.

        The provided token is validated with the JWT_SECRET defined in the Eve configuration.
        The token issuer (iss claim) must be the one specified by JWT_ISSUER and the audience
        (aud claim) must be one of the value(s) defined by the either the "audiences" resource
        parameter or the global JWT_AUDIENCES configuration.

        If JWT_ROLES_CLAIM is defined and a claim by that name is present in the token, roles
        are checked using this claim.

        If a JWT_SCOPE_CLAIM is defined and a claim by that name is present in the token, the
        claim value is check, and if "viewer" is present, only GET and HEAD methods will be
        allowed. The scope name is then added to the list of roles with the scope: prefix.

        If the validation succeed, the claims are stored and accessible thru the
        get_authen_claims() method.
        """
        resource_conf = config.DOMAIN[resource]
        audiences = resource_conf.get('audiences', config.JWT_AUDIENCES)
        return self._perform_verification(token, audiences, allowed_roles) 
Example #5
Source File: place.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
def update_from_nominatim(self, hit):
        if self.place_id != int(hit['place_id']):
            print((self.place_id, hit['place_id']))
            self.place_id = hit['place_id']

        keys = ('lat', 'lon', 'display_name', 'place_rank', 'category', 'type',
                'icon', 'extratags', 'namedetails')
        assert all(hit[n] is not None for n in ('lat', 'lon'))
        for n in keys:
            setattr(self, n, hit.get(n))
        bbox = hit['boundingbox']
        assert all(i is not None for i in bbox)
        (self.south, self.north, self.west, self.east) = bbox
        self.address = [dict(name=n, type=t) for t, n in hit['address'].items()]
        self.wikidata = hit['extratags'].get('wikidata')
        self.geom = hit['geotext'] 
Example #6
Source File: place.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
def name(self):
        if self.override_name:
            return self.override_name

        name = self.namedetails.get('name:en') or self.namedetails.get('name')
        display = self.display_name
        if not name:
            return display

        for short in ('City', '1st district'):
            start = len(short) + 2
            if name == short and display.startswith(short + ', ') and ', ' in display[start:]:
                name = display[:display.find(', ', start)]
                break

        return name 
Example #7
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def _get_config(
    value, config_name, default=None,
    required=True, message='CSRF is not configured.'
):
    """Find config value based on provided value, Flask config, and default
    value.

    :param value: already provided config value
    :param config_name: Flask ``config`` key
    :param default: default value if not provided or configured
    :param required: whether the value must not be ``None``
    :param message: error message if required config is not found
    :raises KeyError: if required config is not found
    """

    if value is None:
        value = current_app.config.get(config_name, default)

    if required and value is None:
        raise KeyError(message)

    return value 
Example #8
Source File: i18n.py    From video2commons with GNU General Public License v3.0 6 votes vote down vote up
def getlanguage():
    """Get the user language."""
    gval = g.get('language', None)
    if gval:
        return gval

    for lang in [
        request.form.get('uselang'),
        request.args.get('uselang'),
        session.get('language'),
        request.accept_languages.best,
    ]:
        if lang and _islang(lang):
            break
    else:
        lang = 'en'

    g.language = lang

    return lang 
Example #9
Source File: place.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
def suggest_larger_areas(self):
        ret = []
        for e in reversed(self.is_in() or []):
            osm_type, osm_id, bounds = e['type'], e['id'], e['bounds']
            if osm_type == self.osm_type and osm_id == self.osm_id:
                continue

            box = func.ST_MakeEnvelope(bounds['minlon'], bounds['minlat'],
                                       bounds['maxlon'], bounds['maxlat'], 4326)

            q = func.ST_Area(box.cast(Geography))
            bbox_area = session.query(q).scalar()
            area_in_sq_km = bbox_area / (1000 * 1000)

            if area_in_sq_km < 10 or area_in_sq_km > 40_000:
                continue
            place = Place.from_osm(osm_type, osm_id)
            if not place:
                continue
            place.admin_level = e['tags'].get('admin_level') or None if 'tags' in e else None
            ret.append(place)

        ret.sort(key=lambda place: place.area_in_sq_km)
        return ret 
Example #10
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def _get_csrf_token(self):
        # find the ``csrf_token`` field in the subitted form
        # if the form had a prefix, the name will be
        # ``{prefix}-csrf_token``
        field_name = current_app.config['WTF_CSRF_FIELD_NAME']

        for key in request.form:
            if key.endswith(field_name):
                csrf_token = request.form[key]

                if csrf_token:
                    return csrf_token

        for header_name in current_app.config['WTF_CSRF_HEADERS']:
            csrf_token = request.headers.get(header_name)

            if csrf_token:
                return csrf_token

        return None 
Example #11
Source File: user_api.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def post(self, user_id):

        post_data = request.get_json()
        organisation = g.get('active_organisation')
        if organisation is None:
            return make_response(jsonify({'message': 'Organisation must be set'})), 400

        response_object, response_code = UserUtils.proccess_create_or_modify_user_request(
            post_data,
            organisation=organisation
        )

        if response_code == 200:
            db.session.commit()

        return make_response(jsonify(response_object)), response_code 
Example #12
Source File: __init__.py    From flask-unchained with MIT License 5 votes vote down vote up
def after_init_app(self, app: FlaskUnchained):
        if not app.config.get(
                'LAZY_TRANSLATIONS',
                BabelBundleDevConfig.LAZY_TRANSLATIONS if app.env in {DEV, TEST}
                else BabelBundleProdConfig.LAZY_TRANSLATIONS):
            app.jinja_env.install_gettext_callables(gettext, ngettext, newstyle=True)
        else:
            app.jinja_env.install_gettext_callables(lazy_gettext, lazy_ngettext,
                                                    newstyle=True) 
Example #13
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def validate_csrf_token(self, form, field):
        if g.get('csrf_valid', False):
            # already validated by CSRFProtect
            return

        try:
            validate_csrf(
                field.data,
                self.meta.csrf_secret,
                self.meta.csrf_time_limit,
                self.meta.csrf_field_name
            )
        except ValidationError as e:
            logger.info(e.args[0])
            raise 
Example #14
Source File: __init__.py    From flask-unchained with MIT License 5 votes vote down vote up
def set_url_defaults(self, endpoint: str, values: Dict[str, Any]):
        if self.language_code_key in values or not g.get(self.language_code_key, None):
            return

        if current_app.url_map.is_endpoint_expecting(endpoint, self.language_code_key):
            values[self.language_code_key] = g.lang_code

    # skipcq: PYL-W0613 (unused argument) 
Example #15
Source File: user_api.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def post(self, user_id):

        post_data = request.get_json()
        reset_user_id = post_data.get('user_id')

        if reset_user_id is not None:
            user = User.query.get(reset_user_id)

            if user is None:
                return make_response(jsonify({'message': 'No user found for ID: {}'.format(reset_user_id)})), 404

            UserUtils.admin_reset_user_pin(user)

            response_object = {
                'status': 'success',
                'message': 'Successfully reset pin for user.',
                'data': {
                    'user': user_schema.dump(user).data
                }
            }
            return make_response(jsonify(response_object)), 200
        else:
            response_object = {
                'message': 'No user to reset pin for',
            }
            return make_response(jsonify(response_object)), 400


# add Rules for API Endpoints 
Example #16
Source File: __init__.py    From flask-unchained with MIT License 5 votes vote down vote up
def register_blueprint(self, app: FlaskUnchained, blueprint: Blueprint, **options):
        if app.config.ENABLE_URL_LANG_CODE_PREFIX:
            url_prefix = (options.get('url_prefix', (blueprint.url_prefix or ''))
                                 .rstrip('/'))
            options = dict(**options,
                           url_prefix=self.get_url_rule(url_prefix),
                           register_with_babel=False)
            app.register_blueprint(blueprint, **options) 
Example #17
Source File: __init__.py    From flask-unchained with MIT License 5 votes vote down vote up
def get_locale(self):
        languages = current_app.config.LANGUAGES
        return g.get(self.language_code_key,
                     request.accept_languages.best_match(languages)) 
Example #18
Source File: auth.py    From huskar with MIT License 5 votes vote down vote up
def detect_token_abuse():
    frontend_name = request.headers.get('X-Frontend-Name')
    if (g.auth.is_application and
            frontend_name and frontend_name == settings.ADMIN_FRONTEND_NAME):
        abort(403, 'Using application token in web is not permitted.') 
Example #19
Source File: auth.py    From huskar with MIT License 5 votes vote down vote up
def indicate_minimal_mode(response):
    auth = g.get('auth')
    if auth is not None and auth.is_minimal_mode:
        response.headers['X-Minimal-Mode'] = u'1'
        response.headers['X-Minimal-Mode-Reason'] = \
            unicode(auth.minimal_mode_reason or u'')
    return response 
Example #20
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def generate_csrf(secret_key=None, token_key=None):
    """Generate a CSRF token. The token is cached for a request, so multiple
    calls to this function will generate the same token.

    During testing, it might be useful to access the signed token in
    ``g.csrf_token`` and the raw token in ``session['csrf_token']``.

    :param secret_key: Used to securely sign the token. Default is
        ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
    :param token_key: Key where token is stored in session for comparision.
        Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.
    """

    secret_key = _get_config(
        secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,
        message='A secret key is required to use CSRF.'
    )
    field_name = _get_config(
        token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',
        message='A field name is required to use CSRF.'
    )

    if field_name not in g:
        if field_name not in session:
            session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()

        s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token')
        setattr(g, field_name, s.dumps(session[field_name]))

    return g.get(field_name) 
Example #21
Source File: decorators.py    From flask-security with MIT License 5 votes vote down vote up
def handle_csrf(method):
    """ Invoke CSRF protection based on authentication method.

    Usually this is called as part of a decorator, but if that isn't
    appropriate, endpoint code can call this directly.

    If CSRF protection is appropriate, this will call flask_wtf::protect() which
    will raise a ValidationError on CSRF failure.

    This routine does nothing if any of these are true:

        #) *WTF_CSRF_ENABLED* is set to False

        #) the Flask-WTF CSRF module hasn't been initialized

        #) csrfProtect already checked and accepted the token

    If the passed in method is not in *SECURITY_CSRF_PROTECT_MECHANISMS* then not only
    will no CSRF code be run, but a flag in the current context ``fs_ignore_csrf``
    will be set so that downstream code knows to ignore any CSRF checks.

    .. versionadded:: 3.3.0
    """
    if (
        not current_app.config.get("WTF_CSRF_ENABLED", False)
        or not current_app.extensions.get("csrf", None)
        or g.get("csrf_valid", False)
    ):
        return

    if config_value("CSRF_PROTECT_MECHANISMS"):
        if method in config_value("CSRF_PROTECT_MECHANISMS"):
            _csrf.protect()
        else:
            _request_ctx_stack.top.fs_ignore_csrf = True 
Example #22
Source File: middleware.py    From gitlab-tools with GNU General Public License v3.0 5 votes vote down vote up
def format_task_invoked_by_filter(invoked_by: int) -> str:
    return {
        InvokedByEnum.MANUAL: 'Manual',
        InvokedByEnum.HOOK: 'Web hook',
        InvokedByEnum.SCHEDULER: 'Scheduler',
        InvokedByEnum.UNKNOWN: 'Unknown',
    }.get(invoked_by, 'Unknown')


# Template filters. 
Example #23
Source File: user_api.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def delete(self, user_id):
        user = User.query.execution_options(show_deleted=True).get(user_id)

        if user is None:
            return make_response(jsonify({'message': 'No User Found for ID {}'.format(user_id)})), 404

        try:
            user.delete_user_and_transfer_account()
            response_object, status_code = {'message': 'User {} deleted'.format(user_id)}, 200
            db.session.commit()

        except (ResourceAlreadyDeletedError, TransferAccountDeletionError) as e:
            response_object, status_code = {'message': str(e)}, 400

        return make_response(jsonify(response_object)), status_code 
Example #24
Source File: kobo_auth.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def generate_auth_token(user_id):
    host_list = request.host.rsplit(':')
    if len(host_list) == 1:
        host = ':'.join(host_list)
    else:
        host = ':'.join(host_list[0:-1])
    if host.startswith('127.') or host.lower() == 'localhost' or host.startswith('[::ffff:7f'):
        warning = _('PLease access calibre-web from non localhost to get valid api_endpoint for kobo device')
        return render_title_template(
            "generate_kobo_auth_url.html",
            title=_(u"Kobo Setup"),
            warning = warning
        )
    else:
        # Invalidate any prevously generated Kobo Auth token for this user.
        auth_token = ub.session.query(ub.RemoteAuthToken).filter(
            ub.RemoteAuthToken.user_id == user_id
        ).filter(ub.RemoteAuthToken.token_type==1).first()

        if not auth_token:
            auth_token = ub.RemoteAuthToken()
            auth_token.user_id = user_id
            auth_token.expiration = datetime.max
            auth_token.auth_token = (hexlify(urandom(16))).decode("utf-8")
            auth_token.token_type = 1

            ub.session.add(auth_token)
            ub.session.commit()
        return render_title_template(
            "generate_kobo_auth_url.html",
            title=_(u"Kobo Setup"),
            kobo_auth_url=url_for(
                "kobo.TopLevelEndpoint", auth_token=auth_token.auth_token, _external=True
            ),
            warning = False
        ) 
Example #25
Source File: kobo_auth.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def get_auth_token():
    if "auth_token" in g:
        return g.get("auth_token")
    else:
        return None 
Example #26
Source File: main.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def image(c: str = '') -> wrappers.Response:
    names = c.split('|')
    try:
        requested_cards = oracle.load_cards(names)
        path = image_fetcher.download_image(requested_cards)
        if path is None:
            raise InternalServerError(f'Failed to get image for {c}')
        return send_file(os.path.abspath(path)) # Send abspath to work around monolith root versus web root.
    except TooFewItemsException as e:
        logger.info(f'Did not find an image for {c}: {e}')
        if len(names) == 1:
            return redirect(f'https://api.scryfall.com/cards/named?exact={c}&format=image', code=303)
        return make_response('', 400) 
Example #27
Source File: main.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def export(deck_id: int) -> Response:
    d = ds.load_deck(deck_id)
    if d.is_in_current_run():
        if not session.get('admin') and (not auth.person_id() or auth.person_id() != d.person_id):
            abort(403)
    safe_name = deck_name.file_name(d)
    return make_response(mc.to_mtgo_format(str(d)), 200, {'Content-type': 'text/plain; charset=utf-8', 'Content-Disposition': 'attachment; filename={name}.txt'.format(name=safe_name)}) 
Example #28
Source File: __init__.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def setup_links(menu: List[Dict[str, Any]]) -> None:
    for item in menu:
        if item.get('endpoint'):
            item['url'] = url_for(item.get('endpoint', ''))
        item['is_external'] = cast(str, item.get('url', '')).startswith('http') and '://pennydreadfulmagic.com/' not in item['url']
        setup_links(item.get('submenu', [])) 
Example #29
Source File: auth.py    From eve-auth-jwt with MIT License 5 votes vote down vote up
def get_authen_claims(self):
        return g.get(AUTHEN_CLAIMS, {}) 
Example #30
Source File: __init__.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def get_season_id() -> int:
    season_id = g.get('season_id', rotation.current_season_num())
    if season_id == 'all':
        return 0
    return season_id