Python flask.session.pop() Examples

The following are 30 code examples of flask.session.pop(). 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: google.py    From app with 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 File: facebook.py    From app with 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 File: mod_user.py    From vulpy with 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 #4
Source File: utils.py    From flux-ci with 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 #5
Source File: settings.py    From the-example-app.py with 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 #6
Source File: Scrummage.py    From Scrummage with 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 #7
Source File: mod_user.py    From vulpy with 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 #8
Source File: flask_util.py    From alfred-gmail with 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 #9
Source File: views.py    From website with 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 #10
Source File: flask_util.py    From aqua-monitor with 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 #11
Source File: github.py    From jbox with 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 #12
Source File: views.py    From honeybadger with GNU General Public License v3.0 5 votes vote down vote up
def logout():
    session.pop('user_id', None)
    flash('You have been logged out')
    return redirect(url_for('index')) 
Example #13
Source File: flask_util.py    From alfred-gmail with MIT License 5 votes vote down vote up
def _make_flow(self, return_url=None, **kwargs):
        """Creates a Web Server Flow"""
        # Generate a CSRF token to prevent malicious requests.
        csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest()

        session[_CSRF_KEY] = csrf_token

        state = json.dumps({
            'csrf_token': csrf_token,
            'return_url': return_url
        })

        kw = self.flow_kwargs.copy()
        kw.update(kwargs)

        extra_scopes = kw.pop('scopes', [])
        scopes = set(self.scopes).union(set(extra_scopes))

        flow = client.OAuth2WebServerFlow(
            client_id=self.client_id,
            client_secret=self.client_secret,
            scope=scopes,
            state=state,
            redirect_uri=url_for('oauth2.callback', _external=True),
            **kw)

        flow_key = _FLOW_KEY.format(csrf_token)
        session[flow_key] = pickle.dumps(flow)

        return flow 
Example #14
Source File: auth.py    From zeus with 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 #15
Source File: app.py    From walrus with MIT License 5 votes vote down vote up
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('homepage')) 
Example #16
Source File: manifestbuilder.py    From quay with Apache License 2.0 5 votes vote down vote up
def done(self):
        """
        Marks the manifest builder as complete and disposes of any state.

        This call is optional and it is expected manifest builders will eventually time out if
        unused for an extended period of time.
        """
        session.pop(_SESSION_KEY, None) 
Example #17
Source File: app.py    From walrus with MIT License 5 votes vote down vote up
def get_current_user():
    if session.get('logged_in'):
        try:
            return User.load(session['username'])
        except KeyError:
            session.pop('logged_in')

# View decorator which indicates that the requesting user must be authenticated
# before they can access the wrapped view. The decorator checks the session to
# see if they're logged in, and if not redirects them to the login view. 
Example #18
Source File: app.py    From SteamLens with Apache License 2.0 5 votes vote down vote up
def index():
    return redirect('/pop') 
Example #19
Source File: __init__.py    From ob2 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def oauth_continue():
    if "code" not in request.args or "state" not in request.args:
        return redirect(url_for("onboarding.log_in"))
    code, state = request.args["code"], request.args["state"]
    try:
        try:
            token = authentication_provider_get_token(code, state)
            github = get_username_from_token(token)
        except AuthenticationIntegrityError:
            raise ValidationError("OAuth session expired. Please try again.")
        except AuthenticationTemporaryError:
            logging.exception("Something odd occurred with GitHub OAuth")
            raise ValidationError("GitHub temporary OAuth issue. Please try again.")
    except ValidationError as e:
        return redirect_with_error(url_for("onboarding.log_in"), e)
    authenticate_as_github_username(github)

    # Route the user to the correct onboarding step.
    # OR, if they've finished onboarding, take them to the dashboard.
    # _get_current_step() will perform student dashboard authentication if onboarding is complete.
    current_step = _get_current_step()
    if current_step == "ta.index" and "login_next__ta" in session:
        return redirect(session.pop("login_next__ta"))
    elif current_step == "dashboard.index" and "login_next__dashboard" in session:
        return redirect(session.pop("login_next__dashboard"))
    else:
        return redirect(url_for(current_step)) 
Example #20
Source File: cloud.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def signout(self, hasSessionContext = True):
		if hasSessionContext:
			from flask import session

			logout_user()

			for key in ('identity.name', 'identity.auth_type'):
				session.pop(key, None)

			identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())

		self.remove_logged_user() 
Example #21
Source File: __init__.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def logout():

	logout_user()

	# Remove session keys set by Flask-Principal
	for key in ('identity.id', 'identity.auth_type'):
		session.pop(key,None)

	identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())

	return NO_CONTENT 
Example #22
Source File: app.py    From Awesome-Scripts with MIT License 5 votes vote down vote up
def logout():
    if 'user' in session:
        session.pop('user')
        return 'Logged out!'
    return redirect(url_for('index')) 
Example #23
Source File: session_routes.py    From TemPy with Apache License 2.0 5 votes vote down vote up
def login_handler():
    from templates.session_example.login_page import get_page

    if session.get('messages'):
        page = get_page(messages = session.pop('messages'))
    elif session.get('token') == super_secret_token:
        return redirect(url_for('user_page_handler'))
    else:
        page = get_page()
    return page.render() 
Example #24
Source File: auth.py    From freight with Apache License 2.0 5 votes vote down vote up
def get(self):
        session.pop("uid", None)
        session.pop("access_token", None)
        session.pop("email", None)
        return redirect(url_for(self.complete_url)) 
Example #25
Source File: server.py    From twitter-gender-distribution with Apache License 2.0 5 votes vote down vote up
def logout():
    session.pop("twitter_token")
    session.pop("twitter_user")
    flash("Logged out.")
    return redirect("/") 
Example #26
Source File: oauth.py    From flask-oauth-example with MIT License 5 votes vote down vote up
def callback(self):
        request_token = session.pop('request_token')
        if 'oauth_verifier' not in request.args:
            return None, None, None
        oauth_session = self.service.get_auth_session(
            request_token[0],
            request_token[1],
            data={'oauth_verifier': request.args['oauth_verifier']}
        )
        me = oauth_session.get('account/verify_credentials.json').json()
        social_id = 'twitter$' + str(me.get('id'))
        username = me.get('screen_name')
        return social_id, username, None   # Twitter does not provide email 
Example #27
Source File: mendeley-example.py    From mendeley-api-python-example with Apache License 2.0 5 votes vote down vote up
def logout():
    session.pop('token', None)
    return redirect('/') 
Example #28
Source File: tempy_examples.py    From TemPy with Apache License 2.0 5 votes vote down vote up
def login_handler():
    from templates.session_example.login_page import get_page

    if session.get('messages'):
        page = get_page(messages = session.pop('messages'))
    elif session.get('token') == super_secret_token: 
        return redirect(url_for('user_page_handler'))
    else: 
        page = get_page()
    return page.render() 
Example #29
Source File: tempy_examples.py    From TemPy with Apache License 2.0 5 votes vote down vote up
def logout_handler():
    if session.get('token'):
        session.pop('token')
    session['messages'] = ['Successfuly logged out!']
    return redirect(url_for('login_handler')) 
Example #30
Source File: session_routes.py    From TemPy with Apache License 2.0 5 votes vote down vote up
def logout_handler():
    if session.get('token'):
        session.pop('token')
    session['messages'] = ['Successfuly logged out!']
    return redirect(url_for('login_handler'))