简体   繁体   中英

Flask logout if sessions expires if no activity and redirect for login page

I'm very new to flask and trying updating a website with flask where users have accounts and are able to login. I want to make user session expire and logout if there is no activity for more than 10 mins and redirect the user for login page.

I want to update it in @app.before_request and below is my code . How do i update it pls suggest. Check for the login time and check if there is been no activity then logout.

@app.before_request
def look_for_user(user=None):
        g.usr = {}
    g.api = False
    if user:
        g.usr = user
    if 'user_id' in session:
        g.usr = get_user((session['user_id'])) //from db
        if not g.usr:
            g.usr = {}
    if not g.usr:
        if request.url_rule:
            if request.url_rule.rule not in app.config['LOGIN_NOT_REQUIRED']:
                session['postlogin_landing_page'] = request.path
                if g.api:
                    return jsonify(error=True, error_message='Invalid Login/Token')
                else:
                    return redirect(app.config['LOGIN_URL'])
    elif 'login_page' in session and request.url_rule:
        if request.url_rule.rule not in app.config:
            landing_page = session.pop('login_page')
            return redirect(landing_page)

You can use permanent_session_lifetime and the session.modified flag as described in this question .

Note that sessions are not permanent by default, and need to be activated with session.permanent = True , as described in this answer .

solution of your problem and for that you have to import datetime.timedelta library

session.permanent = True
app.permanent_session_lifetime = timedelta(seconds=3)
session.modified = True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM