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

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.

Related

Flask - How can we check when more number of users log in at the same time?

#app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
# Login and validate the user.
# user should be an instance of your `User` class
login_user(user)
flask.flash('Logged in successfully.')
return flask.render_template('login.html', form=form)
The above is my attempt at this. How can one send multiple login requests at the same time? Additionally, how can one check how the webapp behaves
I'm not totally sure I understand your question, but your flask app will behave normally as expected when multiple users login simultaneously unless you are executing a huge script. Also, you have no need for the 'flask.' prefix which precedes flash and render_template.

Passing the destination URL through Flask and Flask-Login

Looking at the Flask-Login docs and several relatively old threads on Stackoverflow, I am concerned about the security of my solution for passing the restricted page URL through the login process.
First, I was getting Attribution Error when trying to use #login_manager.unauthorized_handler. ("login_manager does not have an attribute unauthorized_handler.") This a separate issue altogether, because it really should have worked. (See app factory below.)
When I applied a redirect_destination function without the modified #login_manager.unauthorized_handler, the login failed to redirect to the target destination.
def redirect_destination(dest_url, fallback):
try:
dest_url = url_for(dest_url)
except:
return redirect(fallback)
return redirect(dest_url)
Then I applied a session instance to be passed from the destination URL through login along with the fresh_login_required decorator and .is_authenticated property instead of the standard login_required.
target blueprint:
#target.route('/target', methods=['GET', 'POST'])
#fresh_login_required
def target():
if current_user.is_authenticated:
...
return render_template('target.html')
else:
session['dest_url']=request.endpoint
return redirect(url_for('account.login'))
auth blueprint:
#account.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('main.index'))
dest_url = session.get('dest_url')
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if not user:
return redirect(url_for('account.login'))
if user.check_password(form.password.data):
login_user(user, remember=form.remember_me.data)
...
return redirect_destination(dest_url, fallback=url_for('main.index'))
else:
return redirect(url_for('account.login'))
return render_template('account/login.html')
app factory:
...
login_manager = LoginManager()
login_manager.login_view = 'account.login' #hard-coded view
login_manager.refresh_view = 'account.refresh' #hard-coded view
def create_app():
app = Flask(__name__,
static_url_path='/',
static_folder='../app/static',
template_folder='../app/templates')
db.init_app(app)
login_manager.init_app(app)
from app import models
from .templates.account import account
from .templates.main import main
from .templates.target import target
app.register_blueprint(main)
app.register_blueprint(account)
app.register_blueprint(target)
return app
So, this solution works, and it can be applied to multiple blueprints. My concern is that I am missing some important details that necessitated other, more complex solutions. Is there a security weak point? Other issues?
References:
https://flask-login.readthedocs.io/en/latest/
How do I pass through the "next" URL with Flask and Flask-login?
Flask/Werkzeug, how to return previous page after login
Flask how to redirect to previous page after successful login
Get next URL using flask redirect
Flask Basic HTTP Auth use login page

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

Secure logins with flask

I am developing a flask app that requires user logins. There are two users currently, one is admin and the other is normal. At the moment, I am using sessions to store the username of the user in then I check to see which username they have and then allow or disallow them access to pages based on their username.
Here is my code:
from flask import Flask, session, redirect, render_template, request
app = Flask(__name__)
app.config["SECRET_KEY"] = <byte string generated by os.urandom(24)>
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(hours=1)
#app.route("/")
def login_redirect():
if check_login(session, False):
return redirect("/interface")
return redirect("/login")
#app.route("/login", methods=["POST", "GET"])
def login():
error = ""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
if check_password(username, password):
session["username"] = request.form["username"]
return redirect("/register")
error = "Invalid username or password"
return render_template("login.html", theme_colour=theme_colour, error=error)
def check_password(username, password):
ph = PasswordHasher()
db_hash, salt = database.retrieve_pw_salt(username) # returns hashed/salted password and salt from database
if db_hash is None:
return False # invalid username
try:
ph.verify(db_hash, salt + password)
return True # valid username and password
except exceptions.VerifyMismatchError:
return False # invalid password
def check_login(session, requires_elevated):
if "username" not in session:
return False
elif session["username"] == "admin":
return True
elif session["username"] == "normal" and not requires_elevated:
return True
return False
#app.before_request
def setup():
session.permanent = True # will now abide by 1 hour timeout setting
However, it has recently come to my attention that this may not be very secure. To be honest I'm not really so sure myself, so I was wondering if someone would be able to explain any vulnerabilities to me if there are any, and how I might go about improving the security.
Thanks.
Using session data to authorize permissions isn't considered secure because sessions can be hijacked by stealing session cookies, which would then give the attacker undue influence over a given users account. Since you are using Flask, I suggest you use Flask-Login to manage your sessions. This will give you access to differentiating between fresh and non-fresh logins so that sensitive information can't be accessed and manipulated by a simple session hijacking.
You might also consider implementing third-party authentication through Google, Facebook, LinkedIn or some other major provider so that you can partially outsource some of the heavy lifting associated with providing password and username storage. Two-factor authentication is another way you can improve security on your app, sending texts with unique codes for individuals to log in with or some other second factor. I've linked out to the docs for flask-login at the bottom.
Note: I'd give you code samples, but you've asked an extremely general question about how one might improve security from session-based authorization. I suggest you check out these docs, try to write a better solution for your app's security and then if you have any issues, post another, more specific question about errors in logic or syntax you receive. Good luck!
https://flask-login.readthedocs.io/en/latest/

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?

Categories

Resources