Python flask.session 模块,pop() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.session.pop()

项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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)
项目:cloud-site    作者:Mengjianhua-c    | 项目源码 | 文件源码
def get(self):
        if request.cookies.get('save_id'):
            resp = make_response(redirect(url_for('.exit')))
            resp.set_cookie('user_name', expires=0)
            resp.set_cookie('login_time', expires=0)
            resp.set_cookie('save_id', expires=0)
            return resp
        if session.get('name'):
            session.pop('name')
        if session.get('show_name'):
            session.pop('show_name')
        if session.get('user_id'):
            session.pop('user_id')
        return redirect(url_for('.login'))


# ?config.json ???? is_register ?false??????? ??????????????
项目:sarjitsu    作者:distributed-system-analysis    | 项目源码 | 文件源码
def logout_user():
    '''
    Logs a user out. (You do not need to pass the actual user.) This will
    also clean up the remember me cookie if it exists.
    '''
    print "LOGOUT CHECK"
    #print session.keys()
    try:
      #if 'user_id' in session:
      # user = User.query.get(session['user_id'])
      # user.current_user = False
      # user.save()
      print "Logged out: %s | %s" % (session.pop('user_id'), 
                                     session.pop('user'))
      return True
    except:
      return False
项目:Anemone    作者:Winnak    | 项目源码 | 文件源码
def projects():
    """ View for projects """
    session.pop("project", None)
    entries = []
    for pro in Project.select():
        status = (Job.select()
                  .where((Job.project == pro) & (Job.result > 0))
                  .order_by(Job.started.desc())
                  .first())

        latest = (Job.select()
                  .where(Job.project == pro)
                  .order_by(Job.started.desc())
                  .first())

        entries.append(dict(name=pro.name, slug=pro.slug,
                            description=pro.description,
                            status=status, latest=latest))


    return render_template("projects.html", entries=entries)
项目:GitDigger    作者:lc-soft    | 项目源码 | 文件源码
def authorized(access_token):
    next_url = session.get('next_url')
    if next_url is None:
        next_url = url_for('index')
    else:
        session.pop('next_url')
    if access_token is None:
        return redirect(next_url)
    session['github_token'] = access_token
    user = github_helper.get_user()
    if user is None:
        return redirect(next_url)
    if current_user.is_authenticated:
        current_user.github_id = user['id']
        current_user.github_token = access_token
        current_user.github_username = user['login']
        if not current_user.avatar_url:
            current_user.avatar_url = user['avatar_url']
        db.session.commit()
        return redirect(next_url)
    user = User.query.filter_by(github_id=user['id']).first()
    if user is not None:
        login_user(user)
    return redirect(next_url)
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
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)
项目:docklet    作者:unias    | 项目源码 | 文件源码
def internal_server_error(error):
    logger.error(error)
    logger.error(traceback.format_exc())
    if "username" in session:
        if "500" in session and "500_title" in session:
            reason = session['500']
            title = session['500_title']
            session.pop('500', None)
            session.pop('500_title', None)
        else:
            reason = '''The server encountered something unexpected that didn't allow it to complete the request. We apologize.You can go back to
<a href="/dashboard/">dashboard</a> or <a href="/logout">log out</a>'''
            title = 'Internal Server Error'
        return render_template('error/500.html', mysession = session, reason = reason, title = title)
    else:
        return redirect('/login/')
项目:dodscp    作者:seancallaway    | 项目源码 | 文件源码
def changepass():
    if request.method == 'POST':
        # process password change
        if request.form['pass1'] == request.form['pass2']:
            change_password(session['username'], request.form['pass1'])
            log_action(session['uid'], 8)
            session.pop('logged_in', None)
            session.pop('uid', None)
            session.pop('priv', None)
            session.pop('username', None)
            flash('Your password has been changed. Please login using your new password.')
            return redirect(url_for('home'))
        else:
            flash('The passwords you entered do not match. Please try again.')
            return render_template('changepass.html')
    return render_template('changepass.html')

#
# EDIT USER PAGE
#
项目:flask_ishuhui    作者:lufficc    | 项目源码 | 文件源码
def task_status(task_id):
    result = refresh_chapters_task.AsyncResult(task_id)
    if result.state == 'PENDING':
        response = {
            'state': result.state,
            'progress': 0,
        }
    elif result.state != 'FAILURE':
        response = {
            'state': result.state,
            'progress': result.info.get('progress', 0),
        }
        if result.state == 'SUCCESS':
            session.pop('task_id')
        if 'result' in result.info:
            response['result'] = result.info['result']
    else:
        # something went wrong in the background job
        session.pop('task_id')
        response = {
            'state': result.state,
            'progress': 0,
            'status': str(result.info),  # this is the exception raised
        }
    return jsonify(response)
项目:guides-cms    作者:pluralsight    | 项目源码 | 文件源码
def set_featured_title():
    """Form POST to update featured title"""

    title = request.form['title']
    stack = request.form['stack']

    article = models.search_for_article(title, stacks=[stack], status=PUBLISHED)
    if article is None:
        flash('Cannot find published guide "%s" stack "%s"' % (title, stack),
              category='error')

        url = session.pop('previously_requested_page', None)
        if url is None:
            url = url_for('index')

        return redirect(url)

    models.set_featured_article(article)
    flash('Featured guide updated', category='info')

    return redirect(url_for('index'))
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
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)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
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)
项目:graph-data-experiment    作者:occrp-attic    | 项目源码 | 文件源码
def callback():
    resp = oauth_provider.authorized_response()
    if resp is None or isinstance(resp, OAuthException):
        log.warning("Failed OAuth: %r", resp)
        return Unauthorized("Authentication has failed.")
    session['oauth'] = resp
    if 'googleapis.com' in oauth_provider.base_url:
        me = oauth_provider.get('userinfo')
        session['user'] = me.data.get('email')
    elif 'investigativedashboard.org' in oauth_provider.base_url:
        me = oauth_provider.get('api/2/accounts/profile/')
        session['user'] = me.data.get('email')
    else:
        return Unauthorized('Unknown OAuth provider: %r' %
                            oauth_provider.base_url)
    log.info("Logged in: %s", session['user'])
    return redirect(session.pop('next_url', '/'))
项目:ecodash    作者:Servir-Mekong    | 项目源码 | 文件源码
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)
项目:synergy_website    作者:alfredojf    | 项目源码 | 文件源码
def AIdentificar():
    #POST/PUT parameters
    params = request.get_json()
    results = [{'label':'/VPrincipal', "actor":"duenoProducto"}, {'label':'/VLogin', 'msg':['Datos de identificación incorrectos']}, ]
    res = results[1]
    #Action code goes here, res should be a list with a label and a message

    for nombre_usuario, clave in db.session.query(Usuario.nombre_usuario, Usuario.clave) :
        if nombre_usuario == params['usuario'] and clave == params['clave'] :
            res = results[0]
            session['nombre_usuario']=params['usuario']

            session['idPaginaSitio'] = " "
            res['idPaginaSitio'] = " "
            break

    #Action code ends here
    if "actor" in res:
        if res['actor'] is None:
            session.pop("actor", None)
        else:
            session['actor'] = res['actor']
    return json.dumps(res)
项目:synergy_website    作者:alfredojf    | 项目源码 | 文件源码
def ASalir():
    params = request.get_json()
    results = [{'msg':['Cerraste sesión satisfactoriamente.']}, 
    {'msg':['No se pudo cerrar sesión.']} ]
    res = results[1]
    #Action code goes here, res should be a list with a label and a message
    if 'nombre_usuario' in session and params['idUsuario'] == session['nombre_usuario']:
        session.pop('nombre_usuario')
        res = results[0]
    else:
        res = results[1]
    #Action code ends here
    if "actor" in res:
        if res['actor'] is None:
            session.pop("actor", None)
        else:
            session['actor'] = res['actor']
    return json.dumps(res)
项目:synergy_website    作者:alfredojf    | 项目源码 | 文件源码
def AgregMiembro():
    #POST/PUT parameters
    params = request.get_json()
    results = [{'label':'/VGrupo', 'msg':['Nuevo miembro agregado']}, {'label':'/VGrupo', 'msg':['No se pudo agregar al nuevo miembro']}, ]
    res = results[0]
    #Action code goes here, res should be a list with a label and a message

    nombreUsuario = params['nombre']
    usuario = Usuario.query.filter_by(nombre_usuario = nombreUsuario).first()
    id_grupo = session.get('idGrupo')
    res['label'] = res['label'] + '/' + id_grupo
    #Descomentar lo de abajo cuando se tenga la especificación de crear grupos.
    grupo = Grupo.query.filter_by(id = id_grupo).first()
    grupo.miembros.append(usuario)
    db.session.add(grupo)

    db.session.commit()

    #Action code ends here
    if "actor" in res:
        if res['actor'] is None:
            session.pop("actor", None)
        else:
            session['actor'] = res['actor']
    return json.dumps(res)
项目:SurfaceWaterTool    作者:Servir-Mekong    | 项目源码 | 文件源码
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)
项目:SDV-Summary    作者:Sketchy502    | 项目源码 | 文件源码
def login():
    page_init()
    session.permanent = True
    if logged_in():
        return redirect(url_for('home'))
    if request.method == 'POST':
        if 'email' not in request.form or 'password' not in request.form or request.form['email']=='':
            g.error = _('Missing email or password for login!')
        else:
            pw = check_user_pw(request.form['email'],request.form['password'])
            if pw['result'] == False:
                g.error = pw['error']
            elif pw['result'] == None:
                flash({'message':'<p>'+_('Please reset your password to log in!')+'</p>'})
                return redirect(url_for('reset_password'))
            else:
                flash({'message':'<p>'+_('Logged in successfully!')+'</p>'})
                redirect_url = session.get('login_redir')
                if redirect_url:
                    session.pop('login_redir')
                    return redirect(redirect_url)
                else:
                    return redirect(url_for('home'))
    return render_template("login.html",**page_args())
项目:SDV-Summary    作者:Sketchy502    | 项目源码 | 文件源码
def logged_in():
    # designed to prevent repeated db requests
    if not hasattr(g,'logged_in_user'):
        if 'logged_in_user' in session:
            db = get_db()
            cur = db.cursor()
            cur.execute('SELECT auth_key FROM users WHERE id='+app.sqlesc,(session['logged_in_user'][0],))
            result = cur.fetchall()
            if len(result) == 0:
                session.pop('logged_in_user',None)
                g.logged_in_user = False
            elif result[0][0] == session['logged_in_user'][1]:
                g.logged_in_user = True
            else:
                session.pop('logged_in_user',None)
                g.logged_in_user = False
        else:
            g.logged_in_user = False
    return g.logged_in_user
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
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)
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
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)
项目:alfredToday    作者:jeeftor    | 项目源码 | 文件源码
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)
项目:service-level-reporting    作者:zalando-zmon    | 项目源码 | 文件源码
def authorized():
    if not OAUTH2_ENABLED:
        token_info = {'access_token': PRESHARED_TOKEN or zign.api.get_token('uid', ['uid'])}
    else:
        resp = auth.authorized_response()
        if resp is None:
            return 'Access denied: reason={} error={}'.format(request.args['error'], request.args['error_description'])

        if not isinstance(resp, dict):
            return 'Invalid OAUTH response'

        token_info = resp

    set_token_info(token_info)
    flask_session['is_authenticated'] = True  # Session authenticated user
    flask_session['last_login'] = datetime.now().isoformat()

    next_uri = flask_session.pop('next_uri', '/')
    redirect_uri = get_safe_redirect_uri(next_uri, default='/')

    return redirect(redirect_uri)
项目:Webradio_v2    作者:Acer54    | 项目源码 | 文件源码
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)
项目:Awesome-Python    作者:JoMingyu    | 项目源码 | 文件源码
def session_test():
    if request.method == 'DELETE':
        session.pop('username')
        # ?? ??

        return 'Session deleted!'
    else:
        if 'username' in session:
            # ?? ?? ?? ??

            return 'Hello {0}'.format(session['username'])
        else:
            session['username'] = request.values['username']
            # ?? ??

            return 'Session appended!'
项目:pwnedhub    作者:lanmaster53    | 项目源码 | 文件源码
def reset_password():
    # enforce flow control
    if not session.get('reset_id'):
        flash('Reset improperly initialized.')
        return redirect(url_for('ph_bp.reset_init'))
    if request.method == 'POST':
        password = request.form['password']
        if password == request.form['confirm_password']:
            if is_valid_password(password):
                user = User.query.get(session.pop('reset_id'))
                user.password = password
                db.session.add(user)
                db.session.commit()
                flash('Password reset. Please log in.')
                return redirect(url_for('ph_bp.login'))
            else:
                flash('Invalid password.')
        else:
            flash('Passwords do not match.')
    return render_template('reset_password.html')
项目:micro-blog    作者:nickChenyx    | 项目源码 | 文件源码
def after_login(resp):
    if resp.email is None or resp.email == "":
        flash('Invalid login. Please try again.')
        return redirect(url_for('login'))
    user = User.query.filter_by(email=resp.email).first()
    if user is None:
        nickname = resp.nickname
        if nickname is None or nickname == "":
            nickname =resp.email.split('@')[0]
        user = User(nickname=nickname,email=resp.email)
        db.session.add(user)
        db.session.commit()
        # make the user follow him/herself
        db.session.add(user.follow(user))
        db.session.commit()
    remember_me = False
    if 'remember_me' in session:
        remember_me = session['remember_me']
        session.pop('remember_me',None)
    login_user(user,remember = remember_me)
    return redirect(request.args.get('next') or url_for('index'))
项目:vit_acad_web_api    作者:piyushrungta25    | 项目源码 | 文件源码
def valid_session():
    if 'logged_in' not in session or 'username' not in session or 'session_id' not in session or 'email' not in session:
        # session['messages'] =  "No active session"
        return False

    g.cur.execute("select session_id from login_data where email='%s'"%(session['email']))
    result=g.cur.fetchall()
    result=result[0][0]
    if session['session_id']==result:
        return True

    else:
        #pop all session entries
        session.pop('logged_in', None)
        session.pop('session_id', None)
        session.pop('username', None)
        session.pop('email', None)
        return False
        # return redirect(url_for('login'))
项目:website    作者:DiscordEmotes    | 项目源码 | 文件源码
def current(cls):
        """Returns the current User if applicable, None if not authenticated."""
        token = session.get('oauth2_token')
        if token is None:
            return None

        with make_session(token=token) as discord:
            data = cache.get_cached_user_data(token)
            if data is None:
                user = discord.get(DISCORD_API_URL + '/users/@me')
                if user.status_code == 401:
                    # our token is invalidated
                    session.pop('oauth2_token')
                    return None

                data = user.json()
                cache.set_cached_user_data(token, data)

            return cls(data) if data else None
项目:docklet    作者:unias    | 项目源码 | 文件源码
def get(self):
        resp = make_response(redirect('/login/'))
        session.pop('username', None)
        session.pop('nickname', None)
        session.pop('description', None)
        session.pop('avatar', None)
        session.pop('status', None)
        session.pop('usergroup', None)
        session.pop('token', None)
        resp.set_cookie('docklet-jupyter-cookie', '', expires=0)
        return resp
项目:docklet    作者:unias    | 项目源码 | 文件源码
def not_authorized(error):
    if "username" in session:
        if "401" in session:
            reason = session['401']
            session.pop('401', None)
            if (reason == 'Token Expired'):
                return redirect('/logout/')
        return render_template('error/401.html', mysession = session)
    else:
        return redirect('/login/')
项目:apiTest    作者:wuranxu    | 项目源码 | 文件源码
def logout():
    session.pop('user')
    return redirect(url_for("for_login"))
项目:dodscp    作者:seancallaway    | 项目源码 | 文件源码
def logout():
    log_action(session['uid'], 3)
    session.pop('logged_in', None)
    session.pop('uid', None)
    session.pop('priv', None)
    session.pop('username', None)
    flash('You were just logged out.')
    return redirect(url_for('home'))

#
# CHANGE PASSWORD PAGE
#
项目:aniping    作者:kuruoujou    | 项目源码 | 文件源码
def logout():
    """Logout handler.

    Ends the client session and deletes the session ID from the database.

    Returns:
        JSON formatted output describing success.
    """
    log.debug("Entering logout, attempting to end session.")
    fe.delete_login_id(escape(session['logged_in']))
    session.pop('logged_in', None)
    log.debug("Returning to user.")
    return jsonify({ "logout": "success" })
项目:CourseGrab    作者:nnsun    | 项目源码 | 文件源码
def sign_out():
    # remove the token from the session if it's there
    session.pop('access_token', None)
    return redirect(url_for('index'))
项目:github-catalog    作者:yogykwan    | 项目源码 | 文件源码
def logout():
    login_session.pop('user_id', None)
    login_session.pop('access_token', None)
    flash("Logged out!")
    return redirect(url_for('show_home'))
项目:NYCSL2    作者:HMProgrammingClub    | 项目源码 | 文件源码
def get(self):
        if "userID" not in session:
            return jsonify({"loggedIn": False})

        user = db.user.find_one({"_id": session["userID"]})
        if user is None:
            session.pop("userID")
            return jsonify({"loggedIn": False})
        return jsonify({ "loggedIn": True, "user": user })
项目:NYCSL2    作者:HMProgrammingClub    | 项目源码 | 文件源码
def delete(self):
        if "userID" not in session:
            abort(404)

        session.pop("userID")
        return jsonify({"result": True})
项目:NYCSL2    作者:HMProgrammingClub    | 项目源码 | 文件源码
def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("problemID", type=str, required=True, location="json")
        parser.add_argument("userID", type=str, required=True, location="json")
        parser.add_argument("file", type=FileStorage, required=True, location="files")
        entry = parser.parse_args()

        try:
            if db.problem.find_one({"_id": ObjectId(entry['problemID'])}) == None:
                abort(400)
            if db.user.find_one({"_id": entry['userID']}) == None:
                abort(400)
        except:
            abort(400)

        problemName =  db.problem.find_one({"_id": ObjectId(entry['problemID'])})['name']
        gradingFilePath = os.path.join(os.path.join(PROBLEMS_DIR, problemName.lower()), GRADING_SCRIPT)
        command = "python3 "+gradingFilePath+" \""+entry["file"].stream+"\""
        gradingOutput = subprocess.Popen(shlex.split(command.replace('\\','/')), stdout=subprocess.PIPE).communicate()[0]
        structuredGradingOutput = json.loads(gradingOutput)

        status_code = None
        if "score" in structuredGradingOutput:
            entry["score"] = structuredGradingOutput["score"]
            entry.pop("file")
            db.entry.insert_one(entry)
            status_code = 201
        else:
            status_code = 400

        return jsonify(structuredGradingOutput, status=status_code)
项目:love    作者:Yelp    | 项目源码 | 文件源码
def check_csrf_protection():
    """Make sure POST requests are sent with a CSRF token unless they're part of the API.
    In the future we might want to think about a system where we can disable CSRF protection
    on a per-view basis, maybe with a decorator.
    """
    if request.method == 'POST':
        token = session.pop('_csrf_token', None)
        if not token or token != request.form.get('_csrf_token'):
            abort(403)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def _get_flow_for_token(csrf_token):
    """Retrieves the flow instance associated with a given CSRF token from
    the Flask session."""
    flow_pickle = session.pop(
        _FLOW_KEY.format(csrf_token), None)

    if flow_pickle is None:
        return None
    else:
        return pickle.loads(flow_pickle)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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
项目:PythonStudyCode    作者:TongTongX    | 项目源码 | 文件源码
def logout():
    """Log out the user from the application.

    Log out the user from the application by removing them from the
    session.  Note: this does not log the user out of Facebook - this is done
    by the JavaScript SDK.
    """
    session.pop('user', None)
    return redirect(url_for('index'))
项目:eagle    作者:saga92    | 项目源码 | 文件源码
def sign_out():
    session.pop('is_login', None)
    session.pop('user_profile', None)
    return redirect('/')
项目:flask_ishuhui    作者:lufficc    | 项目源码 | 文件源码
def csrf_protect():
    if request.method == "POST":
        token = session.pop('_csrf_token', None)
        request_token = request.form.get('_csrf_token')
        if not token or token != request_token:
            abort(403)
项目:JmilkFan-s-Blog    作者:JmilkFan    | 项目源码 | 文件源码
def logout():
    """View function for logout."""

    # Remove the username from the cookie.
    # session.pop('username', None)

    # Using the Flask-Login to processing and check the logout status for user.
    logout_user()

    identity_changed.send(
        current_app._get_current_object(),
        identity=AnonymousIdentity())
    flash("You have been logged out.", category="success")
    return redirect(url_for('main.login'))
项目:hashtagtodo-open    作者:slackpad    | 项目源码 | 文件源码
def csrf_protect():
    if request.method == 'POST':
        token = session.pop('_csrf_token', None)
        if not token or token != request.form.get('_csrf_token'):
            abort(403)

    if '_csrf_token' not in session:
        session['_csrf_token'] = str(uuid.uuid4())
项目:hashtagtodo-open    作者:slackpad    | 项目源码 | 文件源码
def restrict_to_admin_users():
    g.user = None
    if 'user' in session:
        g.user = User.get_by_id(session['user'])

    if not g.user or not g.user.is_admin:
        session.pop('user', None)
        abort(403)
项目:hashtagtodo-open    作者:slackpad    | 项目源码 | 文件源码
def csrf_protect():
    if request.method == 'POST':
        token = session.pop('_csrf_token', None)
        if not token or token != request.form.get('_csrf_token'):
            abort(403)

    if '_csrf_token' not in session:
        session['_csrf_token'] = str(uuid.uuid4())