Login Algorithm
- Create login form – from data if available.
- After submitting valid data, get requested user from the database.
- If user does not exist, flash error message.
- Otherwise, check the password next.
- If user password matches user email, login user, flash success message, and redirect user to index view.
- If password is wrong, flash error message.
- Eventually, if login info are incorrect, render the login form showing the errors.
[forms.py]
...
class LoginForm(Form):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
Nothing out of the ordinary here.
[app.py]
from flask_bcrypt import check_password_hash
from flask_login import LoginManager, login_user, logout_user, login_required
...
@app.route('/register', methods=['POST', 'GET'])
def register():
...
@app.route('/login', methods=['GET', 'POST'])
def login():
form = forms.LoginForm()
if form.validate_on_submit():
try:
user = models.User.get(models.User.email == form.email.data)
except models.DoesNotExist:
flash("Your email does not match your password!", "error")
else:
if check_password_hash( user.password , form.password.data ):
login_user(user)
flash("You've been logged in successfully", "success")
return redirect(url_for('index'))
else:
flash("Your email does not match your password!", "error")
return render_template('login.html', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
flash("You've successfully logged out", "success")
return redirect(url_for('index'))
@app.route('/')
def index():
...
def load_user(userID)
This function works now; when users actually need to be loaded so they can login.
check_password_hash( user.password, form.password.data )
A bcrypt function that checks if hashed password matches the input password.
login_user(user)
As its name suggests, it is a function that logs a user in; by creating sessions on the user’s browser, and they’re giving them a cookie and the cookie references the user’s account.
logout_user( )
Deletes the cookie login_user( ) created. This way the browser no longer knows who they are.
@login_required
To log users out, first we need to check if they’re logged in. We do that by using the help of the @login_required decorator.
[login.html]
{% from 'macros.html' import render_field %}
<form method="POST" action="" class="form">
{{ form.hidden_tag() }}
{% for field in form %}
{{ render_field(field) }}
{% endfor %}
<button type="submit" id="submit">Login!</button>
</form>
Exactly same as the register.html template, except for the Submit button label. Also, nothing out of the ordinary.