2014-10-29 176 views
0

使用this即可使用本產品代碼。它的工作到現在好,但如果我想註銷。我想在我的html代碼上有一個按鈕,並且當我註銷以再次請求身份驗證時。 如何隱藏此代碼如何在登錄後註銷

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

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): 
     auth = request.authorization 
     if not auth or not check_auth(auth.username, auth.password): 
      return authenticate() 
     return f(*args, **kwargs) 
    return decorated 

@app.route("/") 
@requires_auth 
def index(): 
    return render_template("welcome.html", uptime=GetUptime()) 
#Logout function 
@app.route('/logout') 
def logout(): 
    #return redirect(url_for('index')) 
    flash('You were logged out') 
    return authenticate())) 

回答

0

您正在使用基本身份驗證。它沒有「註銷」的概念,但是,您可以通過發送錯誤的憑據(例如具有無效密碼的用戶名)來模擬,並返回401而不是200。如何實施它,取決於你。一種方法可能是指向「http://username:[email protected]」或ajax調用的錨點。

+0

創建一個端點(URL)嘿snahor!我使用註銷按鈕更新了第一篇文章。我能夠強制用戶使用此功能再次授權他自己。這樣做的問題是:彈出窗口在sceen上彈出詢問用戶和通過,但在後臺用戶仍然能夠點擊按鈕等。如何能夠首先將用戶重定向到索引頁是沒有按鈕的存在然後再詢問用戶並再次傳遞。我添加了行返回重定向(url_for('index')),但在重定向後它不強制用戶再次登錄。換句話說,return authenticate()被跳過。 – Bobys 2014-11-03 22:39:52

+0

你的'logout'函數以重定向結束,因此沒有401.'logout'只應該調用'authenticate',你既不需要flash也不需要重定向。如果您希望在註銷後重定向到索引,則必須使用JavaScript執行此操作,並在收到401狀態時重定向。 – snahor 2014-11-03 23:42:09

0

您可以使用auth數據創建會話(不管是否使用基本身份驗證),以及何時註銷只需刪除會話數據。

0

如果您使用nice燒瓶登錄擴展可以使用logout_user功能

from flask_login import login_user, logout_user 

然後,只需爲它

@expose('/logout/') 
def logout(self): 
    logout_user() 
    return redirect(url_for('index')