Python flask.g() Examples

The following are 30 code examples of flask.g(). 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 , or try the search function .
Example #1
Source File: utils.py    From pagure with GNU General Public License v2.0 8 votes vote down vote up
def is_admin():
    """ Return whether the user is admin for this application or not. """
    if not authenticated():
        return False

    user = flask.g.fas_user

    auth_method = pagure_config.get("PAGURE_AUTH", None)
    if auth_method == "fas":
        if not user.cla_done:
            return False

    admin_users = pagure_config.get("PAGURE_ADMIN_USERS", [])
    if not isinstance(admin_users, list):
        admin_users = [admin_users]
    if user.username in admin_users:
        return True

    admins = pagure_config["ADMIN_GROUP"]
    if not isinstance(admins, list):
        admins = [admins]
    admins = set(admins or [])
    groups = set(flask.g.fas_user.groups)

    return not groups.isdisjoint(admins) 
Example #2
Source File: server.py    From buku with GNU General Public License v3.0 6 votes vote down vote up
def put(self, rec_id: int):
        bukudb = getattr(flask.g, 'bukudb', get_bukudb())
        result_flag = bukudb.update_rec(
            rec_id,
            request.form.get('url'),
            request.form.get('title'),
            request.form.get('tags'),
            request.form.get('description'))
        if result_flag:
            res = (jsonify(response.response_template['success']),
                   status.HTTP_200_OK,
                   {'ContentType': 'application/json'})
        else:
            res = (jsonify(response.response_template['failure']),
                   status.HTTP_400_BAD_REQUEST,
                   {'ContentType': 'application/json'})
        return res 
Example #3
Source File: flask_app.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def after_request(response):
    """ After request callback, adjust the headers returned """
    csp_headers = pagure_config["CSP_HEADERS"]
    try:
        style_csp = "nonce-" + flask.g.nonce
        script_csp = (
            "unsafe-inline"
            if "unsafe_javascript" in flask.g and flask.g.unsafe_javascript
            else "nonce-" + flask.g.nonce
        )
        csp_headers = csp_headers.format(
            nonce_script=script_csp, nonce_style=style_csp
        )
    except (KeyError, IndexError):
        pass
    response.headers.set(str("Content-Security-Policy"), csp_headers)
    return response 
Example #4
Source File: utils.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def is_repo_admin(repo_obj, username=None):
    """ Return whether the user is an admin of the provided repo. """
    if not authenticated():
        return False

    if username:
        user = username
    else:
        user = flask.g.fas_user.username

    if is_admin():
        return True

    usergrps = [usr.user for grp in repo_obj.admin_groups for usr in grp.users]

    return (
        user == repo_obj.user.user
        or (user in [usr.user for usr in repo_obj.admins])
        or (user in usergrps)
    ) 
Example #5
Source File: flask_app.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def logout():
    """ Log out the user currently logged in in the application
    """
    auth = pagure_config.get("PAGURE_AUTH", None)
    if auth in ["fas", "openid"]:
        if hasattr(flask.g, "fas_user") and flask.g.fas_user is not None:
            from pagure.ui.fas_login import FAS

            FAS.logout()
    elif auth == "oidc":
        from pagure.ui.oidc_login import oidc_logout

        oidc_logout()
    elif auth == "local":
        import pagure.ui.login as login

        login.logout() 
Example #6
Source File: login.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def confirm_user(token):
    """ Confirm a user account.
    """
    user_obj = pagure.lib.query.search_user(flask.g.session, token=token)
    if not user_obj:
        flask.flash("No user associated with this token.", "error")
    else:
        user_obj.token = None
        flask.g.session.add(user_obj)

        try:
            flask.g.session.commit()
            flask.flash("Email confirmed, account activated")
            return flask.redirect(flask.url_for("auth_login"))
        except SQLAlchemyError as err:  # pragma: no cover
            flask.flash(
                "Could not set the account as active in the db, "
                "please report this error to an admin",
                "error",
            )
            _log.exception(err)

    return flask.redirect(flask.url_for("ui_ns.index")) 
Example #7
Source File: flask_app.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def admin_session_timedout():
    """ Check if the current user has been authenticated for more than what
    is allowed (defaults to 15 minutes).
    If it is the case, the user is logged out and the method returns True,
    otherwise it returns False.
    """
    timedout = False
    if not pagure.utils.authenticated():
        return True
    login_time = flask.g.fas_user.login_time
    # This is because flask_fas_openid will store this as a posix timestamp
    if not isinstance(login_time, datetime.datetime):
        login_time = datetime.datetime.utcfromtimestamp(login_time)
    if (datetime.datetime.utcnow() - login_time) > pagure_config.get(
        "ADMIN_SESSION_LIFETIME", datetime.timedelta(minutes=15)
    ):
        timedout = True
        logout()
    return timedout 
Example #8
Source File: context.py    From ctfscoreboard with Apache License 2.0 6 votes vote down vote up
def load_apikey():
    """Load flask.g.user, flask.g.uid from an API key."""
    try:
        key = flask.request.headers.get('X-SCOREBOARD-API-KEY')
        if not key or len(key) != 32:
            return
        user = models.User.get_by_api_key(key)
        if not user:
            return
        flask.g.user = user
        flask.g.uid = user.uid
        flask.g.admin = user.admin
        flask.g.tid = None
        return True
    except Exception:
        # Don't want any API key problems to block requests
        pass


# Add headers to responses 
Example #9
Source File: context.py    From ctfscoreboard with Apache License 2.0 6 votes vote down vote up
def load_globals():
    """Prepopulate flask.g.* with properties."""
    try:
        del flask.g.user
    except AttributeError:
        pass
    try:
        del flask.g.team
    except AttributeError:
        pass
    if load_apikey():
        return
    if (app.config.get('SESSION_EXPIRATION_SECONDS') and
            flask.session.get('expires') and
            flask.session.get('expires') < time.time()):
        flask.session.clear()
    flask.g.uid = flask.session.get('user')
    flask.g.tid = flask.session.get('team')
    flask.g.admin = flask.session.get('admin') or False 
Example #10
Source File: user.py    From fence with Apache License 2.0 6 votes vote down vote up
def download_certificate(certificate):
    if not flask.g.user.application:
        flask.g.user.application = Application()
        current_session.merge(flask.g.user)
    cert = (
        current_session.query(Certificate)
        .filter(Certificate.name == certificate)
        .filter(Certificate.application_id == flask.g.user.application.id)
        .first()
    )
    if cert:
        resp = flask.make_response(cert.data)
        resp.headers["Content-Type"] = "application/octet-stream"
        resp.headers["Content-Disposition"] = "attachment; filename={}.{}".format(
            cert.name, cert.extension
        )
        return resp
    else:
        raise NotFound("No certificate with name {} found".format(certificate)) 
Example #11
Source File: __init__.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def get_locale():
    # if a user is logged in, use the locale from the user settings
    user = getattr(g, 'user', None)
    # user = None
    if user is not None and hasattr(user, "locale"):
        if user.nickname != 'Guest':   # if the account is the guest account bypass the config lang settings
            return user.locale

    preferred = list()
    if request.accept_languages:
        for x in request.accept_languages.values():
            try:
                preferred.append(str(LC.parse(x.replace('-', '_'))))
            except (UnknownLocaleError, ValueError) as e:
                log.debug('Could not parse locale "%s": %s', x, e)

    return negotiate_locale(preferred or ['en'], _BABEL_TRANSLATIONS) 
Example #12
Source File: with_blinker.py    From python-sensor with MIT License 6 votes vote down vote up
def request_finished_with_instana(sender, response, **extra):
    scope = None
    try:
        if not hasattr(flask.g, 'scope'):
            return

        scope = flask.g.scope
        if scope is not None:
            span = scope.span

            if 500 <= response.status_code <= 511:
                span.mark_as_errored()

            span.set_tag(ext.HTTP_STATUS_CODE, int(response.status_code))
            tracer.inject(scope.span.context, opentracing.Format.HTTP_HEADERS, response.headers)
            response.headers.add('Server-Timing', "intid;desc=%s" % scope.span.context.trace_id)
    except:
        logger.debug("Flask after_request", exc_info=True)
    finally:
        if scope is not None:
            scope.close() 
Example #13
Source File: common.py    From python-sensor with MIT License 6 votes vote down vote up
def render_with_instana(wrapped, instance, argv, kwargs):
    ctx = argv[1]

    # If we're not tracing, just return
    if not hasattr(ctx['g'], 'scope'):
        return wrapped(*argv, **kwargs)

    with tracer.start_active_span("render", child_of=ctx['g'].scope.span) as rscope:
        try:
            template = argv[0]

            rscope.span.set_tag("type", "template")
            if template.name is None:
                rscope.span.set_tag("name", '(from string)')
            else:
                rscope.span.set_tag("name", template.name)

            return wrapped(*argv, **kwargs)
        except Exception as e:
            rscope.span.log_exception(e)
            raise 
Example #14
Source File: transfer_account.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def _make_initial_disbursement(self, initial_disbursement, auto_resolve=False):
        from server.utils.credit_transfer import make_payment_transfer

        active_org = getattr(g, 'active_organisation', Organisation.master_organisation())
        initial_disbursement = initial_disbursement or active_org.default_disbursement
        if not initial_disbursement:
            return None

        user_id = get_authorising_user_id()
        if user_id is not None:
            sender = User.query.execution_options(show_all=True).get(user_id)
        else:
            sender = self.primary_user

        disbursement = make_payment_transfer(
            initial_disbursement, token=self.token, send_user=sender, receive_user=self.primary_user,
            transfer_subtype=TransferSubTypeEnum.DISBURSEMENT, transfer_mode=TransferModeEnum.WEB,
            is_ghost_transfer=False, require_sender_approved=False,
            require_recipient_approved=False, automatically_resolve_complete=auto_resolve)

        return disbursement 
Example #15
Source File: request.py    From pre-request with MIT License 6 votes vote down vote up
def catch(self, rule=None, **options):
        """ Catch request params
        """
        def decorator(func):
            @wraps(func)
            def wrapper(*args, **kwargs):
                # ignore with empty rule
                if not rule and not options:
                    return func(*args, **kwargs)

                # parse input params
                try:
                    fmt_rst = self.parse(rule, **options)
                except ParamsValueError as e:
                    return self.fmt_resp(e)

                # assignment params to func args
                from flask import g
                setattr(g, self.store_key, fmt_rst)
                if self.store_key in getfullargspec(func).args:
                    kwargs[self.store_key] = fmt_rst

                return func(*args, **kwargs)
            return wrapper
        return decorator 
Example #16
Source File: server.py    From buku with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, rec_id: Union[int, None]):
        if rec_id is None:
            bukudb = getattr(flask.g, 'bukudb', get_bukudb())
            with mock.patch('buku.read_in', return_value='y'):
                result_flag = bukudb.cleardb()
            if result_flag:
                res = jsonify(response.response_template['success'])
            else:
                res = jsonify(response.response_template['failure'])
                res.status_code = status.HTTP_400_BAD_REQUEST
        else:
            bukudb = getattr(flask.g, 'bukudb', get_bukudb())
            result_flag = bukudb.delete_rec(rec_id)
            if result_flag:
                res = (jsonify(response.response_template['success']),
                       status.HTTP_200_OK,
                       {'ContentType': 'application/json'})
            else:
                res = (jsonify(response.response_template['failure']),
                       status.HTTP_400_BAD_REQUEST,
                       {'ContentType': 'application/json'})
        return res 
Example #17
Source File: server.py    From buku with GNU General Public License v3.0 6 votes vote down vote up
def get(self, starting_id: int, ending_id: int):
        bukudb = getattr(flask.g, 'bukudb', get_bukudb())
        max_id = bukudb.get_max_id()
        if starting_id > max_id or ending_id > max_id:
            return jsonify(response.response_template['failure']), status.HTTP_400_BAD_REQUEST, \
                   {'ContentType': 'application/json'}
        result = {'bookmarks': {}}  # type: ignore
        for i in range(starting_id, ending_id + 1, 1):
            bookmark = bukudb.get_rec_by_id(i)
            result['bookmarks'][i] = {
                'url': bookmark[1],
                'title': bookmark[2],
                'tags': list([_f for _f in bookmark[3].split(',') if _f]),
                'description': bookmark[4]
            }
        res = jsonify(result)
        return res 
Example #18
Source File: server.py    From buku with GNU General Public License v3.0 6 votes vote down vote up
def update_tag(tag):
    res = None
    if request.method in ('PUT', 'POST'):
        new_tags = request.form.getlist('tags')
        result_flag = getattr(flask.g, 'bukudb', get_bukudb()).replace_tag(tag, new_tags)
        op_text = 'replace tag [{}] with [{}]'.format(tag, ', '.join(new_tags))
        if request.method == 'PUT' and result_flag and request.path.startswith('/api/'):
            res = (jsonify(response.response_template['success']),
                   status.HTTP_200_OK,
                   {'ContentType': 'application/json'})
        elif request.method == 'PUT' and request.path.startswith('/api/'):
            res = (jsonify(response.response_template['failure']),
                   status.HTTP_400_BAD_REQUEST,
                   {'ContentType': 'application/json'})
        elif request.method == 'POST' and result_flag:
            flash(Markup('Success {}'.format(op_text)), 'success')
            res = redirect(url_for('get_tags-html'))
        elif request.method == 'POST':
            flash(Markup('Failed {}'.format(op_text)), 'danger')
            res = redirect(url_for('get_tags-html'))
        else:
            abort(400, description="Unknown Condition")
    return res 
Example #19
Source File: server.py    From buku with GNU General Public License v3.0 6 votes vote down vote up
def put(self, starting_id: int, ending_id: int):
        bukudb = getattr(flask.g, 'bukudb', get_bukudb())
        max_id = bukudb.get_max_id()
        if starting_id > max_id or ending_id > max_id:
            return jsonify(response.response_template['failure']), status.HTTP_400_BAD_REQUEST, \
                   {'ContentType': 'application/json'}
        for i in range(starting_id, ending_id + 1, 1):
            updated_bookmark = request.data.get(str(i))  # type: ignore
            result_flag = bukudb.update_rec(
                i,
                updated_bookmark.get('url'),
                updated_bookmark.get('title'),
                updated_bookmark.get('tags'),
                updated_bookmark.get('description'))
            if result_flag is False:
                return (
                    jsonify(response.response_template['failure']),
                    status.HTTP_400_BAD_REQUEST,
                    {'ContentType': 'application/json'})
        res = jsonify(response.response_template['success'])
        return res 
Example #20
Source File: mail.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
def open_changeset_error(place, changeset, r):
    url = place.candidates_url(_external=True)
    username = g.user.username
    body = f'''
user: {username}
name: {place.display_name}
page: {url}

message user: https://www.openstreetmap.org/message/new/{username}

sent:

{changeset}

reply:

{r.text}

'''

    send_mail('error creating changeset:' + place.name, body) 
Example #21
Source File: demo_http_method.py    From safrs with GNU General Public License v3.0 6 votes vote down vote up
def per_request_callbacks(response):
    if response.headers["Content-Type"] != "application/json":
        return response
    try:
        data = json.loads(response.data.decode("utf8"))
        validate(data, schema)
        data["meta"] = data.get("meta", {})
        data["meta"]["validation"] = "ok"
        response.data = json.dumps(data, indent=4)
    except Exception as exc:
        print(exc)
        response.data = b'{"result" : "validation failed"}'

    for func in getattr(g, "call_after_request", ()):
        response = func(response)
    return response 
Example #22
Source File: _localhost_token.py    From webviz-config with MIT License 6 votes vote down vote up
def set_request_decorators(self) -> None:
        # pylint: disable=inconsistent-return-statements
        @self._app.before_request
        def _check_for_ott_or_cookie():  # type: ignore[no-untyped-def]
            if not self._ott_validated and self._ott == flask.request.args.get("ott"):
                self._ott_validated = True
                flask.g.set_cookie_token = True
                return flask.redirect(flask.request.base_url)

            if self._cookie_token == flask.request.cookies.get(
                f"cookie_token_{self._port}"
            ):
                self._ott_validated = True
            else:
                flask.abort(401)

        @self._app.after_request
        def _set_cookie_token_in_response(
            response: flask.wrappers.Response,
        ) -> flask.wrappers.Response:
            if "set_cookie_token" in flask.g and flask.g.set_cookie_token:
                response.set_cookie(
                    key=f"cookie_token_{self._port}", value=self._cookie_token
                )
            return response 
Example #23
Source File: vanilla.py    From python-sensor with MIT License 6 votes vote down vote up
def after_request_with_instana(response):
    scope = None
    try:
        # If we're not tracing, just return
        if not hasattr(flask.g, 'scope'):
            return response

        scope = flask.g.scope
        if scope is not None:
            span = scope.span

            if 500 <= response.status_code <= 511:
                span.mark_as_errored()

            span.set_tag(ext.HTTP_STATUS_CODE, int(response.status_code))
            tracer.inject(scope.span.context, opentracing.Format.HTTP_HEADERS, response.headers)
            response.headers.add('Server-Timing', "intid;desc=%s" % scope.span.context.trace_id)
    except:
        logger.debug("Flask after_request", exc_info=True)
    finally:
        if scope is not None:
            scope.close()
            flask.g.scope = None
        return response 
Example #24
Source File: user.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def send_onboarding_sms_messages(user):

    # First send the intro message
    organisation = getattr(g, 'active_organisation', None) or user.default_organisation

    intro_message = i18n_for(
        user,
        "general_sms.welcome.{}".format(organisation.custom_welcome_message_key or 'generic'),
        first_name=user.first_name,
        balance=rounded_dollars(user.transfer_account.balance),
        token=user.transfer_account.token.name
    )

    send_message(user.phone, intro_message)

    send_terms_message_if_required(user) 
Example #25
Source File: server.py    From buku with GNU General Public License v3.0 5 votes vote down vote up
def delete(self, starting_id: int, ending_id: int):
        bukudb = getattr(flask.g, 'bukudb', get_bukudb())
        max_id = bukudb.get_max_id()
        if starting_id > max_id or ending_id > max_id:
            return jsonify(response.response_template['failure']), status.HTTP_400_BAD_REQUEST, \
                   {'ContentType': 'application/json'}
        idx = min([starting_id, ending_id])
        result_flag = bukudb.delete_rec(idx, starting_id, ending_id, is_range=True)
        if result_flag is False:
            res = jsonify(response.response_template['failure'])
            res.status_code = status.HTTP_400_BAD_REQUEST
        else:
            res = jsonify(response.response_template['success'])
        return res 
Example #26
Source File: vanilla.py    From python-sensor with MIT License 5 votes vote down vote up
def before_request_with_instana(*argv, **kwargs):
    try:
        env = flask.request.environ
        ctx = None

        if 'HTTP_X_INSTANA_T' in env and 'HTTP_X_INSTANA_S' in env:
            ctx = tracer.extract(opentracing.Format.HTTP_HEADERS, env)

        flask.g.scope = tracer.start_active_span('wsgi', child_of=ctx)
        span = flask.g.scope.span

        if hasattr(agent, 'extra_headers') and agent.extra_headers is not None:
            for custom_header in agent.extra_headers:
                # Headers are available in this format: HTTP_X_CAPTURE_THIS
                header = ('HTTP_' + custom_header.upper()).replace('-', '_')
                if header in env:
                    span.set_tag("http.%s" % custom_header, env[header])

        span.set_tag(ext.HTTP_METHOD, flask.request.method)
        if 'PATH_INFO' in env:
            span.set_tag(ext.HTTP_URL, env['PATH_INFO'])
        if 'QUERY_STRING' in env and len(env['QUERY_STRING']):
            scrubbed_params = strip_secrets(env['QUERY_STRING'], agent.secrets_matcher, agent.secrets_list)
            span.set_tag("http.params", scrubbed_params)
        if 'HTTP_HOST' in env:
            span.set_tag("http.host", env['HTTP_HOST'])

        if hasattr(flask.request.url_rule, 'rule') and \
                path_tpl_re.search(flask.request.url_rule.rule) is not None:
            path_tpl = flask.request.url_rule.rule.replace("<", "{")
            path_tpl = path_tpl.replace(">", "}")
            span.set_tag("http.path_tpl", path_tpl)
    except:
        logger.debug("Flask before_request", exc_info=True)
    finally:
        return None 
Example #27
Source File: server.py    From buku with GNU General Public License v3.0 5 votes vote down vote up
def delete(self):
        arg_obj = request.form
        keywords = arg_obj.getlist('keywords')
        all_keywords = arg_obj.get('all_keywords')
        deep = arg_obj.get('deep')
        regex = arg_obj.get('regex')
        # api request is more strict
        all_keywords = False if all_keywords is None else all_keywords
        deep = False if deep is None else deep
        regex = False if regex is None else regex
        all_keywords = (
            all_keywords if isinstance(all_keywords, bool) else
            all_keywords.lower() == 'true'
        )
        deep = deep if isinstance(deep, bool) else deep.lower() == 'true'
        regex = regex if isinstance(regex, bool) else regex.lower() == 'true'
        bukudb = getattr(flask.g, 'bukudb', get_bukudb())
        found_bookmarks = bukudb.searchdb(keywords, all_keywords, deep, regex)
        found_bookmarks = [] if found_bookmarks is None else found_bookmarks
        res = None
        if found_bookmarks is not None:
            for bookmark in found_bookmarks:
                result_flag = bukudb.delete_rec(bookmark[0])
                if result_flag is False:
                    res = jsonify(response.response_template['failure'])
                    res.status = status.HTTP_400_BAD_REQUEST
        if res is None:
            res = jsonify(response.response_template['success'])
        return res 
Example #28
Source File: testing.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_test_client_context_binding(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            flask.g.value = 42
            return 'Hello World!'

        @app.route('/other')
        def other():
            1 // 0

        with app.test_client() as c:
            resp = c.get('/')
            self.assert_equal(flask.g.value, 42)
            self.assert_equal(resp.data, b'Hello World!')
            self.assert_equal(resp.status_code, 200)

            resp = c.get('/other')
            self.assert_false(hasattr(flask.g, 'value'))
            self.assert_in(b'Internal Server Error', resp.data)
            self.assert_equal(resp.status_code, 500)
            flask.g.value = 23

        try:
            flask.g.value
        except (AttributeError, RuntimeError):
            pass
        else:
            raise AssertionError('some kind of exception expected') 
Example #29
Source File: g.py    From python-webapp-example with GNU General Public License v3.0 5 votes vote down vote up
def get_db():
    # pylint: disable=redefined-outer-name
    db = getattr(flask.g, '_database', None)
    if db is None:
        db = flask.g._database = psycopg2.connect(
            'dbname=webapp',
            cursor_factory=psycopg2.extras.DictCursor,
        )
    return db 
Example #30
Source File: basic.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_get_method_on_g(self):
        app = flask.Flask(__name__)
        app.testing = True

        with app.app_context():
            self.assert_equal(flask.g.get('x'), None)
            self.assert_equal(flask.g.get('x', 11), 11)
            flask.g.x = 42
            self.assert_equal(flask.g.get('x'), 42)
            self.assert_equal(flask.g.x, 42)