Python flask.session.modified() Examples

The following are 19 code examples of flask.session.modified(). 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.session , or try the search function .
Example #1
Source File: dashboard.py    From PowerDNS-Admin with MIT License 17 votes vote down vote up
def before_request():
    # Check if user is anonymous
    g.user = current_user
    login_manager.anonymous_user = Anonymous

    # Check site is in maintenance mode
    maintenance = Setting().get('maintenance')
    if maintenance and current_user.is_authenticated and current_user.role.name not in [
            'Administrator', 'Operator'
    ]:
        return render_template('maintenance.html')

    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #2
Source File: index.py    From PowerDNS-Admin with MIT License 12 votes vote down vote up
def before_request():
    # Check if user is anonymous
    g.user = current_user
    login_manager.anonymous_user = Anonymous

    # Check site is in maintenance mode
    maintenance = Setting().get('maintenance')
    if maintenance and current_user.is_authenticated and current_user.role.name not in [
            'Administrator', 'Operator'
    ]:
        return render_template('maintenance.html')

    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #3
Source File: domain.py    From PowerDNS-Admin with MIT License 10 votes vote down vote up
def before_request():
    # Check if user is anonymous
    g.user = current_user
    login_manager.anonymous_user = Anonymous

    # Check site is in maintenance mode
    maintenance = Setting().get('maintenance')
    if maintenance and current_user.is_authenticated and current_user.role.name not in [
            'Administrator', 'Operator'
    ]:
        return render_template('maintenance.html')

    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #4
Source File: user.py    From PowerDNS-Admin with MIT License 7 votes vote down vote up
def before_request():
    # Check if user is anonymous
    g.user = current_user
    login_manager.anonymous_user = Anonymous

    # Check site is in maintenance mode
    maintenance = Setting().get('maintenance')
    if maintenance and current_user.is_authenticated and current_user.role.name not in [
            'Administrator', 'Operator'
    ]:
        return render_template('maintenance.html')

    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #5
Source File: backend.py    From docassemble with MIT License 6 votes vote down vote up
def update_session(i, uid=None, encrypted=None, key_logged=None, chatstatus=None):
    if 'sessions' not in session:
        session['sessions'] = dict()
    if i not in session['sessions'] or uid is not None:
        if uid is None:
            raise Exception("update_session: cannot create new session without a uid")
        if encrypted is None:
            encrypted = True
        if key_logged is None:
            key_logged = False
        if chatstatus is None:
            chatstatus = 'off'
        session['sessions'][i] = dict(uid=uid, encrypted=encrypted, key_logged=key_logged, chatstatus=chatstatus)
    else:
        if uid is not None:
            session['sessions'][i]['uid'] = uid
        if encrypted is not None:
            session['sessions'][i]['encrypted'] = encrypted
        if key_logged is not None:
            session['sessions'][i]['key_logged'] = key_logged
        if chatstatus is not None:
            session['sessions'][i]['chatstatus'] = chatstatus
    session.modified = True
    return session['sessions'][i] 
Example #6
Source File: admin.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def before_request():
    # Manage session timeout
    session.permanent = True
    current_app.permanent_session_lifetime = datetime.timedelta(
        minutes=int(Setting().get('session_timeout')))
    session.modified = True 
Example #7
Source File: api.py    From Titan with GNU Affero General Public License v3.0 5 votes vote down vote up
def fetch():
    guild_id = request.args.get("guild_id")
    channel_id = request.args.get('channel_id')
    after_snowflake = request.args.get('after', 0, type=int)
    if user_unauthenticated():
        key = session['user_keys'][guild_id]
    else:
        key = None
    status = update_user_status(guild_id, session['username'], key)
    messages = {}
    if status['banned'] or status['revoked']:
        status_code = 403
        if user_unauthenticated():
            session['user_keys'].pop(guild_id, None)
            session.modified = True
    else:
        chan = filter_guild_channel(guild_id, channel_id)
        if not chan:
            abort(404)
        if not chan.get("read") or chan["channel"]["type"] != "text":
            status_code = 401
        else:
            messages = redisqueue.get_channel_messages(guild_id, channel_id, after_snowflake)
            status_code = 200
    response = jsonify(messages=messages, status=status)
    response.status_code = status_code
    return response 
Example #8
Source File: test_app_compare.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def test_remove_all_from_compare_basket(self):
        with self.frontend.app.test_request_context():
            session['uids_for_comparison'] = [TEST_FW.uid, TEST_FW_2.uid]
            session.modified = True
            assert 'uids_for_comparison' in session
            assert TEST_FW.uid in session['uids_for_comparison']
            assert TEST_FW_2.uid in session['uids_for_comparison']

            CompareRoutes._remove_all_from_compare_basket(self.frontend, 'some_uid')
            assert TEST_FW.uid not in session['uids_for_comparison']
            assert TEST_FW_2.uid not in session['uids_for_comparison'] 
Example #9
Source File: test_app_compare.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def test_remove_from_compare_basket(self):
        with self.frontend.app.test_request_context():
            session['uids_for_comparison'] = [TEST_FW.uid, TEST_FW_2.uid]
            session.modified = True
            assert 'uids_for_comparison' in session
            assert TEST_FW.uid in session['uids_for_comparison']
            assert TEST_FW_2.uid in session['uids_for_comparison']

            CompareRoutes._remove_from_compare_basket(self.frontend, 'some_uid', TEST_FW.uid)
            assert TEST_FW.uid not in session['uids_for_comparison']
            assert TEST_FW_2.uid in session['uids_for_comparison'] 
Example #10
Source File: compare_routes.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def _remove_all_from_compare_basket(self, analysis_uid):
        compare_uid_list = get_comparison_uid_list_from_session()
        compare_uid_list.clear()
        session.modified = True
        return redirect(url_for('analysis/<uid>', uid=analysis_uid)) 
Example #11
Source File: compare_routes.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def _remove_from_compare_basket(self, analysis_uid, compare_uid):
        compare_uid_list = get_comparison_uid_list_from_session()
        if compare_uid in compare_uid_list:
            session['uids_for_comparison'].remove(compare_uid)
            session.modified = True
        return redirect(url_for('analysis/<uid>', uid=analysis_uid)) 
Example #12
Source File: compare_routes.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def _add_to_compare_basket(self, uid):
        compare_uid_list = get_comparison_uid_list_from_session()
        compare_uid_list.append(uid)
        session.modified = True
        return redirect(url_for('analysis/<uid>', uid=uid)) 
Example #13
Source File: provider.py    From acousticbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def _persist_data(**kwargs):
    """Save data in session."""
    if _session_key not in session:
        session[_session_key] = dict()
    session[_session_key].update(**kwargs)
    session.modified = True 
Example #14
Source File: app.py    From flask-react-spa with MIT License 5 votes vote down vote up
def configure_app(app, config_object):
    """General application configuration:

    - register the app's config
    - register Jinja extensions
    - register functions to run on before/after request
    """
    # automatically configure a migrations folder for each bundle
    config_object.ALEMBIC['version_locations'] = [
        (bundle._name, os.path.join(PROJECT_ROOT,
                                    bundle.module_name.replace('.', os.sep),
                                    'migrations'))
        for bundle in app.bundles if bundle.has_models
    ]
    app.config.from_object(config_object)

    app.jinja_env.add_extension('jinja2_time.TimeExtension')

    @app.before_request
    def enable_session_timeout():
        session.permanent = True  # set session to use PERMANENT_SESSION_LIFETIME
        session.modified = True   # reset the session timer on every request

    @app.after_request
    def set_csrf_cookie(response):
        if response:
            response.set_cookie('csrf_token', generate_csrf())
        return response 
Example #15
Source File: home.py    From spendb with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_locale():
    locale = request.json.get('locale')

    if locale is not None:
        session['locale'] = locale
        session.modified = True
    return jsonify({'locale': locale}) 
Example #16
Source File: login.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def signout():
    logout_user()
    for key in ("identity.name", "identity.auth_type"):
        session.pop(key, None)
    session.modified = True
    # Tell Flask-Principal the user is anonymous
    identity_changed.send(
        current_app._get_current_object(), identity=AnonymousIdentity()
    )
    return jsonify({"logged_in": False}) 
Example #17
Source File: login.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def signin():
    json = request.get_json()
    if "username" not in json or "password" not in json:
        raise InvalidUsage("Must supply username or password.")
    user = User.query.filter(User.username == json["username"]).first()
    if user is not None:
        current_app.logger.debug(
            "Login attempt", username=user.username, user_id=user.id
        )
        if user.is_correct_password(json["password"]):
            two_factor = user.two_factor_auth
            if two_factor is not None and two_factor.enabled:
                if "two_factor_code" not in json or json["two_factor_code"] == "":
                    raise InvalidUsage(
                        "Must supply a two-factor authentication code.",
                        payload={"need_two_factor": True},
                    )
                try:
                    two_factor.validate(json["two_factor_code"])
                except (Unauthorized, binascii.Error):
                    two_factor.validate_backup_code(json["two_factor_code"])
            login_user(user, remember=False)
            identity_changed.send(
                current_app._get_current_object(), identity=Identity(user.id)
            )
            session.modified = True
            return jsonify(
                {
                    "logged_in": True,
                    "is_admin": user.is_admin,
                    "require_two_factor_setup": current_user.two_factor_setup_required,
                }
            )
    current_app.logger.debug("Failed login attempt", username=json["username"])
    raise Unauthorized("Incorrect username or password.") 
Example #18
Source File: provider.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def _persist_data(**kwargs):
    """Save data in session."""
    if _session_key not in session:
        session[_session_key] = dict()
    session[_session_key].update(**kwargs)
    session.modified = True 
Example #19
Source File: registry.py    From quay with Apache License 2.0 5 votes vote down vote up
def set_cache_headers(f):
    """
    Returns HTTP headers suitable for caching.
    """

    @wraps(f)
    def wrapper(*args, **kwargs):
        # Set TTL to 1 year by default
        ttl = 31536000
        expires = datetime.fromtimestamp(int(time()) + ttl)
        expires = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
        headers = {
            "Cache-Control": "public, max-age={0}".format(ttl),
            "Expires": expires,
            "Last-Modified": "Thu, 01 Jan 1970 00:00:00 GMT",
        }
        if "If-Modified-Since" in request.headers:
            response = make_response("Not modified", 304)
            response.headers.extend(headers)
            return response
        kwargs["headers"] = headers
        # Prevent the Cookie to be sent when the object is cacheable
        session.modified = False
        return f(*args, **kwargs)

    return wrapper