HTTP基本认证的基本超时设置

1 投票
1 回答
2828 浏览
提问于 2025-04-18 11:32

我正在提供一个静态文件,查看这个文件需要基本的登录和密码。目前我只用了一段代码:http://flask.pocoo.org/snippets/8/

现在这个文件会一直保持活动状态,直到浏览器关闭。我想知道怎么写一个简单的超时功能。比如说“如果超过5分钟,就结束这个会话并把用户重定向回首页。”

我已经快搞定了,确实有超时功能,问题是如果浏览器窗口还开着,它会记住这个重定向。有没有什么建议来处理最后这个问题?用cookie?清除会话?还是其他什么方法?

谢谢

def check_auth(username, password):
  #This function is called to check if a username / password combination is valid.
  return username == 'oneshot' and password == 'private'

def authenticate():
  # Sends a 401 response that enables basic auth
  return Response(
  'Could not verify your access level for that URL.\n'
  'You have to login with proper credentials', 401,
  {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
  @wraps(f)
  def decorated(*args, **kwargs):

    start_time = session.get('session_time', None)

    if start_time is None:
      start_time = datetime.datetime.now()
      session['session_time'] = start_time

    elapsed = datetime.datetime.now() - start_time

    if datetime.timedelta(0, 60, 0) < elapsed:
      return redirect(url_for('index'))


    auth = request.authorization
    if not auth or not check_auth(auth.username, auth.password):
      return authenticate()

    return f(*args, **kwargs)

  return decorated

1 个回答

1

这是我最后做的事情:

def login_required(test):
  @wraps(test)
  def wrap(*args, **kwargs):
    if 'logged_in' in session:

      # session is always none
      start_time = session.get('session_time', None)


      #get the current time and set it as start time, this is also your session timer start
      if start_time is None:
        start_time = datetime.datetime.now()
        session['session_time'] = start_time

      # make an end time 1 minute from now
      end_time = start_time + datetime.timedelta(minutes=1)

      #find the current time in a for loop maybe? or just an if will probably work.
      if datetime.datetime.now() > end_time: 
        return redirect(url_for('expired', next=request.url))
        session.clear()
        start_time = session.get('session_time', None)

      return test(*args, **kwargs)
    else:

      return redirect(url_for('login', next=request.url))
  return wrap


@app.route('/login', methods=['GET', 'POST'])
def login():   
  error = None
  if request.method == 'POST':
    if request.form['username'] != app.config['USERNAME']:
      error = 'Invalid username'
    elif request.form['password'] != app.config['PASSWORD']:
      error = 'Invalid password'
    else:
      session['logged_in'] = True
      return redirect(url_for('media'))
  return render_template('login.html', error=error)

@app.route('/expired')
def expired():
  session.clear()
  return render_template('expired.html')

撰写回答