The Flask Mega-Tutorial Part V: User Logins

Posted by
on under

This is the fifth installment of the Flask Mega-Tutorial series, in which I'm going to tell you how to create a user login subsystem.

For your reference, below is a list of the articles in this series.

In Chapter 3 you learned how to create the user login form, and in Chapter 4 you learned how to work with a database. This chapter will teach you how to combine the topics from those two chapters to create a simple user login system.

The GitHub links for this chapter are: Browse, Zip, Diff.

Password Hashing

In Chapter 4 the user model was given a password_hash field, that so far is unused. The purpose of this field is to hold a hash of the user password, which will be used to verify the password entered by the user during the log in process. Password hashing is a complicated topic that should be left to security experts, but there are several easy to use libraries that implement all that logic in a way that is simple to be invoked from an application.

One of the packages that implement password hashing is Werkzeug, which you may have seen referenced in the output of pip when you install Flask, since it is one of its core dependencies. Since it is a dependency, Werkzeug is already installed in your virtual environment. The following Python shell session demonstrates how to hash a password:

>>> from werkzeug.security import generate_password_hash
>>> hash = generate_password_hash('foobar')
>>> hash
'pbkdf2:sha256:50000$vT9fkZM8$04dfa35c6476acf7e788a1b5b3c35e217c78dc04539d295f011f01f18cd2'

In this example, the password foobar is transformed into a long encoded string through a series of cryptographic operations that have no known reverse operation, which means that a person that obtains the hashed password will be unable to use it to obtain the original password. As an additional measure, if you hash the same password multiple times, you will get different results, so this makes it impossible to identify if two users have the same password by looking at their hashes.

The verification process is done with a second function from Werkzeug, as follows:

>>> from werkzeug.security import check_password_hash
>>> check_password_hash(hash, 'foobar')
True
>>> check_password_hash(hash, 'barfoo')
False

The verification function takes a password hash that was previously generated, and a password entered by the user at the time of log in. The function returns True if the password provided by the user matches the hash, or False otherwise.

The whole password hashing logic can be implemented as two new methods in the user model:

app/models.py: Password hashing and verification

from werkzeug.security import generate_password_hash, check_password_hash

# ...

class User(db.Model):
    # ...

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

With these two methods in place, a user object is now able to do secure password verification, without the need to ever store original passwords. Here is an example usage of these new methods:

>>> u = User(username='susan', email='susan@example.com')
>>> u.set_password('mypassword')
>>> u.check_password('anotherpassword')
False
>>> u.check_password('mypassword')
True

Introduction to Flask-Login

In this chapter I'm going to introduce you to a very popular Flask extension called Flask-Login. This extension manages the user logged-in state, so that for example users can log in to the application and then navigate to different pages while the application "remembers" that the user is logged in. It also provides the "remember me" functionality that allows users to remain logged in even after closing the browser window. To be ready for this chapter, you can start by installing Flask-Login in your virtual environment:

(venv) $ pip install flask-login

As with other extensions, Flask-Login needs to be created and initialized right after the application instance in app/__init__.py. This is how this extension is initialized:

app/__init__.py: Flask-Login initialization

# ...
from flask_login import LoginManager

app = Flask(__name__)
# ...
login = LoginManager(app)

# ...

Preparing The User Model for Flask-Login

The Flask-Login extension works with the application's user model, and expects certain properties and methods to be implemented in it. This approach is nice, because as long as these required items are added to the model, Flask-Login does not have any other requirements, so for example, it can work with user models that are based on any database system.

The four required items are listed below:

  • is_authenticated: a property that is True if the user has valid credentials or False otherwise.
  • is_active: a property that is True if the user's account is active or False otherwise.
  • is_anonymous: a property that is False for regular users, and True for a special, anonymous user.
  • get_id(): a method that returns a unique identifier for the user as a string (unicode, if using Python 2).

I can implement these four easily, but since the implementations are fairly generic, Flask-Login provides a mixin class called UserMixin that includes generic implementations that are appropriate for most user model classes. Here is how the mixin class is added to the model:

app/models.py: Flask-Login user mixin class

# ...
from flask_login import UserMixin

class User(UserMixin, db.Model):
    # ...

User Loader Function

Flask-Login keeps track of the logged in user by storing its unique identifier in Flask's user session, a storage space assigned to each user who connects to the application. Each time the logged-in user navigates to a new page, Flask-Login retrieves the ID of the user from the session, and then loads that user into memory.

Because Flask-Login knows nothing about databases, it needs the application's help in loading a user. For that reason, the extension expects that the application will configure a user loader function, that can be called to load a user given the ID. This function can be added in the app/models.py module:

app/models.py: Flask-Login user loader function

from app import login
# ...

@login.user_loader
def load_user(id):
    return User.query.get(int(id))

The user loader is registered with Flask-Login with the @login.user_loader decorator. The id that Flask-Login passes to the function as an argument is going to be a string, so databases that use numeric IDs need to convert the string to integer as you see above.

Logging Users In

Let's revisit the login view function, which as you recall, implemented a fake login that just issued a flash() message. Now that the application has access to a user database and knows how to generate and verify password hashes, this view function can be completed.

app/routes.py: Login view function logic

# ...
from flask_login import current_user, login_user
from app.models import User

# ...

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)

The top two lines in the login() function deal with a weird situation. Imagine you have a user that is logged in, and the user navigates to the /login URL of your application. Clearly that is a mistake, so I want to not allow that. The current_user variable comes from Flask-Login and can be used at any time during the handling to obtain the user object that represents the client of the request. The value of this variable can be a user object from the database (which Flask-Login reads through the user loader callback I provided above), or a special anonymous user object if the user did not log in yet. Remember those properties that Flask-Login required in the user object? One of those was is_authenticated, which comes in handy to check if the user is logged in or not. When the user is already logged in, I just redirect to the index page.

In place of the flash() call that I used earlier, now I can log the user in for real. The first step is to load the user from the database. The username came with the form submission, so I can query the database with that to find the user. For this purpose I'm using the filter_by() method of the SQLAlchemy query object. The result of filter_by() is a query that only includes the objects that have a matching username. Since I know there is only going to be one or zero results, I complete the query by calling first(), which will return the user object if it exists, or None if it does not. In Chapter 4 you have seen that when you call the all() method in a query, the query executes and you get a list of all the results that match that query. The first() method is another commonly used way to execute a query, when you only need to have one result.

If I got a match for the username that was provided, I can next check if the password that also came with the form is valid. This is done by invoking the check_password() method I defined above. This will take the password hash stored with the user and determine if the password entered in the form matches the hash or not. So now I have two possible error conditions: the username can be invalid, or the password can be incorrect for the user. In either of those cases, I flash an message, and redirect back to the login prompt so that the user can try again.

If the username and password are both correct, then I call the login_user() function, which comes from Flask-Login. This function will register the user as logged in, so that means that any future pages the user navigates to will have the current_user variable set to that user.

To complete the login process, I just redirect the newly logged-in user to the index page.

Logging Users Out

I know I will also need to offer users the option to log out of the application. This can be done with Flask-Login's logout_user() function. Here is the logout view function:

app/routes.py: Logout view function

# ...
from flask_login import logout_user

# ...

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

To expose this link to users, I can make the Login link in the navigation bar automatically switch to a Logout link after the user logs in. This can be done with a conditional in the base.html template:

app/templates/base.html: Conditional login and logout links

    <div>
        Microblog:
        <a href="{{ url_for('index') }}">Home</a>
        {% if current_user.is_anonymous %}
        <a href="{{ url_for('login') }}">Login</a>
        {% else %}
        <a href="{{ url_for('logout') }}">Logout</a>
        {% endif %}
    </div>

The is_anonymous property is one of the attributes that Flask-Login adds to user objects through the UserMixin class. The current_user.is_anonymous expression is going to be True only when the user is not logged in.

Requiring Users To Login

Flask-Login provides a very useful feature that forces users to log in before they can view certain pages of the application. If a user who is not logged in tries to view a protected page, Flask-Login will automatically redirect the user to the login form, and only redirect back to the page the user wanted to view after the login process is complete.

For this feature to be implemented, Flask-Login needs to know what is the view function that handles logins. This can be added in app/__init__.py:

# ...
login = LoginManager(app)
login.login_view = 'login'

The 'login' value above is the function (or endpoint) name for the login view. In other words, the name you would use in a url_for() call to get the URL.

The way Flask-Login protects a view function against anonymous users is with a decorator called @login_required. When you add this decorator to a view function below the @app.route decorators from Flask, the function becomes protected and will not allow access to users that are not authenticated. Here is how the decorator can be applied to the index view function of the application:

app/routes.py: @login\_required decorator

from flask_login import login_required

@app.route('/')
@app.route('/index')
@login_required
def index():
    # ...

What remains is to implement the redirect back from the successful login to the page the user wanted to access. When a user that is not logged in accesses a view function protected with the @login_required decorator, the decorator is going to redirect to the login page, but it is going to include some extra information in this redirect so that the application can then return to the first page. If the user navigates to /index, for example, the @login_required decorator will intercept the request and respond with a redirect to /login, but it will add a query string argument to this URL, making the complete redirect URL /login?next=/index. The next query string argument is set to the original URL, so the application can use that to redirect back after login.

Here is a snippet of code that shows how to read and process the next query string argument:

app/routes.py: Redirect to "next" page

from flask import request
from werkzeug.urls import url_parse

@app.route('/login', methods=['GET', 'POST'])
def login():
    # ...
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    # ...

Right after the user is logged in by calling Flask-Login's login_user() function, the value of the next query string argument is obtained. Flask provides a request variable that contains all the information that the client sent with the request. In particular, the request.args attribute exposes the contents of the query string in a friendly dictionary format. There are actually three possible cases that need to be considered to determine where to redirect after a successful login:

  • If the login URL does not have a next argument, then the user is redirected to the index page.
  • If the login URL includes a next argument that is set to a relative path (or in other words, a URL without the domain portion), then the user is redirected to that URL.
  • If the login URL includes a next argument that is set to a full URL that includes a domain name, then the user is redirected to the index page.

The first and second cases are self-explanatory. The third case is in place to make the application more secure. An attacker could insert a URL to a malicious site in the next argument, so the application only redirects when the URL is relative, which ensures that the redirect stays within the same site as the application. To determine if the URL is relative or absolute, I parse it with Werkzeug's url_parse() function and then check if the netloc component is set or not.

Showing The Logged In User in Templates

Do you recall that way back in Chapter 2 I created a fake user to help me design the home page of the application before the user subsystem was in place? Well, the application has real users now, so I can now remove the fake user and start working with real users. Instead of the fake user I can use Flask-Login's current_user in the template:

app/templates/index.html: Pass current user to template

{% extends "base.html" %}

{% block content %}
    <h1>Hi, {{ current_user.username }}!</h1>
    {% for post in posts %}
    <div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
    {% endfor %}
{% endblock %}

And I can remove the user template argument in the view function:

app/routes.py: Do not pass user to template anymore

@app.route('/')
@app.route('/index')
@login_required
def index():
    # ...
    return render_template("index.html", title='Home Page', posts=posts)

This is a good time to test how the login and logout functionality works. Since there is still no user registration, the only way to add a user to the database is to do it via the Python shell, so run flask shell and enter the following commands to register a user:

>>> u = User(username='susan', email='susan@example.com')
>>> u.set_password('cat')
>>> db.session.add(u)
>>> db.session.commit()

If you start the application and go to the application's / or /index URLs, you will be immediately redirected to the login page, and after you log in using the credentials of the user that you added to your database, you will be returned to the original page, in which you will see a personalized greeting.

User Registration

The last piece of functionality that I'm going to build in this chapter is a registration form, so that users can register themselves through a web form. Let's begin by creating the web form class in app/forms.py:

app/forms.py: User registration form

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from app.models import User

# ...

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('Please use a different username.')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('Please use a different email address.')

There are a couple of interesting things in this new form related to validation. First, for the email field I've added a second validator after DataRequired, called Email. This is another stock validator that comes with WTForms that will ensure that what the user types in this field matches the structure of an email address.

The Email() validator from WTForms requires an external dependency to be installed:

(venv) $ pip install email-validator

Since this is a registration form, it is customary to ask the user to type the password two times to reduce the risk of a typo. For that reason I have password and password2 fields. The second password field uses yet another stock validator called EqualTo, which will make sure that its value is identical to the one for the first password field.

When you add any methods that match the pattern validate_<field_name>, WTForms takes those as custom validators and invokes them in addition to the stock validators. I have added two of those methods to this class for the username and email fields. In this case I want to make sure that the username and email address entered by the user are not already in the database, so these two methods issue database queries expecting there will be no results. In the event a result exists, a validation error is triggered by raising an exception of type ValidationError. The message included as the argument in the exception will be the message that will be displayed next to the field for the user to see.

To display this form on a web page, I need to have an HTML template, which I'm going to store in file app/templates/register.html. This template is constructed similarly to the one for the login form:

app/templates/register.html: Registration template

{% extends "base.html" %}

{% block content %}
    <h1>Register</h1>
    <form action="" method="post">
        {{ form.hidden_tag() }}
        <p>
            {{ form.username.label }}<br>
            {{ form.username(size=32) }}<br>
            {% for error in form.username.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.email.label }}<br>
            {{ form.email(size=64) }}<br>
            {% for error in form.email.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.password.label }}<br>
            {{ form.password(size=32) }}<br>
            {% for error in form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.password2.label }}<br>
            {{ form.password2(size=32) }}<br>
            {% for error in form.password2.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>{{ form.submit() }}</p>
    </form>
{% endblock %}

The login form template needs a link that sends new users to the registration form, right below the form:

app/templates/login.html: Link to registration page

    <p>New User? <a href="{{ url_for('register') }}">Click to Register!</a></p>

And finally, I need to write the view function that is going to handle user registrations in app/routes.py:

app/routes.py: User registration view function

from app import db
from app.forms import RegistrationForm

# ...

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)

And this view function should also be mostly self-explanatory. I first make sure the user that invokes this route is not logged in. The form is handled in the same way as the one for logging in. The logic that is done inside the if validate_on_submit() conditional creates a new user with the username, email and password provided, writes it to the database, and then redirects to the login prompt so that the user can log in.

Registration Form

With these changes, users should be able to create accounts on this application, and log in and out. Make sure you try all the validation features I've added in the registration form to better understand how they work. I am going to revisit the user authentication subsystem in a future chapter to add additional functionality such as to allow the user to reset the password if forgotten. But for now, this is enough to continue building other areas of the application.

Become a Patron!

Hello, and thank you for visiting my blog! If you enjoyed this article, please consider supporting my work on this blog on Patreon!

597 comments
  • #576 Miguel Grinberg said

    @Chresten: Looks like this issue has been fixed in the Flask-Login repo, but they haven't made a new release. If you need the fix now, install Flask-Login directly from the main branch on GitHub.

  • #577 Wasiu said

    @miguel Grinberg, I am having issue while running app after adding user registration it keeps saying :

    [2022-06-03 16:58:44,706] ERROR in app: Exception on /register [GET]
    Traceback (most recent call last):
    File "/mnt/c/Users/WASIU/Desktop/NEXXY/Python/Flask/microblog/venv/lib/python3.8/site-packages/flask/app.py", line 2077, in wsgi_app
    response = self.full_dispatch_request()
    File "/mnt/c/Users/WASIU/Desktop/NEXXY/Python/Flask/microblog/venv/lib/python3.8/site-packages/flask/app.py", line 1525, in full_dispatch_request
    rv = self.handle_user_exception(e)
    File "/mnt/c/Users/WASIU/Desktop/NEXXY/Python/Flask/microblog/venv/lib/python3.8/site-packages/flask/app.py", line 1523, in full_dispatch_request
    rv = self.dispatch_request()
    File "/mnt/c/Users/WASIU/Desktop/NEXXY/Python/Flask/microblog/venv/lib/python3.8/site-packages/flask/app.py", line 1509, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
    File "/mnt/c/Users/WASIU/Desktop/NEXXY/Python/Flask/microblog/app/routes.py", line 62, in register
    user.set_password(form.password.data)
    File "/mnt/c/Users/WASIU/Desktop/NEXXY/Python/Flask/microblog/app/models.py", line 17, in set_password
    self.password_hash= generate_password_hash(password)
    File "/mnt/c/Users/WASIU/Desktop/NEXXY/Python/Flask/microblog/venv/lib/python3.8/site-packages/werkzeug/security.py", line 88, in generate_password_hash
    h, actual_method = _hash_internal(method, salt, password)
    File "/mnt/c/Users/WASIU/Desktop/NEXXY/Python/Flask/microblog/venv/lib/python3.8/site-packages/werkzeug/security.py", line 36, in _hash_internal
    password = password.encode("utf-8")
    AttributeError: 'NoneType' object has no attribute 'encode'

    kindly assist.

  • #578 Miguel Grinberg said

    @Wasiu: You are passing None as the password. I can't tell you why, you'll need to debug this yourself, or compare your code against mine on GitHub.

  • #579 Ephraim Becker said

    How do I do this with WebAuthn?

  • #580 Miguel Grinberg said

    @Ephraim: I don't have any tutorials for WebAuthn, but Flask-Login is not tied to any particular authentication method. You can authenticate using any libraries of your choice, and once authentication passes you call login_user() to update the user session.

  • #581 Todd Decker said

    @Miguel the code above works perfectly well; however, PyCharm's linter flags two warning issues that I don't know how to mitigate. First, it sees validate_username() and validate_email() as static. I assume it's doing this because it doesn't see where they are being used. I assume they are used by wtforms auto-magically. Is there a way I can correct things so PyCharm is happy? Second, in user = User(username=form.username.data, email=form.email.data) PyCharm is throwing an "unexpected argument" warning. I found an obtuse reference to this message that it could be caused by the mixin and something about an init being needed on the User model class. What are your thoughts on correcting this warning too?

  • #582 Todd Decker said

    As a follow-up to my prior question, the warning on the concern Pycharm has with wanting validate_username() and validate_email() to be static can be suppressed by putting # noinspection PyMethodMayBeStatic as an annotation right above the function definition. The problem with unexpected arguments can be fixed by adding the following code to the model classes:

    def __init__(self, *args, **kwargs):
        pass
    

    I'd still like to know why these warnings are being generated, but these suggestions suppress them

  • #583 Miguel Grinberg said

    @Todd: first of all, linters are wrong more often than people think. Python is a dynamic language, and as such it is very difficult for a static code analyzer to figure out how things work. If you want to silence incorrect linter warnings you'll have to add annotations manually into the code to disable them.

    I do not subscribe to the idea of modifying the code to make the linter happy when the code is already correct and it is the linter that is wrong. But yes, adding a constructor to your class might silence your linter's warning on the User class, at the cost of adding unnecessary code to your application. In case it isn't clear, the warning here is triggered because the linter is unable to find the parent class of your User model, which has the constructor that takes the arguments that you have in your code.

  • #584 Joseph Rono said

    Hey Miguel, I might be a little late for the tutorial. I keep getting this error message when I try to login. What might be the issue?

    AttributeError: 'function' object has no attribute 'args'
    127.0.0.1 - - [04/Nov/2022 17:42:52] "POST /login?next=%2Findex HTTP/1.1" 500 -

  • #585 Miguel Grinberg said

    @Joseph: It's hard to diagnose the problem from an error message. Please provide the entire output, with stack trace.

  • #586 Richard said

    I noticed the user-name is case-sensitive, mostly because you have doubled it up with Display name. Wouldn't it be better to log in with the email address or convert it to lower before hashing?

  • #587 Miguel Grinberg said

    @Richard: Hashing is only applied to the password, never to usernames or emails. Using case-insensitive names and/or emails shouldn't take much effort if you prefer that, as you can probably imagine, you have to apply lower() to these values before saving them to the database and before searching during login. And probably you'd also want to save the original case-sensitive values in separate columns that are used for display.

  • #588 Denny McLean said

    Hi Miguel, great blog. I'm wondering if the flash('Congratulations, you are now a registered user!') function is expected to work at this stage of the blog. I didn't see it but I'm able to register new users then get redirected to the login page and login with the new users credentials. I've tried debugging and if I've followed you so far the flash would need to be rendered either in the base.html or login.html since we redirect the user to the login page.

  • #589 Miguel Grinberg said

    @Denny: Yes, flashed messages should be visible. A basic rendering of flashed messages is included in chapter 3 of this tutorial.

  • #590 Avner said

    Hi Miguel,

    I have a web app that can connect to 2 webservers (for development purposes) and I want to specify the IP address of the webserver in the login form.
    Up to now I directed to a login page on a the first webserver, and it works ok. The code for the login page on a the first webserver is shown in snippet1 below.

    To be able to specify the IP address of the webserver, I want to dynamically create a form in javascript, and add a field for the IP address.
    I created a dynamic form on the frontend, by embeding the html page from snippet1.
    But on submit, I'm getting and error "405 method not allowed" from the webserver.

    Can you show an example on what needs to change?
    Thanks

    snippet1 - the code for the login page on a the first webserver:

    <div class="admin-add-user">
        <div class="page-header">
            <h2>Log In</h2>
        </div>
        <h1>Sign In</h1>
        <div class="row">
            <div class="col-md-4">
                <input id="csrf_token" name="csrf_token" type="hidden" value="...">
                <form action="" method="post" class="form" role="form">
                    <input id="csrf_token" name="csrf_token" type="hidden" value="...">
                    <div class="form-group  required"><label class="control-label" for="email">Email1</label>
                        <input class="form-control" id="email" name="email" required="" type="text" value="">
                    </div>
                    <div class="form-group  required"><label class="control-label" for="password">Password</label>
                        <input class="form-control" id="password" name="password" required="" type="password" value="">
                    </div>
                    <div class="checkbox">
                        <label>
                            <input id="remember_me" name="remember_me" type="checkbox" value="y"> Remember Me
                        </label>
                    </div>
                    <input class="btn btn-default" id="submit" name="submit" type="submit" value="Sign In">
                </form>
            </div>
        </div>
        <br>
        <p><em>Forgot your password? </em><a href="/reset">Reset!!</a></p>
    </div>
    
  • #591 Miguel Grinberg said

    @Avner: this is a JavaScript question, not at all related to this tutorial. It is also non-trivial, so it is impossible for me to provide a solution in the context of a comment and from memory.

  • #592 Avner Moshkovitz said

    In regards to question #590, and your answer in #591.
    I solved the problem by formulating the url on the front-end in Javascript. url1 for server1, and url2 for server2.
    So the approach still calls the login page in the backend: either url1 for server1 or url2 for server2
    Like you said, the solution is completely unrelated to flask or bask-end.
    I'm mentioning this only for benefit to others.

    Thanks
    Avner

  • #593 Cassiano Tadao Yasumitsu said

    Hi, running this in 2023.
    In the Logging Users In session I'm struggling with this error:
    "AttributeError: 'NoneType' object has no attribute 'count'"

    Traceback (most recent call last):
      File "/Users/cassiano/code/Python/flask_tutorial/venv/lib/python3.9/site-packages/flask/app.py", line 2548, in __call__
        return self.wsgi_app(environ, start_response)
      File "/Users/cassiano/code/Python/flask_tutorial/venv/lib/python3.9/site-packages/flask/app.py", line 2528, in wsgi_app
        response = self.handle_exception(e)
      File "/Users/cassiano/code/Python/flask_tutorial/venv/lib/python3.9/site-packages/flask/app.py", line 2525, in wsgi_app
        response = self.full_dispatch_request()
      File "/Users/cassiano/code/Python/flask_tutorial/venv/lib/python3.9/site-packages/flask/app.py", line 1822, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "/Users/cassiano/code/Python/flask_tutorial/venv/lib/python3.9/site-packages/flask/app.py", line 1820, in full_dispatch_request
        rv = self.dispatch_request()
      File "/Users/cassiano/code/Python/flask_tutorial/venv/lib/python3.9/site-packages/flask/app.py", line 1796, in dispatch_request
        return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
      File "/Users/cassiano/code/Python/flask_tutorial/app/routes.py", line 33, in login
        if user is None or not user.check_password(form.password.data):
      File "/Users/cassiano/code/Python/flask_tutorial/app/models.py", line 22, in check_password
        return check_password_hash(self.password_hash, password)
      File "/Users/cassiano/code/Python/flask_tutorial/venv/lib/python3.9/site-packages/werkzeug/security.py", line 103, in check_password_hash
        if pwhash.count("$") < 2:
    AttributeError: 'NoneType' object has no attribute 'count'
    

    Please, any advice?

  • #594 Miguel Grinberg said

    @Cassiano: which year it is when you run this on should not change anything. The error is saying that you passed a None value to the check_password_hash() function instead of a valid hash. You need to debug this backwards to determine why you are not passing a hash to this function.

  • #595 Chandan said

    Hi Miguel,

    In my flask app, I have only 1 user session allowed at a time(in a browser) such that if a user "A" is already logged in a browser tab, and if I try to open another tab with say login page, it will redirect to user "A"'s home page. This works fine. The problem I now face is that if I have 2 tabs open with login page and say in 1st tab user "A" logs in successfully and next if now user "B" tries to login from the 2nd tab, it allows to login but changes it to user "A" homepage(because initially "A" got logged in and at a time only one session is allowed). What I want is that, if user "B" wants to login from 2nd tab and if user "A" is already logged in from 1st tab, we should get a message asking if want to logout the user "A" and allow "B" to login?

    Is this something possible with Flask sessions?

  • #596 Miguel Grinberg said

    @Chandan: you can always do anything you want. Flask does not handle authentication, so this is outside its area. The Flask-Login extension supports the more normal usages. To do what you want you would need to implement custom logic. In general what you are asking is not a common situation, because once you are logged in, a well behaved application would never show you a login form to log in again. Note the first two lines in the /login route, which redirect users to the index page if they attempt to log in a second time. The only way to be in the situation that you describe is by going to the log in page on two tabs while you are logged out. Is this an interesting use case to cover? I don't believe it is, but of course you are free to handle it yourself if you think it is important.

  • #597 Chandan said

    Thanks @Miguel for your comments.

    The points you covered are true that a properly constructed web app won't show login page after a user is logged in successfully. I came to this unusual scenario(while testing) and hence noticed this behaviour(which I showed in my above comment). In some other professional websites, I tested the same scenario and found that they present with a window popup in such cases when a new session is being tried from another browser tab. In the popup window, we have a choice to either continue with existing session OR logout and start with a new session.

    Thanks for your points and I am now able to handle this inside myapp itself.

Leave a Comment