2

I'm trying to update 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 to the login page.

I want to update it in @app.before_request and below is my code. How do I check for the login time and check if there has 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)
Patrick Yoder
  • 1,065
  • 4
  • 14
  • 19
kittu deopa
  • 79
  • 2
  • 2
  • 12
  • Could you use the cookie module? Perhaps each page load could check the stored cookie and, if it's still valid, set a new one with an expiration of 10 minutes. Otherwise, instead of continuing with the page load, it would log out and redirect to the login page. – coralvanda Sep 27 '16 at 08:30

2 Answers2

3

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.

Community
  • 1
  • 1
kfb
  • 6,252
  • 6
  • 40
  • 51
  • im trying the same setting app.permanent_session_lifetime = timedelta(minutes=2) , but its not happening. ? Not sure where I'm going wrong. Do I need to set permanent session time somewhere. And then use session.modified ? – kittu deopa Sep 27 '16 at 09:52
  • as suggested in this [link](http://stackoverflow.com/questions/11783025/is-there-an-easy-way-to-make-sessions-timeout-in-flask/11785722#11785722 ) Changed and added : @app.before_request def make_session_permanent(): session.permanent = True app.permanent_session_lifetime = timedelta(minutes=5) session.modified = True After adding I'm not able to login, it keeps redirecting to login page . – kittu deopa Sep 28 '16 at 07:24
1

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
Smit Mehta
  • 91
  • 9