2014-10-29 179 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')