Flask doubts regarding redirection - python

I am following this tutorial here. The login page shows a sign in page. When I click on any of the providers, and click on the submit button, the page gets redirected back to the login page. What am I doing wrong here? I have the following code in the views.py page
#app.route('/login', methods=['GET', 'POST'])
#oid.loginhandler
def login():
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
session['remember_me'] = form.remember_me.data
return oid.try_login(form.openid.data, ask_for=['nickname', 'email'])
return render_template('login.html',
title='Sign In',
form=form,
providers=app.config['OPENID_PROVIDERS'])
#oid.after_login
def after_login(resp):
if resp.email is None or resp.email=="":
flash('Invalid login. Please try again')
return redirect(url_for('login'))
user=User.query.filter_by(email=resp.email).first()
if user is None:
nickname= resp.nickname
if nickname is None or nickname == "":
nickname=resp.email.split('#')[0]
user= User(nickname=nickname, email=resp.email)
db.session.add(user)
db.session.commit()
remember_me=False
if 'remember_me' in session:
remember_me=session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
return redirect(request.args.get('next') or url_for('index'))

you need to set the app config
app.config['SECURITY_POST_LOGIN_VIEW'] = '/post_login_page'
app.config['SECURITY_POST_REGISTER_VIEW'] = '/register_complete'

Related

Flask login_user does not work with firebase

I want to switch from SQLAlchemy to Firebase Authorisation. I have rewriten the authorisation part code to this:
firebase = pyrebase.initialize_app(firebaseConfig)
authorisation = firebase.auth()
auth = Blueprint("auth", __name__)
#auth.route("/sign-in", methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form.get("email")
password = request.form.get("password")
try:
user = authorisation.sign_in_with_email_and_password(email, password)
login_user(user, remember=True)
return redirect(url_for("views.profile"))
except:
flash("Invalid credentials! :(", category="error")
return render_template("sign-in.html", user=current_user)
the parts that authorisation is needed i use #login_required like so:
#views.route("/profile", methods=["GET", "POST"])
#login_required
def profile():
...
seems user = authorisation.sign_in_with_email_and_password(email, password) works but login_user(user, remember=True) does not.
As I googled for login_user user should be an object and seems it is not.
I can make it work this way, but is it there an option to make login_user work, becacause I do not want to re-write the code?

How to prevent a client to resubmit form data to a flask login route?

#app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
if login_check(form.email.data, form.password.data):
session["email"] = form.email.data
return redirect(url_for("login"))
flash("Wrong email or password")
if session.get("email"):
return redirect(url_for("index"))
return render_template("login.html", form=form)
If the user submits invalid information, then no redirect occurs and when the page is refreshed, the information is sent again. How can I prevent it using post/redirect/get?
I tried to add an additional condition to redirect the page if the user entered wrong information, but then return render_template("login.html", form=form) is never executed

Customized debug/flask Flask python

I have created an webapp.The home page consists of a login form and upon login it will redirect to "host_address/security_portal". And once I logout I tried accessing this security_portal page it says
could not build url for endpoint 'login'. Did you mean 'logout' instead
what I want is a customized error page instead of this debug page.
#app.route('/', methods=['GET', 'POST'])
def home():
form = LoginForm()
if form.validate_on_submit():
# Grab the user from our User Models table
user = User.query.filter_by(email=form.email.data.lower()).first()
if user==None:
flash('The E-mail is not registered! Kindly register and login')
return redirect(url_for('home'))
if user.check_password(form.password.data) and user is not None:
#Log in the user
login_user(user)
next = request.args.get('next')
#check if user trying to access page that needs login without signing in#
if next == None or not next[0]=='/':
next = url_for('security')
return redirect(next)
else:
flash("Incorrect Password!")
return render_template('home.html',form=form)
#app.route('/SecurityPage')
#login_required
def security():
return render_template('SecurityPage.html',username=(current_user.email.split('#'))[0].split('.')[0].capitalize())

Get next URL using flask redirect

I am following this information here, all seems good, but I need to know how to load the originally requested url from the new login page on the second to last line.
#app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if not models.check_auth(username, password):
error = 'Please try again.'
else:
return redirect(url_for(**next**))
return render_template('login.html', error=error)
Try this out:
#app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if not models.check_auth(username, password):
error = 'Please try again.'
else:
return redirect(request.args.get("next") or url_for("admin"))
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return render_template('login.html', error=error)

Passing data into flask template

During login form validation, I query for a user and store the object on the form instance. I want to pass the user object into the template. Following Python, Flask - Passing Arguments Into redirect(url_for()) , I tried:
def home():
form = LoginForm(request.form)
# Handle logging in
if request.method == 'POST':
if form.validate_on_submit():
login_user(form.user)
flash("You are logged in.", 'success')
redirect_url = request.args.get("next") or url_for("user.profile")
return redirect(redirect_url, userobj=form.user)
I'm redirecting to :
#blueprint.route("/profile")
#login_required
def profile():
return render_extensions("users/profile.html")
and again I want to pass the user object into profile.html template.
I'm getting:
TypeError: redirect() got an unexpected keyword argument 'userobj'
How can I fix this?
You may not be doing it correct. user which is logged in is available through current_user which is available in from flask.ext.login import current_user
this is how i did
#auth.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, form.remember_me.data)
return redirect(request.args.get('next') or url_for('main.index'))
flash('Invalid username or password')
return render_template('auth/login.html', form=form)
in the index view i am able to access it like current_user.username same in the template
try this it may help
peace

Categories

Resources