Issue
i am programming by flask and i have a problem with flask_login login and authentication will complete when i enter username and password and i can get my user data in login page but after redirecting to other pages the user become anonymous! it seems that flask_login or UserMixin module does not work correctly. Please help me to solve this problem in my code
app = Flask(__name__)
app.secret_key = os.urandom(12)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@app.before_request
def before_request():
g.db = Models.DATABASE
g.db.connect()
g.user=current_user
@login_manager.user_loader
def load_user(useremail):
try:
return Models.User.select().where(
Models.User.email == str(useremail)
).get()
except Models.DoesNotExist:
return None
@app.after_request
def after_request(response):
g.db.close()
return response
@app.route('/login', methods=('GET','POST'))
def login():
form=forms.Signinform()
if form.validate_on_submit():
try:
user = Models.User.get(
Models.User.email == form.email.data
)
if (user.password==hashmypassword(form.password.data)):
login_user(user)
flash("You're now logged in!")
print(user.join_date)
return redirect(url_for('home'))
else:
flash("No user with that email/password combo")
print(hashmypassword(form.password.data))
print(form.password.data)
return redirect(url_for('register'))
except Models.DoesNotExist:
flash("No user with that email/password combo")
except:
print(user.password)
flash ("incorrect")
return render_template('login.html',form=form)
@app.route('/')
@app.route('/home')
def home():
if current_user.is_authenticated:
print(current_user.email)
else:
print("No AAA")
"""Renders the home page."""
return render_template(
'index.html',
title='Home Page',
year=datetime.datetime.now().year,
)
i am authenticated in login page but not authenticated in home page!
Solution
my problem solved using these functions in my Model class
def is_active(self):
"""True, as all users are active."""
return True
def get_id(self):
"""Return the email address to satisfy Flask-Login's requirements."""
return self.email
def is_authenticated(self):
"""Return True if the user is authenticated."""
return self.authenticated
def is_anonymous(self):
"""False, as anonymous users aren't supported."""
return False
i thought that def is_authenticated(self) is enough but all of these functions was necessary
Answered By - Amir Ahmadabadiha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.