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

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?

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

render_template in Python-Flask is not working

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.

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.

Categories

Resources