render_template in Python-Flask is not working - python

I am actually creating an app with Flask and I am encountering issues regarding my routing.
My situation is simple: The user enters a token to authenticate himself. Once he clicks on authenticate, an angular HTTP request uses POST to send his token to a Python server. There, if he is granted access, the home page is displayed using render_template; otherwise the login keeps still.
However, when the user authenticates himself, I see on my command line that the POST was successful, the authentication was a success but the page just stuck on login and does not redirect to home page as if the second render_template does not work. Please Help!
#app.route('/')
def index():
if not session.get('logged_in'):
return render_template('auth.html') # this is ok.
else:
return render_template('index.html') # this does not work
#app.route('/login', methods=['POST','GET'])
def login():
tok = request.form['token']
if (check_token(tok) == "pass"): # check_token is a function I've implemented
# to check if token is ok=pass, ko=fail
session['logged_in'] = True
else:
flash("wrong token")
return index()

Your login handler shouldn't call index directly. It should return a redirect to the index.
return redirect('/')
or better:
return redirect(url_for('index'))

I was thinking of the following.
#app.route('/')
def index():
if not session.get('logged_in'):
return return redirect(url_for('login'))
else:
return render_template('index.html')
#app.route('/login', methods=['POST','GET'])
def login():
if request.method = "POST":
tok = request.form['token']
if (check_token(tok) == "pass"):
session['logged_in'] = True
return redirect(url_for('index'))
else:
flash("wrong token")
return render_template("login.html")

I have used Angular JS in my app to send requests to my flask server and i realised that my client side angular JS had difficulties in rendering page as it was just expecting a response.
I first tried to do.. document.write('response.data') and it did display my home page but my scripts attached on my html page stopped working.
Second try, I tried to reload the page after receiving the response in my client and it works well. I don't know if it's the best way to do but it does work.

Related

Is there a way to protect logged in contents in Flask without using flask-login to manage users?

I am trying to set up a POC website in Flask\python to play around with some APIs. I have made a simple login page that redirects to /loggedin. But /loggedin is also accesible by just writing https://mysite/loggedin.html. Is there an easy way to prevent this that does not involve using something like flask-login? I don't want to spend time setting up an SQL user base and such, as I will be the only user of the application.
app = Flask(__name__)
#app.route("/")
def home():
return render_template("home.html")
#app.route("/loggedin")
def innsiden():
return render_template("loggedin.html")
#app.route("/login", methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'admin':
error = 'Invalid Credentials. Please try again.'
else:
return redirect(url_for('loggedin'))
return render_template('login.html', error=error)
In flask you can maintain on the server "session" information.
A simple method might be to
When user logs in with the correct password, add their username to the session data
When a logged in user visits a "secure" page, flask checks to see if their user id is in the sesson data if 'username' in session:. If it is, they are directed to the correct page, if not they are directed to a log in page
When the user logs out, their user name is removed from the list.
A version of this recipe is described at https://www.tutorialspoint.com/flask/flask_sessions.htm

Why is Flask's flash message failing to display

I'm trying to flash a message then redirect to the home page. But the flash message never appears after being redirected to home page. However app.logger.debug(get_flashed_messages()) does catch the flash message before redirection.
app.secret_key = 'somesecret'
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/add',methods=["GET","POST"])
def add():
if request.method == "POST":
url = request.form['url']
flash("Stored bookmark " + url) # Never displays
store_bookmarks(url)
app.logger.debug(get_flashed_messages()) # Catches flash message
return redirect(url_for('index')) # Always redirects
return render_template('add.html')
https://github.com/mitsuhiko/flask/issues/1168 This is the only thing i could find while searching but my APPLICATION_ROOT is unmodified

How do I only enable cookies if the user logs in?

I have a Flask app that runs on https behind nginx. The app also uses flask-login to log users in.
I have set my app.secret_key and have 3 views:
#app.route('/')
def index():
return render_template('index.html')
#app.route('/login', methods=['GET', 'POST'])
def login():
form = Login()
if form.validate_on_submit():
# log the user in...
......
return redirect(request.args.get('next') or '/')
return render_template('login.html', form=form)
#login_required
#app.route('/logged_in')
def logged_in():
return render_template('logged_in.html')
The vast, vast majority of my users do not log in (and don't have a user account) and some are complaining that we are setting cookies on them. I can confirm this behavior in my browser (Firefox) when I delete the cookie, visit "https://www.example.com" and see that the cookie gets reset.
How do I change the behavior so that the cookie only gets reset if the user logs in?

Python Flask - How to pass values from one route to another?

Hi I am new to flask and I am trying to create a simple login functionality. Users fill out their username and password (which at this point needs to match the username and password I hardcoded) and if their credentials are approved they are taken to their profile page. The profile page should show the message Hello followed by the username.
The validation is working just fine and the user is taken to the profile page but I can't pass the username from the form (login.html) to the template "profile.html".
Below follows the code. I am sending the code that works but there is no tentative to pass the username.
Thank you!
from flask import *
SECRET_KEY = "super secret"
app = Flask(__name__)
app.config.from_object(__name__)
#app.route('/')
def index():
return render_template('login.html')
#app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] == 'user' and request.form['password'] == 'pass':
session['loggedin'] = True
return redirect(url_for('profile'))
else:
error="Invalid credentials. Please try again."
return render_template('login.html', error=error)
#app.route('/profile')
def profile():
return render_template('profile.html')
#app.route('/logout')
def logout():
session.pop('loggedin', None)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
I think you miss the point of your hard work login page.
What about the next page the user will choose to visit? Will you send the username value again? of course not..
I suggest you to define a global var(session? DB data?) that contain the current-logged-in-user-data, so you can use all user's data, not only his username(age?posts? etc..)
One last thing, i use flask-login, i really like it, it simple mange my login session/views and guess what? there is current_user with the current-logged-in-user-data :)
Flask-login summery:
Flask-Login provides user session management for Flask.
It handles the common tasks of logging in, logging out, and remembering your users’ sessions over extended periods of time.
Why not make use of flask's many useful modules? They make flask an attractive microframework for speedy web development.
Flask-login, as stated above, streamlines authentication processes and manages sessions. Flask sessions also automatically stores session data for logged-in users. This allows you to implement a "Remember Me" feature in your login form.
Also, for security purposes, you would want to decorate some of your functions with #login_required, which is part of the flask-login module. This makes sure that the user is automatically redirected to the login page if he or she is not logged in already.
Here is an example of an index function that implements this:
from flask import render_template, session
from flask.ext.login import login_required
#app.route('/')
#login_required
def index():
return render_template("index.html")
You could also use flask.ext.openidto make authentication even more convenient.

Why does the login method of Flask use 'GET'?

I'm trying to learn more about Flask for a project, and I'm wondering if someone can explain to me why the sample code lists the methods 'GET' and 'POST', when it only ever tries to process a login if the request was 'POST'?
#app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
# Note that nowhere do we seem to care about 'GET'...
return render_template('login.html', error=error)
GET and POST methods are both handled by your function.
When GET is used, the login form (login.html) is returned for the user to log in. This is the last line of the function.
When POST is used, the form is validated using provided login/password. After that the user is either redirected to an other page (url for show_entries) or the login form is sent another time with the related error.
You should read 'When do you use POST and when do you use GET?' for more details on why POST is used to process the login form and why GET is used to send it.
return render_template('login.html', error=error) is the handler for GET.
Think about the logic:
if request.method == 'POST':
Check Credentials, Set error method
If no credential errors return the correct redirect
if there were errors in the POST section of code render_template gets those errors, otherwise it gets the None from the beginning of the method. I assume that if error is None in render_template it probably just renders a plain ol' login form.
Note: I've never used flask, but I understand python

Categories

Resources