簡體   English   中英

HTTP基本身份驗證的基本超時

[英]Basic timeout for HTTP Basic Auth

我正在提供一個靜態文件,要查看該文件需要基本的登錄名和密碼。 目前,我僅使用以下代碼段: http : //flask.pocoo.org/snippets/8/

現在,它只是保持活動狀態,直到瀏覽器退出為止。 我想弄清楚如何編寫一個簡單的超時。 如“如果已經5分鍾,請殺死它,然后將用戶重定向回索引頁面。

我已經很接近了,它超時了,唯一的事情是,如果瀏覽器窗口仍然打開,它會記住該重定向。 關於如何處理最后一部分的任何建議? 一塊餅干? 會議清理? 還有嗎

謝謝

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

這是我最終要做的事情:

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM