Python flask.session.clear() Examples

The following are 30 code examples of flask.session.clear(). 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 Project: restpie3   Author: tomimick   File: account.py    License: MIT License 13 votes vote down vote up
def build_session(user_obj, is_permanent=True):
    """On login+signup, builds the server-side session dict with the data we
    need. userid being the most important."""

    assert user_obj
    assert user_obj.id

    # make sure session is empty
    session.clear()

    # fill with relevant data
    session['userid'] = user_obj.id
    session['role'] = user_obj.role # if you update user.role, update this too

    # remember session even over browser restarts?
    session.permanent = is_permanent

    # could also store ip + browser-agent to verify freshness
    # of the session: only allow most critical operations with a fresh
    # session 
Example #2
Source Project: easywall   Author: jpylypiw   File: login.py    License: GNU General Public License v3.0 11 votes vote down vote up
def login_post():
    """
    the function handles the login post request and if all information are correct
    a session variable is set to store the login information
    """
    utils = Webutils()
    hostname = platform.node().encode("utf-8")
    salt = hashlib.sha512(hostname).hexdigest()
    pw_hash = hashlib.sha512(
        str(salt + request.form['password']).encode("utf-8")).hexdigest()
    if request.form['username'] == utils.cfg.get_value(
            "WEB", "username") and pw_hash == utils.cfg.get_value(
                "WEB", "password"):
        session.clear()
        session['logged_in'] = True
        session['ip_address'] = request.remote_addr
        session.permanent = True
        return redirect("/")
    return login("Incorrect username or password.", "danger") 
Example #3
Source Project: 7Eleven-Python   Author: freyta   File: app.py    License: GNU General Public License v3.0 8 votes vote down vote up
def logout():

    # The logout payload is an empty string but it is still needed
    payload = '""'
    tssa = functions.generateTssa(functions.BASE_URL + "account/logout", "POST", payload, session['accessToken'])

    headers = {'User-Agent':'Apache-HttpClient/UNAVAILABLE (java 1.4)',
               'Authorization':'%s' % tssa,
               'X-OsVersion':functions.OS_VERSION,
               'X-OsName':'Android',
               'X-DeviceID':session['DEVICE_ID'],
               'X-VmobID':functions.des_encrypt_string(session['DEVICE_ID']),
               'X-AppVersion':functions.APP_VERSION,
               'X-DeviceSecret':session['deviceSecret'],
               'Content-Type':'application/json; charset=utf-8'}

    response = requests.post(functions.BASE_URL + "account/logout", data=payload, headers=headers)

    # Clear all of the previously set session variables and then redirect to the index page
    session.clear()

    return redirect(url_for('index'))

# The confirmation page for a manual lock in 
Example #4
Source Project: quay   Author: quay   File: test_decorators.py    License: Apache License 2.0 6 votes vote down vote up
def test_extract_namespace_repo_from_session_present(app):
    encountered = []

    def somefunc(namespace, repository):
        encountered.append(namespace)
        encountered.append(repository)

    # Add the namespace and repository to the session.
    session.clear()
    session["namespace"] = "foo"
    session["repository"] = "bar"

    # Call the decorated method.
    extract_namespace_repo_from_session(somefunc)()

    assert encountered[0] == "foo"
    assert encountered[1] == "bar" 
Example #5
Source Project: Ostrich   Author: anantzoid   File: decorators.py    License: MIT License 6 votes vote down vote up
def user_session(func):
    @wraps(func)
    def wrapper(**kwargs):
        from app.models import Utils
        if Utils.getParam(request.args, 'session', default=None):
            user_data = session.get('_user', None)
            if user_data and user_data['is_admin']:
                session.clear()

        user_data = session.get('_user', None)
        kwargs['props'] = {'user': user_data,
                            'cdn': webapp.config['S3_HOST']+'website/',
                            'host': webapp.config['HOST']+'/' 
                          }
        return func(**kwargs)
    return wrapper 
Example #6
Source Project: picoCTF   Author: picoCTF   File: user.py    License: MIT License 5 votes vote down vote up
def logout():
    """Clear the session."""
    session.clear() 
Example #7
Source Project: FXTest   Author: liwanlei   File: views.py    License: MIT License 5 votes vote down vote up
def get(self):
        username = session.get("username")
        session.clear()
        logout_user()
        user = User.query.filter_by(username=username).first()
        user.is_login = False
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('home.login', next=request.url)) 
Example #8
Source Project: cloud-inquisitor   Author: RiotGames   File: wrappers.py    License: Apache License 2.0 5 votes vote down vote up
def __check_auth(self, view):
        headers = {x[0]: x[1] for x in request.headers}
        if 'Authorization' in headers:
            try:
                token = jwt.decode(
                    headers['Authorization'],
                    get_jwt_key_data()
                )

                if token['auth_system'] != current_app.active_auth_system.name:
                    self.log.error('Token is from another auth_system ({}) than the current one ({})'.format(
                        token['auth_system'],
                        current_app.active_auth_system.name
                    ))

                    return view.make_unauth_response()

                if has_access(session['user'], self.role):
                    return

                self.log.error('User {} attempted to access page {} without permissions'.format(
                    session['user'].username,
                    request.path
                ))
                return view.make_unauth_response()

            except (jwt.DecodeError, jwt.ExpiredSignatureError) as ex:
                session.clear()
                view.log.info('Failed to decode signature or it had expired: {0}'.format(ex))
                return view.make_unauth_response()

        session.clear()
        view.log.info('Failed to detect Authorization header')
        return view.make_unauth_response() 
Example #9
Source Project: cloud-inquisitor   Author: RiotGames   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def get(self):
        def dscb():
            session.clear()

        url = self.auth.process_slo(delete_session_cb=dscb)
        errors = self.auth.get_errors()

        if len(errors) == 0:
            if url:
                return self.auth.redirect_to(url)

        return redirect('/logout') 
Example #10
Source Project: Hands-on-Microservices-with-Python   Author: PacktPublishing   File: routes.py    License: MIT License 5 votes vote down vote up
def home():
    # session.clear()
    if current_user.is_authenticated:
        # order = order
        session['order'] = OrderClient.get_order_from_session()

    try:
        products = ProductClient.get_products()
    except requests.exceptions.ConnectionError:
        products = {
            'results': []
        }

    return render_template('home/index.html', products=products)


# Login 
Example #11
Source Project: Hands-on-Microservices-with-Python   Author: PacktPublishing   File: routes.py    License: MIT License 5 votes vote down vote up
def logout():
    session.clear()
    return redirect(url_for('frontend.home'))


# Product page 
Example #12
Source Project: python-scripts   Author: realpython   File: 23_flask_session_test.py    License: MIT License 5 votes vote down vote up
def set():
    session.clear()
    session['works'] = True
    return redirect(url_for('get')) 
Example #13
Source Project: mendeley-api-python-example   Author: Mendeley   File: mendeley-example.py    License: Apache License 2.0 5 votes vote down vote up
def auth_return():
    auth = mendeley.start_authorization_code_flow(state=session['state'])
    mendeley_session = auth.authenticate(request.url)

    session.clear()
    session['token'] = mendeley_session.token

    return redirect('/listDocuments') 
Example #14
Source Project: ckan-multisite   Author: datacats   File: pw.py    License: MIT License 5 votes vote down vote up
def remove_login_cookie():
    session.clear() 
Example #15
Source Project: Cloud-Native-Python   Author: PacktPublishing   File: app.py    License: MIT License 5 votes vote down vote up
def clearsession():
    # Clear the session
    session.clear()
    # Redirect the user to the main page
    return redirect(url_for('main')) 
Example #16
Source Project: Cloud-Native-Python   Author: PacktPublishing   File: app.py    License: MIT License 5 votes vote down vote up
def clearsession():
    # Clear the session
    session.clear()
    # Redirect the user to the main page
    return redirect(url_for('main')) 
Example #17
Source Project: burp-ui   Author: ziirish   File: sessions.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def invalidate_current_session(self):
        """Ivalidate current session"""
        id = getattr(session, 'sid', None)
        session.clear()
        # simulate a logout to clear cookies
        session['remember'] = 'clear'
        return self.invalidate_session_by_id(id, False) 
Example #18
Source Project: burp-ui   Author: ziirish   File: sessions.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def invalidate_session_by_id(self, id, recurse=True):
        """Invalidate a given session"""
        if self.session_managed() and self.backend:
            if not id:
                return True
            try:
                if id == self.get_session_id() and recurse:
                    return self.invalidate_current_session()
            except RuntimeError:
                # in case we are invoked through celery we will never
                # work on the current session
                pass
            key = self.prefix + id
            if not hasattr(self.app.session_interface, 'serializer'):
                return False
            # if we are working on the current session that have been freshly
            # created, its content has not been dumped yet
            dump = self.backend.get(key)
            if dump:
                sess = self.app.session_interface.serializer.loads(dump)
                sess.clear()
                sess['remember'] = 'clear'
                ttl = self.backend.ttl(key)
                val = self.app.session_interface.serializer.dumps(dict(sess))
                self.backend.setex(name=key, value=val, time=ttl)
            # make sure to remove the current user cache
            if self.app.auth != 'none':
                handler = self.app.uhandler
                users = getattr(handler, 'users', {})
                user = self.get_session_username_by_id(id)
                if user and user in users:
                    users.pop(user)
                if id in users:
                    users.pop(id)
        return True 
Example #19
Source Project: flask-gopher   Author: michael-lazar   File: run_server.py    License: GNU General Public License v3.0 5 votes vote down vote up
def demo_session(action):
    if action == 'create':
        session['id'] = request.environ['SEARCH_TEXT']
    elif action == 'delete':
        session.clear()
    return gopher.render_menu_template('demo_session.gopher', action=action) 
Example #20
Source Project: Loki   Author: Pure-L0G1C   File: loki.py    License: MIT License 5 votes vote down vote up
def logout():
    session.clear()
    return redirect(url_for('index')) 
Example #21
Source Project: quay   Author: quay   File: test_decorators.py    License: Apache License 2.0 5 votes vote down vote up
def test_extract_namespace_repo_from_session_missing(app):
    def emptyfunc():
        pass

    session.clear()
    with pytest.raises(HTTPException):
        extract_namespace_repo_from_session(emptyfunc)() 
Example #22
Source Project: listenbrainz-server   Author: metabrainz   File: login.py    License: GNU General Public License v2.0 5 votes vote down vote up
def logout():
    session.clear()
    logout_user()
    return redirect(url_for('index.index')) 
Example #23
Source Project: zeus   Author: getsentry   File: auth.py    License: Apache License 2.0 5 votes vote down vote up
def logout():
    session.clear()
    g.current_user = None
    g.current_tenant = None
    with sentry_sdk.configure_scope() as scope:
        scope.user = None 
Example #24
Source Project: zeus   Author: getsentry   File: auth.py    License: Apache License 2.0 5 votes vote down vote up
def get_redirect_target(clear=True, session=session) -> Optional[str]:
    if clear:
        session_target = session.pop("next", None)
    else:
        session_target = session.get("next")

    for target in request.values.get("next"), session_target:
        if not target:
            continue

        if is_safe_url(target):
            return target
    return None 
Example #25
Source Project: notifications-admin   Author: alphagov   File: user.py    License: MIT License 5 votes vote down vote up
def sign_out(self):
        session.clear()
        # Update the db so the server also knows the user is logged out.
        self.update(current_session_id=None)
        logout_user() 
Example #26
Source Project: marvin   Author: sdss   File: index.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clear_session(self):
        current_session.clear()
        return jsonify(result=dict(current_session)) 
Example #27
Source Project: auth0-python-web-app   Author: auth0-samples   File: server.py    License: MIT License 5 votes vote down vote up
def logout():
    session.clear()
    params = {'returnTo': url_for('home', _external=True), 'client_id': AUTH0_CLIENT_ID}
    return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params)) 
Example #28
Source Project: confidant   Author: lyft   File: userauth.py    License: Apache License 2.0 5 votes vote down vote up
def clear_session(self):
        logger.info('Clearing flask session')
        session['user'] = {}
        session.clear() 
Example #29
Source Project: confidant   Author: lyft   File: userauth.py    License: Apache License 2.0 5 votes vote down vote up
def log_out(self):
        """
        Initiate SAML SLO redirect.
        """

        logger.info('Initiating SAML logout request')

        try:
            current_nameid = self._current_user_nameid()
            current_session_id = self._current_saml_session_id()
        except errors.UserUnknownError:
            # must be already logged out
            logger.warning('No SAML data in session. Cannot SLO log out')
            self.clear_session()
            return self.redirect_to_goodbye()

        auth = self._saml_auth()

        # check for SLO support
        if not auth.get_slo_url():
            logger.warning('No SingleLogOut endpoint defined for IdP')
            self.clear_session()
            return self.redirect_to_goodbye()

        # TODO: decide whether to always clear the session here or not. Relying
        # on the IDP to redirect back to us hasn't been super reliable.
        self.clear_session()

        # redirect to SLO endpoint
        return flask.redirect(auth.logout(name_id=current_nameid,
                                          session_index=current_session_id)) 
Example #30
Source Project: PowerDNS-Admin   Author: ngoduykhanh   File: index.py    License: MIT License 5 votes vote down vote up
def clear_session():
    session.pop('user_id', None)
    session.pop('github_token', None)
    session.pop('google_token', None)
    session.pop('authentication_type', None)
    session.pop('remote_user', None)
    session.clear()
    logout_user()