Setup:
- Flask web app.
- User navigates to one of multiple pages [e.g.
game
page (localhost:5000/game
) orplayers
page (localhost:5000/players
)] through a post request withGAME_ID
in the form.GAME_ID
is used to fetch additional details and render the page.
Objective:
- When an unauthenticated users makes a post request to
/game
, redirect them to the/login
page but retain the endpoint (game
) and theGAME_ID
in the session, so that on successful login, I can send them back to the page they were accessing. My approach was to make a 307 redirect.
Approach (based on this and this):
In application.py
@login_manager.unauthorized_handler
def intercept_unauthorized():
<Set NEXT_PAGE_FOR_REDIRECT and GAME_ID_FOR_REDIRECT into the session>
return redirect(url_for('login'))
@application.route("/login", methods=['GET', 'POST'])
def login():
#User sees the login page
if request.method=='GET':
<show the login page>
#User has submitted username and password on the login page
elif request.method=='POST':
<authentication code here>
if validUser:
#Get the page the user was trying to access e.g. 'game'
nextPage = session.get('NEXT_PAGE_FOR_REDIRECT')
session.pop('NEXT_PAGE_FOR_REDIRECT')
gameID = session.get('GAME_ID_FOR_REDIRECT')
session.pop('GAME_ID_FOR_REDIRECT')
return redirect(url_for(next_page, gameID=gameID), code=307)
@application.route("/game", methods=['POST'])
@login_required
def game():
if 'gameID' in request.form:
render_template('game.html', gameID=request.form['gameID'])
Issue:
- I am able to redirect to
/game
whererequest.method
is POST. But, the data inrequest.form
is the data submitted from thelogin
page submit i.e. username and password. - I am able to access the
gameID
I set in theurl_for
line, but it is sent inrequest.args
(and is visible in the browser's address bar) instead of throughrequest.form
.
Questions:
- Is my approach of using a redirect correct?
- How can I modify the form being sent to
/game
so that I can addgameID
to it?