Home > front end >  Browser back button takes user back inside after Logout
Browser back button takes user back inside after Logout

Time:12-20

I have been working on a web interface using Flask and having some issues with back button in browser as after logging out hitting it takes user back inside. I have found similar questions and tried their answers but the issue is not resolved. I am attaching a simple example kindly have a look at it.

Main

from flask import Flask, request,session, redirect, url_for, render_template
from os import urandom

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.secret_key = urandom(24)

@app.route('/', methods=['POST', 'GET'])
def index():

  if request.method == 'POST':
      session['Email id'] = request.form.get('Email Id')
      Pass = request.form.get('Password')
      try:
          if session['Email id'] == '[email protected]' and Pass == 'KKK':
              return render_template('Logged_in.html')
      except:
          return render_template('login.html')   
  return render_template('login.html')

@app.route('/sign_out')
def sign_out():
  session.pop('Email id')
  return redirect(url_for('index'))

@app.after_request
def add_header(r):
  r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  r.headers["Pragma"] = "no-cache"    
  r.headers["Expires"] = "0"
  r.headers['Cache-Control'] = 'public, max-age=0'    
  return r

if __name__ == '__main__':
  app.run(host="0.0.0.0", debug=True, threaded=True)

login.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form action="{{ url_for('index') }}" method="POST" id="login" >
      <input type="text"  placeholder="Email Id" required name="Email Id">
      <input type="text"  placeholder="Password" required name="Password">  
      <button type="submit"  style="color: white;">Log in</button>
  </form>
</body>
</html>

Logged_in.html

<h2>You are Logged in</h2>
<a href="/sign_out"><i ></i>Log out</a>

CodePudding user response:

Your problem is that when users push the back button their browser will re-do the POST request. You need to use the POST/redirect/GET pattern to prevent this. For this you need four endpoints in totalt:

  1. GET / : Check in the session that the user is logged in and render Logged_in.html, otherwise redirect to /login.html
  2. GET /login.html : Render login.html
  3. POST /sign_in : Check username and password. If successful, update the session and redirect to /
  4. POST /sign_out : Log out the user session and redirect to /login.html

Do not render templates in your POST endpoints, just make them manipulate the session and then redirect.

  • Related