Hi everyone,
I am facing a hard time since I could not figure out how to redirect to the previous URL. When I tested request.referrer 10 days ago, it worked, but now it's not working anymore and instead, I am getting the same URL. I am creating a Google login. Here's the code:
@main.route("/post/<int:post_id>", methods=["GET", "POST"])
def post(post_id):
post = Posts.query.filter_by(id=post_id).one()
comments = post.comments
if post == None:
return ('Error')
elif current_user.is_authenticated:
return render_template("show_post0.html", post=post, comments=comments, username=current_user.user_name, userimage=current_user.user_photo)
return render_template("show_post_login.html", post=post, comments=comments)
def redirect_url(default='main.post'):
return request.args.get('next') or \
request.referrer or \
url_for(default)
@main.route("/login/callback")
def callback():
code = request.args.get("code")
google_provider_cfg = get_google_provider_cfg()
token_endpoint = google_provider_cfg["token_endpoint"]
token_url, headers, body = client.prepare_token_request(
token_endpoint,
authorization_response=request.url,
redirect_url=request.base_url,
code=code,
)
token_response = requests.post(
token_url,
headers=headers,
data=body,
auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
)
client.parse_request_body_response(json.dumps(token_response.json()))
userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
uri, headers, body = client.add_token(userinfo_endpoint)
userinfo_response = requests.get(uri, headers=headers, data=body)
if userinfo_response.json().get("email_verified"):
unique_id = userinfo_response.json()["sub"]
users_email = userinfo_response.json()["email"]
picture = userinfo_response.json()["picture"]
users_name = userinfo_response.json()["given_name"]
else:
return "User email not available or not verified by Google.", 400
author = Author(
google_id=unique_id, user_name=users_name, user_email=users_email, user_photo=picture
)
user = Author.query.filter_by(google_id=unique_id).first()
if user:
login_user(user)
else:
db.session.add(author)
db.session.commit()
login_user(author)
print("##############", request.args.get('next'))
print ("#########", request.referrer)
not the previous page.
return redirect(redirect_url())
I could redirect to the Post route directly but I want to use this method in more than one route.
Thanks in advance!
What I have tried:
I tried all the possible ways on the internet. though, when the login success, it refreshes the same URL instead of returning to the previous URL. I will be thankful if anyone can find a solution. Maybe I missed something. maybe it's a silly bug