Customized debug/flask Flask python - 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())

Related

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

Login_redirect_url not working. View always redirecting to index

This is my login redirect url in settings.py:
LOGIN_REDIRECT_URL='/category/all'
And this is my login view:
def login(request):
if request.user.is_authenticated:
return redirect('/')
else:
if request.method == "POST":
email=request.POST['email']
password=request.POST['password']
user=auth.authenticate(email=email,password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
messages.info(request,"Email Password didn't match")
return redirect('login')
else:
return render(request,"login.html")
Whenever the user logs in I want to redirect him to the category/all page but it is always redirecting to index("/") and this might be because I am using return redirect("/").Also even when I have login required for some view then too even when the url is like:
http://localhost:8000/login/?next=/cart/
Instead of redirecting me to cart it redirects too index. Please help me to work around this so that the redirect works properly.
You constructed your own login view, hence that means that the mechanism to redirect will not work, since the LOGIN_REDIRECT_URL, etc. are parameters for the LoginView [Django-doc] of the Django auth module.
You can simply redirect in your view:
def login(request):
if request.user.is_authenticated:
return redirect('/category/all')
else:
if request.method == 'POST':
email=request.POST['email']
password=request.POST['password']
user=auth.authenticate(email=email,password=password)
if user is not None:
auth.login(request, user)
# redirect to a view
return redirect('/category/all')
else:
messages.info(request, "Email Password didn't match")
return redirect('login')
else:
return render(request,'login.html')
In the code, you are using return redirect('/') statement, which is redirecting you to home page.
To handle the redirections of urls like this - http://localhost:8000/login/?next=/cart/ you need to get value of next parameter from url, then write statement something like this. (Add this where you are using "return redirect('/')" statement)
next = request.GET.get('next')
if next:
return redirect(next)
else:
return redirect('/')
Sorry for not formatting properly,, I m posting from mobile

307 Redirect in OAUTH2 in Python using Flask

I'm trying to manipulate the following code to issue a 307 redirect, instead of the default 302.
Code:
#app.route('/', methods=('GET', 'POST'))
def home():
if request.method == 'POST':
username = request.form.get('username')
user = User.query.filter_by(username=username).first()
if not user:
user = User(username=username)
db.session.add(user)
db.session.commit()
session['id'] = user.id
return redirect('/',code = 307)
user = current_user()
return render_template('home.html', user=user)
The functionality of the above code is after a user enters the username, redirect to the home page.
Although it's issued properly (by inspecting the according message in terminal), I keep getting a "This page isn't redirecting properly" from the browser. The same code works perfectly for the simple redirect
return redirect('/')
What am I missing ?

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

Flask doubts regarding redirection

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'

Categories

Resources