Python flask.session.pop() Examples

The following are 30 code examples of flask.session.pop(). These examples are extracted from open source projects. 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: app   Author: simple-login   File: google.py    License: MIT License 12 votes vote down vote up
def google_login():
    # to avoid flask-login displaying the login error message
    session.pop("_flashes", None)

    next_url = request.args.get("next")

    # Google does not allow to append param to redirect_url
    # we need to pass the next url by session
    if next_url:
        session["google_next_url"] = next_url

    google = OAuth2Session(GOOGLE_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri)
    authorization_url, state = google.authorization_url(_authorization_base_url)

    # State is used to prevent CSRF, keep this for later.
    session["oauth_state"] = state
    return redirect(authorization_url) 
Example #2
Source Project: app   Author: simple-login   File: facebook.py    License: MIT License 7 votes vote down vote up
def facebook_login():
    # to avoid flask-login displaying the login error message
    session.pop("_flashes", None)

    next_url = request.args.get("next")

    # Facebook does not allow to append param to redirect_uri
    # we need to pass the next url by session
    if next_url:
        session["facebook_next_url"] = next_url

    facebook = OAuth2Session(
        FACEBOOK_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri
    )
    facebook = facebook_compliance_fix(facebook)
    authorization_url, state = facebook.authorization_url(_authorization_base_url)

    # State is used to prevent CSRF, keep this for later.
    session["oauth_state"] = state
    return redirect(authorization_url) 
Example #3
Source Project: jbox   Author: jpush   File: github.py    License: MIT License 6 votes vote down vote up
def cancel_github_authorization(dev_key):
    print('cancel github authorization')
    developer = Developer.query.filter_by(dev_key=dev_key).first()
    if developer is None:
        abort(400)
    authorization = Authorization.query.filter_by(developer=developer, type='github').first()
    if authorization:
        try:
            db.session.delete(authorization)
            db.session.commit()
        except:
            db.session.rollback()
            abort(500)
    session.pop('user', None)
    session.pop('github_token', None)
    return jsonify({}), 200 
Example #4
Source Project: website   Author: jazzband-roadies   File: views.py    License: MIT License 6 votes vote down vote up
def consent():
    # redirect to next url when current user has already consented
    if current_user.has_consented:
        return redirect(session.pop("next_url", default_url()))
    form = ConsentForm()

    if form.validate_on_submit():
        current_user.consented_at = datetime.utcnow()
        current_user.profile_consent = True
        current_user.org_consent = True
        current_user.cookies_consent = True
        current_user.age_consent = True
        current_user.save()
        next_url = session.pop("next_url", default_url())
        return redirect(next_url)

    return {"form": form} 
Example #5
Source Project: vulpy   Author: fportantier   File: mod_user.py    License: MIT License 6 votes vote down vote up
def do_create():

    session.pop('username', None)

    if request.method == 'POST':

        username = request.form.get('username')
        password = request.form.get('password')
        email = request.form.get('password')

        session['username'] = libuser.login(username, password)

        if session['username']:
            return redirect('/')

    return render_template('user.create.html') 
Example #6
Source Project: vulpy   Author: fportantier   File: mod_user.py    License: MIT License 6 votes vote down vote up
def do_create():

    session.pop('username', None)

    if request.method == 'POST':

        username = request.form.get('username')
        password = request.form.get('password')
        #email = request.form.get('password')
        if not username or not password:
            flash("Please, complete username and password")
            return render_template('user.create.html')

        libuser.create(username, password)
        flash("User created. Please login.")
        return redirect('/user/login')

        #session['username'] = libuser.login(username, password)

        #if session['username']:
        #    return redirect('/')

    return render_template('user.create.html') 
Example #7
Source Project: aqua-monitor   Author: Deltares   File: flask_util.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def authorize_view(self):
        """Flask view that starts the authorization flow.

        Starts flow by redirecting the user to the OAuth2 provider.
        """
        args = request.args.to_dict()

        # Scopes will be passed as mutliple args, and to_dict() will only
        # return one. So, we use getlist() to get all of the scopes.
        args['scopes'] = request.args.getlist('scopes')

        return_url = args.pop('return_url', None)
        if return_url is None:
            return_url = request.referrer or '/'

        flow = self._make_flow(return_url=return_url, **args)
        auth_url = flow.step1_get_authorize_url()

        return redirect(auth_url) 
Example #8
Source Project: Scrummage   Author: matamorphosis   File: Scrummage.py    License: GNU General Public License v3.0 6 votes vote down vote up
def dropsession():

        try:

            if session.get('user'):
                username = session.get('user')
                session.pop('user', None)
                session.pop('is_admin', False)
                Message = f"Session for user: {username} terminated."
                app.logger.warning(Message)
                Create_Event(Message)

            return render_template('index.html', loggedout=True)

        except Exception as e:
            app.logger.error(e)
            return redirect(url_for('index')) 
Example #9
Source Project: the-example-app.py   Author: contentful   File: settings.py    License: MIT License 6 votes vote down vote up
def reset_settings():
    session.pop('space_id', None)
    session.pop('delivery_token', None)
    session.pop('preview_token', None)
    session.pop('editorial_features', None)

    space = contentful().space(api_id())

    return render_with_globals(
        'settings',
        title=translate('settingsLabel', locale().code),
        errors={},
        has_errors=False,
        success=False,
        space=space,
        host=request.url_root
    ) 
Example #10
Source Project: flux-ci   Author: NiklasRosenstein   File: utils.py    License: MIT License 6 votes vote down vote up
def with_logger(kwarg='logger', stream_dest_kwarg='stream', replace=True):
  ''' Decorator that creates a new :class:`logging.Logger` object
  additionally to or in-place for the *stream* parameter passed to
  the wrapped function. This is usually used in combination with
  the :func:`with_io_response` decorator.

  Note that exceptions with this decorator will be logged and the
  returned status code will be 500 Internal Server Error. '''

  def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
      if replace:
        stream = kwargs.pop(stream_dest_kwarg)
      else:
        stream = kwargs[stream_dest_kwarg]
      kwargs[kwarg] = logger = create_logger(stream)
      try:
        return func(*args, **kwargs)
      except BaseException as exc:
        logger.exception(exc)
        return 500
    return wrapper

  return decorator 
Example #11
Source Project: alfred-gmail   Author: fniephaus   File: flask_util.py    License: MIT License 6 votes vote down vote up
def authorize_view(self):
        """Flask view that starts the authorization flow.

        Starts flow by redirecting the user to the OAuth2 provider.
        """
        args = request.args.to_dict()

        # Scopes will be passed as mutliple args, and to_dict() will only
        # return one. So, we use getlist() to get all of the scopes.
        args['scopes'] = request.args.getlist('scopes')

        return_url = args.pop('return_url', None)
        if return_url is None:
            return_url = request.referrer or '/'

        flow = self._make_flow(return_url=return_url, **args)
        auth_url = flow.step1_get_authorize_url()

        return redirect(auth_url) 
Example #12
Source Project: llvm-zorg   Author: llvm   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def logout():
    session.pop('logged_in', None)
    session.pop('active_user', None)
    flask.flash('You were logged out!')
    return redirect(url_for("index")) 
Example #13
Source Project: calibre-web   Author: janeczku   File: oauth_bb.py    License: GNU General Public License v3.0 5 votes vote down vote up
def logout_oauth_user():
    for oauth_key in oauth_check.keys():
        if str(oauth_key) + '_oauth_user_id' in session:
            session.pop(str(oauth_key) + '_oauth_user_id') 
Example #14
Source Project: jbox   Author: jpush   File: views.py    License: MIT License 5 votes vote down vote up
def logout():
    session.pop('qq_token', None)
    return redirect(url_for('main.index')) 
Example #15
Source Project: Flask-Discord   Author: thec0sm0s   File: client.py    License: MIT License 5 votes vote down vote up
def revoke(self):
        """This method clears current discord token, state and all session data from flask
        `session <http://flask.pocoo.org/docs/1.0/api/#flask.session>`_. Which means user will have
        to go through discord authorization token grant flow again. Also tries to remove the user from internal
        cache if they exist.

        """

        self.users_cache.pop(self.user_id, None)

        for session_key in self.SESSION_KEYS:
            try:
                session.pop(session_key)
            except KeyError:
                pass 
Example #16
Source Project: shamer   Author: yasyf   File: app.py    License: MIT License 5 votes vote down vote up
def preprocess_request():
  if request.endpoint in {'redirect_view', 'proxy_view', 'pending_view', 'leaderboard_view', 'user_leaderboard_view'}:
    if request.view_args.get('object_key'):
      session['object_key'] = request.view_args.get('object_key')
    if session.get('verified') != True:
      session['next'] = request.url
      return redirect(url_for('login_view'))
    if session.get('next'):
      return redirect(session.pop('next'))
    if not s3:
      flash('Your S3 keys are invalid!', 'danger')
      return 'Your S3 keys are invalid!' 
Example #17
Source Project: shamer   Author: yasyf   File: app.py    License: MIT License 5 votes vote down vote up
def callback_view():
  if request.args.get('state') == session.get('state'):
    code = request.args.get('code')
    user = GithubUser(code=code, client_id=constants.get('GH_CLIENT_ID'), secret=constants.get('GH_SECRET'))
    if user.is_valid():
      session['token'] = user.token
      org_verified = user.verify_org(constants.get('GH_ORG'))
      repo_verified = any([user.verify_repo(str(b.repo.id)) for b in bots.values()])
      if org_verified and repo_verified:
        flash('You are now logged in!', 'success')
        session['verified'] = True
      else:
        flash('You do not satisfy the authentication requirements!', 'danger')
        session['verified'] = False
        session['org_verified'] = org_verified
        session['repo_verified'] = repo_verified
        return redirect(url_for('no_auth_view'))
    else:
      flash('Your GitHub credentials are not valid!', 'danger')
      session['verified'] = False
  if session.get('object_key'):
    object_key = session.pop('object_key')
    return redirect(url_for('go_view', object_key=object_key))
  if session.get('next'):
    return redirect(session.pop('next'))
  return redirect(url_for('demo_view')) 
Example #18
Source Project: shamer   Author: yasyf   File: app.py    License: MIT License 5 votes vote down vote up
def hook_view(pull_request_id, object_key):
  repo_name = request.args.get('repo_name')
  if not repo_name:
    return jsonify({'status': 'no repo name'})
  bot = bots.get(repo_name)
  storage = storages.get(repo_name)
  if bot:
    if not pull_request_id.isdigit():
      # pull_request_id is the branch name
      if storage:
        args = request.args.copy().to_dict()
        commit = args.pop('commit_id')
        if commit:
          value = storage.get(pull_request_id, {})
          value[commit] = args
          value['current'] = args
          storage.set(pull_request_id, value)
      try:
        pull_request_id = bot.get_pr_by_branch(pull_request_id).number
      except:
        return jsonify({'status': 'no such pull request'})
    url = url_for('go_view', object_key=object_key, _external=True)
    if bot.process_hook(int(pull_request_id), url, request.args, storage):
      return jsonify({'status': 'success'})
    else:
      return jsonify({'status': 'restarting'})
  return jsonify({'status': 'no bot credentials'}) 
Example #19
Source Project: cloud-asr   Author: UFAL-DSG   File: run.py    License: Apache License 2.0 5 votes vote down vote up
def logout():
    logout_user()

    for key in ['identity.name', 'identity.auth_type']:
        session.pop(key, None)
    identity_changed.send(app, identity=AnonymousIdentity())

    return redirect(url_for('index')) 
Example #20
Source Project: flask-sqlalchemy-web   Author: ypmc   File: start.py    License: MIT License 5 votes vote down vote up
def logout():
    # remove the username from the session if it's there
    logger.debug("logout page")
    session.pop('username', None)
    return redirect(url_for('login')) 
Example #21
Source Project: flask-security   Author: Flask-Middleware   File: utils.py    License: MIT License 5 votes vote down vote up
def logout_user():
    """Logs out the current user.

    This will also clean up the remember me cookie if it exists.

    This sends an ``identity_changed`` signal to note that the current
    identity is now the `AnonymousIdentity`
    """

    for key in ("identity.name", "identity.auth_type", "fs_paa", "fs_gexp"):
        session.pop(key, None)

    # Clear csrf token between sessions.
    # Ideally this would be handled by Flask-WTF but...
    # We don't clear entire session since Flask-Login seems to like having it.
    csrf_field_name = find_csrf_field_name()
    if csrf_field_name:
        session.pop(csrf_field_name, None)
        # Flask-WTF 'caches' csrf_token - and only set the session if not already
        # in 'g'. Be sure to clear both. This affects at least /confirm
        g.pop(csrf_field_name, None)
    session["fs_cc"] = "clear"
    identity_changed.send(
        current_app._get_current_object(), identity=AnonymousIdentity()
    )
    _logout_user() 
Example #22
Source Project: flask-security   Author: Flask-Middleware   File: utils.py    License: MIT License 5 votes vote down vote up
def find_redirect(key):
    """Returns the URL to redirect to after a user logs in successfully.

    :param key: The session or application configuration key to search for
    """
    rv = (
        get_url(session.pop(key.lower(), None))
        or get_url(current_app.config[key.upper()] or None)
        or "/"
    )
    return rv 
Example #23
Source Project: flask-security   Author: Flask-Middleware   File: twofactor.py    License: MIT License 5 votes vote down vote up
def tf_clean_session():
    """
    Clean out ALL stuff stored in session (e.g. on logout)
    """
    if config_value("TWO_FACTOR"):
        for k in [
            "tf_state",
            "tf_user_id",
            "tf_primary_method",
            "tf_remember_login",
            "tf_totp_secret",
        ]:
            session.pop(k, None) 
Example #24
Source Project: Python24   Author: HaoZhang95   File: views.py    License: MIT License 5 votes vote down vote up
def logout():
    # 推出登陆就是从redis中删除session
    session.pop('user_id', None)
    session.pop('mobile', None)
    session.pop('nick_name', None)
    # 不清除admin,会在管理员和普通用户切换过程中,能够以普通用户身份来登陆管理员
    session.pop('is_admin', None)
    return jsonify(errno=RET.OK, errmsg='退出成功') 
Example #25
Source Project: Python24   Author: HaoZhang95   File: demo2.py    License: MIT License 5 votes vote down vote up
def demo32():
    # 删除服务器端的session.pop(), 没有username的话直接返回none
    session.pop('username', None)
    return redirect(url_for('demo3')) 
Example #26
Source Project: Hands-on-Microservices-with-Python   Author: PacktPublishing   File: routes.py    License: MIT License 5 votes vote down vote up
def thank_you():

    if 'user' not in session:
        flash('Please login', 'error')
        return redirect(url_for('frontend.login'))

    if 'order' not in session:
        flash('No order found', 'error')
        return redirect(url_for('frontend.home'))

    session.pop('order', None)
    flash('Thank you for your order', 'success')

    return render_template('order/thankyou.html') 
Example #27
Source Project: bepasty-server   Author: bepasty   File: login.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def post(self):
        # note: remove all session entries that are not needed for logged-out
        # state (because the code has defaults for them if they are missing).
        # if the session is empty. flask will automatically remove the cookie.
        session.pop(LOGGEDIN, None)
        session.pop(PERMISSIONS, None)
        return redirect_next_referrer('bepasty.index') 
Example #28
Source Project: white   Author: whiteclover   File: security.py    License: GNU General Public License v2.0 5 votes vote down vote up
def init_user():
    """Load user if the auth session validates."""
    try:
        user = _guest
        if 'auth' in session:
            uid = session['auth']
            user = Backend('user').find(uid)
        if user is None:
            session.pop('auth', None)
            user = _guest
    except:
        user = _guest
    g.user = user 
Example #29
Source Project: white   Author: whiteclover   File: security.py    License: GNU General Public License v2.0 5 votes vote down vote up
def csrf_protect(f):
    if request.method == "POST":
        token = session.pop('_csrf_token', None)
        if not token or token != request.form.get('_csrf_token'):
            abort(403)

    return f 
Example #30
Source Project: white   Author: whiteclover   File: user.py    License: GNU General Public License v2.0 5 votes vote down vote up
def logout(self):
        session.pop('auth', None)