The session doesn't keep value in flask? - python

When I login I can store on session but it seems after that session will be empty because I can't go to profile? I also tried from flask_session import Session , app.config.from_object(name) but it still have same issue? Also I send request from react.
from flask import Flask, request, jsonify, session
app.secret_key = "tutorialtutorial"
#app.route('/login',methods=['GET','POST'])
def login():
data = request.get_json()
user = User.query.filter_by(email=data.get("email")).one()
print(user)
if not user:
return "no user"
else:
if bcrypt.check_password_hash(user.password,data.get("password")):
# create sesion
session['user'] = user.firstname
print(session)
return "Authorized"
else:
return "UnAthorized"
# if user is not null
return "Hello login!"
#app.route('/profile',methods=['POST'])
def profile():
print(session)
print(len(session))
if "user" in session:
return "Hello Here is your profile"
else:
return "You are not defined" ```

Related

My flask app login does not work properly

I have a flask app that works great on laptops/desktops but on mobile phone and small screens the login route doesn't work properly.
When I want to login to my app on a mobile phone the login page redirects to itself and nothing happen. I think this problem is somehow related to session or login decorated function. Sometimes it works suddenly but it doesn't response often.
What can I do now?
Here is my app heads and login route:
from cs50 import SQL
from math import ceil
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.security import check_password_hash, generate_password_hash
from helpers import intro_alert, main_alert, login_required, usd, ex_separator, separator, \
cmc_logo, exchange_rates, cmc_quote, cmc_listing, cmc_info, exchanges, exchange_pairs, cmc_projects
coinjito = Flask(__name__)
coinjito.config["TEMPLATES_AUTO_RELOAD"] = True
#coinjito.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
coinjito.config["SESSION_FILE_DIR"] = mkdtemp()
coinjito.config["SESSION_PERMANENT"] = False
coinjito.config["SESSION_TYPE"] = "filesystem"
Session(coinjito)
#coinjito.route("/login", methods=["GET", "POST"])
def login():
session.clear()
if request.method == "GET":
return render_template("login.html")
else:
rows = db.execute("SELECT * FROM users WHERE username=:username",
username=request.form.get("username"))
if len(rows) != 1 or not check_password_hash(rows[0]["password"],
request.form.get("password")):
return intro_alert("Apology", "alert-danger", "Login Failed",
"Invalid username and/or password.", "/login", "Go Back")
session["user_id"] = rows[0]["id"]
session["username"] = rows[0]["username"]
return redirect("/tracking")
#coinjito.route("/tracking")
#login_required
And here is my login helper function:
def login_required(f):
#wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function

NameError: name 'logged' is not defined, Flask Python

I have a Python code with using framework Flask, that check if admin logged (logged = True) to render admin page, if admin is not logged (logged = False), redirecting to login page.
#app.route('/admin_login', methods=['POST', 'GET'])
def admin_login():
if request.method == 'POST':
login = request.form['login']
passsword = request.form['password']
if (login == 'admin') and (passsword == 'admin_pass'):
logged = True
return redirect('/admin_page'), logged
else:
return "Wrond login and passsword!"
else:
return render_template('admin_login.html')
#app.route('/admin_page')
def admin_page():
if logged == True:
return render_template('admin_page.html')
else:
return redirect('/admin_login')
But I get an error in if logged == True: - NameError: name 'logged' is not defined. I tried to make logged global but it didn't helped. So how can I make logged defined and use it in function admin_page?
You should avoid having a global logged_in variable on the server. Then anybody will be allowed to use your website after a successful login! You should use a session variable instead.
Session data is stored on top of cookies and encrypted. For this encryption, a Flask application needs a defined SECRET_KEY. A Session object is also a dictionary object containing key-value pairs.
Add this near the top of your main script if you haven't already got it:
from flask import Flask, session, redirect, url_for, escape, request, flash
app = Flask(__name__)
app.secret_key = 'any random string’
Then change your function admin_login() to set the session variable:
#app.route('/admin_login', methods=['POST', 'GET'])
def admin_login():
if request.method == 'POST':
login = request.form['login']
passsword = request.form['password']
if not 'logged_in' in session:
if (login == 'admin') and (passsword == 'admin_pass'):
session['logged_in'] = True
return redirect(url_for("admin_page"))
else:
flash("Wrong login and passsword!")
return render_template('admin_login.html')
else:
return redirect(url_for("admin_page"))
else:
if "logged_in" in session:
return redirect(url_for("admin_page"))
return render_template("admin_login.html")
Then change your admin_page() function to check this session variable:
#app.route('/admin_page')
def admin_page():
if 'logged_in' in session:
return render_template('admin_page.html')
else:
return redirect(url_for('admin_login'))
You would also need a logout end point to pop out the session variable:
#app.route('/logout')
def logout():
session.pop('logged_in', None)
return redirect(url_for('index'))

load_user function gets None as a parameter

I'm building a very simple Flask application, when I implemented load_user from flask-login, I started having errors because the function was getting None passed to it and was trying to query using a None value.
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
#login_manager.user_loader
def load_user(id):
return User.query.get(id)
Possibly relevant files:
auth/__init__.py:
from flask import Blueprint
auth = Blueprint('auth', __name__, url_prefix='/auth')
from . import views
auth/views.py:
from flask import render_template, redirect, url_for, flash, session
from flask_login import login_user
from app.forms import LoginForm
from app.models import User
from app.queries import get_user
from . import auth
#auth.route('/login', methods=['GET', 'POST'])
def login():
login_form = LoginForm()
context = {
'login_form' : login_form
}
username = login_form.username.data
password = login_form.password.data
if login_form.validate_on_submit():
user_query = get_user(username)
if user_query:
db_password = user_query.password
if password == db_password:
registeredUser = User(username = username,
password = password)
login_user(registeredUser)
flash('Bienvenido de nuevo!', 'alert alert-success alert-dismissible')
return redirect(url_for('hello'))
else:
flash('La información no coincide', 'alert alert-danger')
else:
flash('El usuario no existe.', 'alert alert-danger')
return redirect(url_for('index'))
return render_template('login.html', **context)
I'm not using the username as the primary key, I have a separate id column for that.
Assuming, from context, that user_query = get_user(username) is actually a User object and not a query, making a new User and passing it to login_user before persisting it mean that its id will be be None.
The easy fix would be to replace
if password == db_password:
registeredUser = User(username = username,
password = password)
login_user(registeredUser)
with
if password == user_query.password:
login_user(user_query)
and then to consider renaming user_query to user so that the code is clearer.
Also, give some thought to not storing user password in the clear. The Flask Mega Tutorial has a chapter that'll walk you through a way to store passwords encrypted.

How to know whether user is logged in or not in Pyrebase and Flask?

app = Flask(__name__)
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
db = firebase.database()
#app.route('/login', methods=["POST", "GET"])
def login():
message = ""
if request.method == "POST":
email = request.form["login_email"]
password = request.form["login_password"]
try:
user = auth.sign_in_with_email_and_password(email, password)
user = auth.refresh(user['refreshToken'])
user_id = user['idToken']
return redirect(url_for('admin'))
except:
message = "Incorrect Password!"
return render_template("login.html", message=message)
#app.route('/admin')
def admin():
return render_template("admin.html")
if __name__ == '__main__':
app.run()
How can I only load /admin page when the user is logged in? I know it has something to do with the user token, but I'm still not sure about how I could use the token to identify whether the user is logged in or not. Also, the user and user_id are not defined in admin()and only in login() since they're in a function.
So what do I need to change in my code in order to only load the /admin page when the user is logged in?
use flask session to store your key,if key exist then user is logged,
also you can access all session variables globally for individual session
from flask import Flask, session, request
import requests
import os
app = Flask(__name__)
app.secret_key = os.urandom(24)
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
db = firebase.database()
#app.route('/login', methods=["POST", "GET"])
def login():
message = ""
try:
print(session['usr'])
return redirect(url_for('admin'))
except KeyError:
if request.method == "POST":
email = request.form["login_email"]
password = request.form["login_password"]
try:
user = auth.sign_in_with_email_and_password(email, password)
user = auth.refresh(user['refreshToken'])
user_id = user['idToken']
session['usr'] = user_id
return redirect(url_for('admin'))
except:
message = "Incorrect Password!"
return render_template("login.html", message=message)
#app.route('/admin')
def admin():
try:
print(session['usr'])
return render_template("admin.html")
except KeyError:
return redirect(url_for('login'))
if __name__ == '__main__':
app.run()
if session['usr'] is not assigned then it will give key error which means that usr in not logged in. but note that in the process of logout you need to delete the session for that usr.

TypeError: __call__() got an unexpected keyword argument 'mimetype' [duplicate]

I have built a website using flask (www.csppdb.com). Sometimes when I log in as one user, log out, then login as another user I still see pages from the first user I logged in as. This problem is immediately fixed when the page is refreshed. I think this is called "caching" if I am not mistaken. Is there any way I could disable this on a site wide level so that every page that is visited needs a new refresh?
It would be like sharing your computer with a friend. He logs into Facebook, then logs out. Now you log in on his computer and you see his profile... (awkward). After you refresh the page the problem is fixed.
Here is some of my code. I was using flask-login but I then tried to "roll my own"
from flask.ext.mysql import MySQL
import os
from flask import Flask, request, jsonify, session, url_for, redirect, \
render_template, g, flash
from data import *
from werkzeug import check_password_hash, generate_password_hash
import config
app = Flask(__name__)
mysql = MySQL()
app.config['MYSQL_DATABASE_HOST'] = os.environ['MYSQL_DATABASE_HOST'] if 'MYSQL_DATABASE_HOST' in os.environ else config.MYSQL_DATABASE_HOST
app.config['MYSQL_DATABASE_PORT'] = os.environ['MYSQL_DATABASE_PORT'] if 'MYSQL_DATABASE_PORT' in os.environ else config.MYSQL_DATABASE_PORT
app.config['MYSQL_DATABASE_USER'] = os.environ['MYSQL_DATABASE_USER'] if 'MYSQL_DATABASE_USER' in os.environ else config.MYSQL_DATABASE_USER
app.config['MYSQL_DATABASE_PASSWORD'] = os.environ['MYSQL_DATABASE_PASSWORD'] if 'MYSQL_DATABASE_PASSWORD' in os.environ else config.MYSQL_DATABASE_PASSWORD
app.config['MYSQL_DATABASE_DB'] = os.environ['MYSQL_DATABASE_DB'] if 'MYSQL_DATABASE_DB' in os.environ else config.MYSQL_DATABASE_DB
mysql.init_app(app)
if 'SECRET_KEY' in os.environ: app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
else: app.config['SECRET_KEY'] = os.urandom(24)
def connect_db(): return mysql.connect()
def check_auth():
g.user = None
if 'username' in session:
g.user = get_user(session['username'])
return
return redirect(url_for('login'))
#app.route('/')
def home():
if 'username' in session: return redirect(url_for('main'))
return render_template('home.html')
def connect_db(): return mysql.connect()
#app.teardown_request
def teardown_request(exception):
if exception: print exception
g.db.close()
#app.before_request
def before_request():
print session.keys(), session.values()
print("before request")
print ('username' in session, "in session?")
g.db = connect_db()
g.user = None
if "username" in session:
g.user = get_user(session['username'])
#app.route('/login/', methods=['GET', 'POST'])
def login():
"""Logs the user in."""
if 'username' in session:
return redirect(url_for('main'))
error = None
if request.method == 'POST':
print("login hit")
user = get_user(request.form['username'])
if user is None:
error = 'Invalid username'
print error
elif not check_password_hash(user.password, request.form['password']):
error = 'Invalid password'
print error
else:
flash('You were logged in')
print "logged in"
session['username'] = request.form['username']
g.user = request.form['username']
print error, "error"
return redirect(url_for('main'))
return render_template('login.html', error=error)
Setting the cache to be max-age=0 fixed it.
#app.after_request
def add_header(response):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=0'
return response
To stop browser caching on these sort of pages you need to set some HTTP response headers.
Cache-Control: no-cache, no-store
Pragma: no-cache
Once you do this then the browser wont cache those pages. I dont know how to do this with "flask" so I will leave that as an exercise for you :)
This question shows how to add a response header Flask/Werkzeug how to attach HTTP content-length header to file download

Categories

Resources