Python flask.session() Examples

The following are 30 code examples of flask.session(). 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: oauth_tester.py    From app with MIT License 7 votes vote down vote up
def demo():
    """Step 1: User Authorization.
    Redirect the user/resource owner to the OAuth provider (i.e. SimpleLogin)
    using an URL with a few key OAuth parameters.
    """
    simplelogin = OAuth2Session(
        client_id, redirect_uri="http://127.0.0.1:5000/callback"
    )
    authorization_url, state = simplelogin.authorization_url(authorization_base_url)

    # State is used to prevent CSRF, keep this for later.
    session["oauth_state"] = state
    return redirect(authorization_url)


# Step 2: User authorization, this happens on the provider. 
Example #2
Source File: app.py    From oabot with MIT License 7 votes vote down vote up
def get_random_edit():
    # Check first that we are logged in
    access_token =flask.session.get('access_token', None)
    if not access_token:
        return flask.redirect(flask.url_for('login', next_url=flask.url_for('get_random_edit')))

    # Then, redirect to a random cached edit
    for page_name in list_cache_contents():
        # Randomly skip or pick the current one, about 1 % chance.
        if random() > 0.01:
            continue

        cache_fname = "cache/"+to_cache_name(page_name)
        with open(cache_fname, 'r') as f:
            page_json = json.load(f)

        proposed_edits = page_json.get('proposed_edits', [])
        proposed_edits = [template_edit for template_edit in proposed_edits if (template_edit['classification'] != 'rejected')]
        if proposed_edits:
            edit_idx = randint(0, len(proposed_edits)-1)
            orig_hash = proposed_edits[edit_idx]['orig_hash']
            return flask.redirect(
                flask.url_for('review_one_edit', name=page_name, edit=orig_hash))

    return flask.redirect(flask.url_for('index')) 
Example #3
Source File: developers.py    From jbox with MIT License 6 votes vote down vote up
def modificate_integration(dev_key, integration_id):
    if not request.json or not 'channel' in request.json:
        abort(400)
    developer = get_developer_with_devkey(dev_key)
    integration = Integration.query.filter_by(developer_id=developer.id, integration_id=integration_id).first()
    if integration is None:
        abort(400)
    integration.channel.channel = request.json['channel']
    if 'name' in request.json:
        integration.name = request.json['name']
    if 'description' in request.json:
        integration.description = request.json['description']
    if 'icon' in request.json:
        integration.icon = request.json['icon']
    db.session.add(integration)
    try:
        db.session.commit()
    except:
        db.session.rollback()
        abort(500)
    return jsonify({'modification': True}), 200


# 保存 github 集成,将所选的仓库与之前的仓库比较,新增则生成 webhook, 否则去掉之前的 webhook 
Example #4
Source File: developers.py    From jbox with MIT License 6 votes vote down vote up
def modify_developer(dev_key):
    developer = Developer.query.filter_by(dev_key=dev_key).first()
    if developer is None:
        abort(404)
    if 'name' in request.json:
        developer.username = request.json['name']
    if 'desc' in request.json:
        developer.description = request.json['desc']
    if 'avatar' in request.json:
        developer.avatar = request.json['avatar']
    if 'email' in request.json:
        developer.email = request.json['email']
    db.session.add(developer)
    try:
        db.session.commit()
        return jsonify({'modified': True}), 200
    except:
        db.session.rollback()
        abort(500)


# 在dev_key 下创建一个 channel 
Example #5
Source File: flask_pyoidc.py    From Flask-pyoidc with Apache License 2.0 6 votes vote down vote up
def _logout(self):
        logger.debug('user logout')
        try:
            session = UserSession(flask.session)
        except UninitialisedSession as e:
            logger.info('user was already logged out, doing nothing')
            return None

        id_token_jwt = session.id_token_jwt
        client = self.clients[session.current_provider]
        session.clear()

        if client.provider_end_session_endpoint:
            flask.session['end_session_state'] = rndstr()

            end_session_request = EndSessionRequest(id_token_hint=id_token_jwt,
                                                    post_logout_redirect_uri=self._get_post_logout_redirect_uri(client),
                                                    state=flask.session['end_session_state'])

            logger.debug('send endsession request: %s', end_session_request.to_json())

            return redirect(end_session_request.request(client.provider_end_session_endpoint), 303)
        return None 
Example #6
Source File: flask_pyoidc.py    From Flask-pyoidc with Apache License 2.0 6 votes vote down vote up
def _authenticate(self, client, interactive=True):
        if not client.is_registered():
            self._register_client(client)

        flask.session['destination'] = flask.request.url
        flask.session['state'] = rndstr()
        flask.session['nonce'] = rndstr()

        # Use silent authentication for session refresh
        # This will not show login prompt to the user
        extra_auth_params = {}
        if not interactive:
            extra_auth_params['prompt'] = 'none'

        login_url = client.authentication_request(flask.session['state'],
                                                  flask.session['nonce'],
                                                  extra_auth_params)

        auth_params = dict(parse_qsl(login_url.split('?')[1]))
        flask.session['fragment_encoded_response'] = AuthResponseHandler.expect_fragment_encoded_response(auth_params)
        return redirect(login_url) 
Example #7
Source File: views.py    From Bad-Tools with MIT License 6 votes vote down vote up
def index(self):
        ga = FlaskGATracker('www.codingexcuses.com', 'UA-53020725-1')

        for method in self.accepts:
            if self._accepts(method):
                response, path = Which(
                    method,
                    request.args
                ).get_response()

                ga.track(request, session, path=path)
                return response

        # Assume it's a browser
        response, path = Which("text/html", request.args).get_response()
        ga.track(request, session, path=path)
        return response 
Example #8
Source File: flask_pyoidc.py    From Flask-pyoidc with Apache License 2.0 6 votes vote down vote up
def oidc_logout(self, view_func):
        self._logout_view = view_func

        @functools.wraps(view_func)
        def wrapper(*args, **kwargs):
            if 'state' in flask.request.args:
                # returning redirect from provider
                if flask.request.args['state'] != flask.session.pop('end_session_state'):
                    logger.error("Got unexpected state '%s' after logout redirect.", flask.request.args['state'])
                return view_func(*args, **kwargs)

            redirect_to_provider = self._logout()
            if redirect_to_provider:
                return redirect_to_provider

            return view_func(*args, **kwargs)

        return wrapper 
Example #9
Source File: user.py    From Flask-Discord with MIT License 6 votes vote down vote up
def add_to_guild(self, guild_id) -> dict:
        """Method to add user to the guild, provided OAuth2 session has already been created with ``guilds.join`` scope.

        Parameters
        ----------
        guild_id : int
            The ID of the guild you want this user to be added.
            
        Returns
        -------
        dict
            A dict of guild member object. Returns an empty dict if user is already present in the guild.

        Raises
        ------
        flask_discord.Unauthorized
            Raises :py:class:`flask_discord.Unauthorized` if current user is not authorized.

        """
        data = {"access_token": session["DISCORD_OAUTH2_TOKEN"]["access_token"]}
        headers = {"Authorization": f"Bot {current_app.config['DISCORD_BOT_TOKEN']}"}
        return self._request(
            f"/guilds/{guild_id}/members/{self.id}", method="PUT", oauth=False, json=data, headers=headers
        ) or dict() 
Example #10
Source File: test_flask_pyoidc.py    From Flask-pyoidc with Apache License 2.0 6 votes vote down vote up
def test_handle_authentication_response_POST(self):
        access_token = 'test_access_token'
        state = 'test_state'

        authn = self.init_app()
        auth_response = AuthorizationResponse(**{'state': state, 'token_type': 'Bearer', 'access_token': access_token})

        with self.app.test_request_context('/redirect_uri',
                                           method='POST',
                                           data=auth_response.to_dict(),
                                           mimetype='application/x-www-form-urlencoded'):
            UserSession(flask.session, self.PROVIDER_NAME)
            flask.session['destination'] = '/test'
            flask.session['state'] = state
            flask.session['nonce'] = 'test_nonce'
            response = authn._handle_authentication_response()
            session = UserSession(flask.session)
            assert session.access_token == access_token
            assert response == '/test' 
Example #11
Source File: enter_sudo.py    From app with MIT License 6 votes vote down vote up
def enter_sudo():
    password_check_form = LoginForm()

    if password_check_form.validate_on_submit():
        password = password_check_form.password.data

        if current_user.check_password(password):
            session["sudo_time"] = int(time())

            # User comes to sudo page from another page
            next_url = request.args.get("next")
            if next_url:
                LOG.debug("redirect user to %s", next_url)
                return redirect(next_url)
            else:
                LOG.debug("redirect user to dashboard")
                return redirect(url_for("dashboard.index"))
        else:
            flash("Incorrect password", "warning")

    return render_template(
        "dashboard/enter_sudo.html", password_check_form=password_check_form
    ) 
Example #12
Source File: test_flask_pyoidc.py    From Flask-pyoidc with Apache License 2.0 6 votes vote down vote up
def test_token_error_response_calls_to_error_view_if_set(self):
        token_endpoint = self.PROVIDER_BASEURL + '/token'
        error_response = {'error': 'invalid_request', 'error_description': 'test error'}
        responses.add(responses.POST, token_endpoint, json=error_response)

        authn = self.init_app(provider_metadata_extras={'token_endpoint': token_endpoint})
        error_view_mock = self.get_view_mock()
        authn.error_view(error_view_mock)
        state = 'test_tate'
        with self.app.test_request_context('/redirect_uri?code=foo&state={}'.format(state)):
            UserSession(flask.session, self.PROVIDER_NAME)
            flask.session['state'] = state
            flask.session['nonce'] = 'test_nonce'
            result = authn._handle_authentication_response()

        self.assert_view_mock(error_view_mock, result)
        error_view_mock.assert_called_with(**error_response) 
Example #13
Source File: flask_app.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def auth_logout():  # pragma: no cover
    """ Method to log out from the application. """
    return_point = flask.url_for("ui_ns.index")
    if "next" in flask.request.args:
        if pagure.utils.is_safe_url(flask.request.args["next"]):
            return_point = flask.request.args["next"]

    if not pagure.utils.authenticated():
        return flask.redirect(return_point)

    logout()
    flask.flash("You have been logged out")
    flask.session["_justloggedout"] = True
    return flask.redirect(return_point)


# pylint: disable=unused-argument 
Example #14
Source File: level.py    From hackit with Apache License 2.0 6 votes vote down vote up
def autosolve(app):
    if 'autosolve' not in session:
        return None
    if g.user is None:
        return None

    last_res = None
    try:
        for name, idx, password in session['autosolve']:
            app.logger.info('[%s] autosolve %r, %r, %r', g.user, name, idx, password)
            level = routes_by_name[name].levels[idx]
            res = level.solve(password, auto=True)
            if res is not None:
                last_res = res
    except:
        app.logger.exception('[%s] autosolve failed: (%r)', g.user, session['autosolve'])

    del session['autosolve']
    return last_res 
Example #15
Source File: auth.py    From github-stats with MIT License 6 votes vote down vote up
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
    'next': flask.url_for('welcome'),
    'remember': False,
  })
  flask.session.pop('auth-params', None)
  if flask_login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    if user_db.github:
      return flask.redirect(flask.url_for('gh_account', username=user_db.github))
    return flask.redirect(util.get_next_url(auth_params['next']))
  flask.flash('Sorry, but you could not sign in.', category='danger')
  return flask.redirect(flask.url_for('signin')) 
Example #16
Source File: app.py    From hackit with Apache License 2.0 6 votes vote down vote up
def login():
    if g.user is not None:
        return redirect(url_for('index'))

    form = LoginForm(request.form)

    if request.method == 'POST' and form.validate():
        user = users.User.query.filter_by(username=form.username.data).first()
        if user is None:
            flash(u'El usuario no existe')
        elif not user.checkpassword(form.password.data):
            flash(u'Contraseña incorrecta')
            app.logger.info('[%s] login failed', user)
        else:
            flash(u'Bienvenido de nuevo, %s'%user.username)
            session['user_id'] = user.id
            g.user = user
            app.logger.info('[%s] login succeeded', user)
            return level.autosolve(app) or redirect(url_for('index'))

    return redirect(url_for('index')) 
Example #17
Source File: app.py    From oabot with MIT License 6 votes vote down vote up
def login():
    """Initiate an OAuth login.

    Call the MediaWiki server to get request secrets and then redirect
the
    user to the MediaWiki server to sign the request.
    """
    consumer_token = mwoauth.ConsumerToken(
        app.config['CONSUMER_KEY'], app.config['CONSUMER_SECRET'])
    try:
        redirect, request_token = mwoauth.initiate(
            app.config['OAUTH_MWURI'], consumer_token)
    except Exception:
        app.logger.exception('mwoauth.initiate failed')
        return flask.redirect(flask.url_for('index'))
    else:
        flask.session['request_token'] = dict(zip(
            request_token._fields, request_token))
        return flask.redirect(redirect) 
Example #18
Source File: app.py    From hackit with Apache License 2.0 5 votes vote down vote up
def logout():
    session['csrf_token'] = os.urandom(8).encode('hex')
    if 'user_id' in session:
        del session['user_id']
        flash(u'Has cerrado tu sesión')
    return redirect(url_for('index'))

# ====== Levels ====== 
Example #19
Source File: oauth.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def set(self, blueprint, token, user=None, user_id=None):
            uid = first([user_id, self.user_id, blueprint.config.get("user_id")])
            u = first(_get_real_user(ref, self.anon_user)
                      for ref in (user, self.user, blueprint.config.get("user")))

            if self.user_required and not u and not uid:
                raise ValueError("Cannot set OAuth token without an associated user")

            # if there was an existing model, delete it
            existing_query = (
                self.session.query(self.model)
                .filter_by(provider=self.provider_id)
            )
            # check for user ID
            has_user_id = hasattr(self.model, "user_id")
            if has_user_id and uid:
                existing_query = existing_query.filter_by(user_id=uid)
            # check for user (relationship property)
            has_user = hasattr(self.model, "user")
            if has_user and u:
                existing_query = existing_query.filter_by(user=u)
            # queue up delete query -- won't be run until commit()
            existing_query.delete()
            # create a new model for this token
            kwargs = {
                "provider": self.provider_id,
                "token": token,
            }
            if has_user_id and uid:
                kwargs["user_id"] = uid
            if has_user and u:
                kwargs["user"] = u
            self.session.add(self.model(**kwargs))
            # commit to delete and add simultaneously
            self.session.commit()
            # invalidate cache
            self.cache.delete(self.make_cache_key(
                blueprint=blueprint, user=user, user_id=user_id
            )) 
Example #20
Source File: oauth.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, model, session, provider_id,
                     user=None, user_id=None, user_required=None, anon_user=None,
                     cache=None):
            self.provider_id = provider_id
            super(OAuthBackend, self).__init__(model, session, user, user_id, user_required, anon_user, cache) 
Example #21
Source File: flask_app.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def generate_user_key_files():
    """ Regenerate the key files used by gitolite.
    """
    gitolite_home = pagure_config.get("GITOLITE_HOME", None)
    if gitolite_home:
        users = pagure.lib.query.search_user(flask.g.session)
        for user in users:
            pagure.lib.query.update_user_ssh(
                flask.g.session,
                user,
                None,
                pagure_config.get("GITOLITE_KEYDIR", None),
                update_only=True,
            )
    pagure.lib.git.generate_gitolite_acls(project=None) 
Example #22
Source File: utils.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def login_required(function):
    """ Flask decorator to retrict access to logged in user.
    If the auth system is ``fas`` it will also require that the user sign
    the FPCA.
    """

    @wraps(function)
    def decorated_function(*args, **kwargs):
        """ Decorated function, actually does the work. """
        auth_method = pagure_config.get("PAGURE_AUTH", None)
        if flask.session.get("_justloggedout", False):
            return flask.redirect(flask.url_for("ui_ns.index"))
        elif not authenticated():
            return flask.redirect(
                flask.url_for("auth_login", next=flask.request.url)
            )
        elif auth_method == "fas" and not flask.g.fas_user.cla_done:
            flask.session["_requires_fpca"] = True
            flask.flash(
                flask.Markup(
                    'You must <a href="https://admin.fedoraproject'
                    '.org/accounts/">sign the FPCA</a> (Fedora Project '
                    "Contributor Agreement) to use pagure"
                ),
                "errors",
            )
            return flask.redirect(flask.url_for("ui_ns.index"))
        return function(*args, **kwargs)

    return decorated_function 
Example #23
Source File: developers.py    From jbox with MIT License 5 votes vote down vote up
def regenerate_integration_token(integration_id):
    integration = Integration.query.filter_by(integration_id=integration_id).first()
    if integration is None:
        abort(400)
    token = generate_auth_token()
    integration.token = token
    try:
        db.session.add(integration)
        db.session.commit()
        return jsonify({'token': token}), 200
    except:
        db.session.rollback()
        abort(500) 
Example #24
Source File: developers.py    From jbox with MIT License 5 votes vote down vote up
def get_developer_from_session():
    if 'qq_token' in session:
        respMe = qq.get('/oauth2.0/me', {'access_token': session['qq_token'][0]})
        openid = json_to_dict(respMe.data)['openid']
        developer = Developer.query.filter_by(platform_id=openid).first()
        return developer
    return None 
Example #25
Source File: user.py    From Flask-Discord with MIT License 5 votes vote down vote up
def fetch_from_api(cls, guilds=False, connections=False):
        """A class method which returns an instance of this model by implicitly making an
        API call to Discord. The user returned from API will always be cached and update in internal cache.

        Parameters
        ----------
        guilds : bool
            A boolean indicating if user's guilds should be cached or not. Defaults to ``False``. If chose to not
            cache, user's guilds can always be obtained from :py:func:`flask_discord.Guilds.fetch_from_api()`.
        connections : bool
            A boolean indicating if user's connections should be cached or not. Defaults to ``False``. If chose to not
            cache, user's connections can always be obtained from :py:func:`flask_discord.Connections.fetch_from_api()`.

        Returns
        -------
        cls
            An instance of this model itself.
        [cls, ...]
            List of instances of this model when many of these models exist."""
        self = super().fetch_from_api()
        current_app.discord.users_cache.update({self.id: self})
        session["DISCORD_USER_ID"] = self.id

        if guilds:
            self.fetch_guilds()
        if connections:
            self.fetch_connections()

        return self 
Example #26
Source File: app.py    From hackit with Apache License 2.0 5 votes vote down vote up
def delete_account():
    app.logger.warning('[%s] account deleted', g.user)
    users.db.session.delete(g.user)
    users.db.session.commit()
    del session['user_id']
    session['csrf_token'] = os.urandom(8).encode('hex')
    flash(u'Cuenta de usuario borrada')
    return redirect(url_for('index')) 
Example #27
Source File: app.py    From hackit with Apache License 2.0 5 votes vote down vote up
def profile():
    if g.user is None:
        return redirect(url_for('index'))

    form = ProfileForm(request.form)
    form.username.data = g.user.username

    if request.method == 'POST' and form.validate():
        g.user.pubname = form.pubname.data
        g.user.email = form.email.data
        if app.config['USE_SEAT']:
            g.user.seat = form.seat.data

        if form.password.data:
            g.user.changepassword(form.password.data)

        users.db.session.commit()
        app.logger.info('[%s] profile updated %r,%r,%r', g.user, g.user.pubname, g.user.email, g.user.seat)
        flash(u'Perfil actualizado correctamente')
    else:
        form.pubname.data = g.user.pubname
        form.email.data = g.user.email
        if app.config['USE_SEAT']:
            form.seat.data = g.user.seat

    return render_template('profile.html', form=form) 
Example #28
Source File: app.py    From hackit with Apache License 2.0 5 votes vote down vote up
def register():
    if g.user is not None:
        return redirect(url_for('index'))

    form = RegistrationForm(request.form)

    if request.method == 'POST' and form.validate():
        if form.username.data in app.config['BANNED_USERNAMES']:
            form.username.errors.append(u'Buen intento ;)')
            return render_template('register.html', form=form)
        if app.config['USE_SEAT']:
            seat = form.seat.data
        else:
            seat = None
        newuser = users.User(form.username.data, form.password.data,
            form.pubname.data, form.email.data, seat)
        try:
            users.db.session.add(newuser)
            users.db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            form.username.errors.append(u'Ya existe un usuario con ese nombre')
        else:
            flash(u'Te has registrado con éxito. ¡Comienza el desafío!')
            session['user_id'] = newuser.id
            g.user = newuser
            app.logger.info('[%s] Registered %r,%r,%r', g.user, g.user.pubname, g.user.email, g.user.seat)
            return level.autosolve(app) or redirect(url_for('index'))

    return render_template('register.html', form=form) 
Example #29
Source File: common_helpers.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def get_ut_uid():
    """已登录用户获得学号,未登录用户获得user序列ID"""
    if SESSION_CURRENT_USER in session:
        return UTYPE_USER, session[SESSION_CURRENT_USER].identifier
    if SESSION_USER_SEQ in session:
        return UTYPE_GUEST, session[SESSION_USER_SEQ]
    raise NotImplementedError("user seq not exist in session") 
Example #30
Source File: oidc_login.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def fas_user_from_oidc():
    if "oidc_cached_userdata" in flask.session:
        flask.g.fas_user = munch.Munch(**flask.session["oidc_cached_userdata"])
    elif oidc.user_loggedin and "oidc_logintime" in flask.session:
        email_key, fulln_key, usern_key, ssh_key, groups_key = [
            pagure_config["OIDC_PAGURE_EMAIL"],
            pagure_config["OIDC_PAGURE_FULLNAME"],
            pagure_config["OIDC_PAGURE_USERNAME"],
            pagure_config["OIDC_PAGURE_SSH_KEY"],
            pagure_config["OIDC_PAGURE_GROUPS"],
        ]
        info = oidc.user_getinfo(
            [email_key, fulln_key, usern_key, ssh_key, groups_key]
        )
        username = info.get(usern_key)
        if not username:
            fb = pagure_config["OIDC_PAGURE_USERNAME_FALLBACK"]
            if fb == "email":
                username = info[email_key].split("@")[0]
            elif fb == "sub":
                username = flask.g.oidc_id_token["sub"]
        flask.g.fas_user = munch.Munch(
            username=username,
            fullname=info.get(fulln_key, ""),
            email=info[email_key],
            ssh_key=info.get(ssh_key),
            groups=info.get(groups_key, []),
            login_time=flask.session["oidc_logintime"],
        )
        flask.session["oidc_cached_userdata"] = dict(flask.g.fas_user)