Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask-Login — User Registration, Login, Logout

Flask-Login — User Registration, Login, Logout

In this chapter you will learn to implement Session-based user authentication with Flask-Login, the most important security guarantee in Flask web development.


What is Flask-Login?

HTTP requests in web applications are essentially stateless—the server does not automatically remember who you are.

Flask-Login maintains user state through a Session mechanism: after login, the server stores the user ID in the Session, and subsequent requests automatically identify the current user.


Installation and initialization



(venv) $ pip install flask-login

Example

File path: app.py

from

flask

import

Flask

from

flask_sqlalchemy

import

SQLAlchemy

from

flask_login

import

LoginManager

app

=

Flask

(

name

)

app.

config

[

'SQLALCHEMY_DATABASE_URI'

]

=

'sqlite:///blog.db'

app.

config

[

'SECRET_KEY'

]

=

'your-secret-key-here'

 

Session encryption secret key (use an environment variable in production)

db

=

SQLAlchemy

(

app

)

Initialize LoginManager

login_manager

=

LoginManager

(

)

login_manager.

init_app

(

app

)

login_manager.

login_view

=

'auth.login'

   

Redirect unauthenticated users to the login page

login_manager.

login_message

=

'Please log in before accessing.'

SECRET_KEY It is the cornerstone of Flask's security system—Session encryption, CSRF Tokens, and Flash messages all depend on it. In production it must be read from an environment variable and never hardcoded.


Define the User model

Flask-Login requires the User model to implement several methods provided by UserMixin.

Example

File path: add to models.py

from

flask_login

import

UserMixin

from

werkzeug.

security

import

generate_password_hash

,

check_password_hash

class

User

(

UserMixin

,

db.

Model

)

:

   

"""User model"""

    tablename

=

'users'

   

id

=

db.

Column

(

db.

Integer

,

primary_key

=

True

)

    username

=

db.

Column

(

db.

String

(

50

)

,

unique

=

True

,

nullable

=

False

)

   

email

=

db.

Column

(

db.

String

(

120

)

,

unique

=

True

,

nullable

=

False

)

    password_hash

=

db.

Column

(

db.

String

(

256

)

,

nullable

=

False

)

   

def

set_password

(

self

,

password

)

:

       

"""Hash the password (never store plaintext passwords)"""

       

self

.

password_hash

=

generate_password_hash

(

password

)

   

def

check_password

(

self

,

password

)

:

       

"""Verify whether the password matches"""

       

return

check_password_hash

(

self

.

password_hash

,

password

)

   

def

repr

(

self

)

:

       

return

f

''

Define user_loader: Flask-Login uses this function to restore the user object from the session

@

login_manager.

user_loader

def

load_user

(

user_id

)

:

   

return

User.

query

.

get

(

int

(

user_id

)

)

UserMixin automatically injects the following attributes and methods into the User model:

Attribute / method Description
is_authenticated Whether the user is authenticated
is_active Whether the user is active
is_anonymous Whether the user is anonymous (not logged in)
get_id() Get the user's primary key ID

Generate the migration and run it:



(venv) $ flask db migrate -m "新增 User 模型"

(venv) $ flask db upgrade


Create the Auth Blueprint

Example

File path: app/blueprints/auth.py

from

flask

import

Blueprint

,

render_template

,

redirect

,

url_for

,

request

,

flash

from

flask_login

import

login_user

,

logout_user

,

login_required

,

current_user

from

app.

models

import

User

,

db

auth_bp

=

Blueprint

(

'auth'

,

name

)

@

auth_bp.

route

(

"/register"

,

methods

=

[

'GET'

,

'POST'

]

)

def

register

(

)

:

   

"""User registration"""

   

if

current_user.

is_authenticated

:

       

return

redirect

(

url_for

(

'main.index'

)

)

   

if

request.

method

==

'POST'

:

        username

=

request.

form

.

get

(

'username'

,

''

)

.

strip

(

)

       

email

=

request.

form

.

get

(

'email'

,

''

)

.

strip

(

)

        password

=

request.

form

.

get

(

'password'

,

''

)

       

Validate required fields

       

if

not

username

or

not

email

or

not

password:

            flash

(

'All fields are required.'

,

'error'

)

           

return

render_template

(

'register.html'

)

       

Check whether the username and email already exist

       

if

User.

query

.

filter_by

(

username

=

username

)

.

first

(

)

:

            flash

(

'Username is already taken.'

,

'error'

)

           

return

render_template

(

'register.html'

)

       

if

User.

query

.

filter_by

(

email

=

email

)

.

first

(

)

:

            flash

(

'Email is already registered.'

,

'error'

)

           

return

render_template

(

'register.html'

)

       

Create users

       

user

=

User

(

username

=

username

,

email

=

email

)

       

user

.

set_password

(

password

)

   

Hash and store the password

        db.

session

.

add

(

user

)

        db.

session

.

commit

(

)

        login_user

(

user

)

             

Automatically log in after registration

        flash

(

f

'Registration successful, welcome, {username}!'

,

'success'

)

       

return

redirect

(

url_for

(

'main.index'

)

)

   

return

render_template

(

'register.html'

)

@

auth_bp.

route

(

"/login"

,

methods

=

[

'GET'

,

'POST'

]

)

def

login

(

)

:

   

"""User Login"""

   

if

current_user.

is_authenticated

:

       

return

redirect

(

url_for

(

'main.index'

)

)

   

if

request.

method

==

'POST'

:

        username

=

request.

form

.

get

(

'username'

,

''

)

.

strip

(

)

        password

=

request.

form

.

get

(

'password'

,

''

)

       

user_loader looks up the user in the database

       

user

=

User.

query

.

filter_by

(

username

=

username

)

.

first

(

)

       

Verify the password (the password itself is never logged)

       

if

user

is

None

or

not

user

.

check_password

(

password

)

:

            flash

(

'Invalid username or password.'

,

'error'

)

           

return

render_template

(

'login.html'

)

        login_user

(

user

,

remember

=

request.

form

.

get

(

'remember'

)

)

        flash

(

f

'Welcome back, {username}!'

,

'success'

)

       

After login, redirect to the page visited before logging in (the next parameter in the URL)

        next_page

=

request.

args

.

get

(

'next'

)

       

return

redirect

(

next_page

or

url_for

(

'main.index'

)

)

   

return

render_template

(

'login.html'

)

@

auth_bp.

route

(

"/logout"

)

@

login_required      

Only logged-in users can log out

def

logout

(

)

:

    logout_user

(

)

    flash

(

'You have been safely logged out.'

,

'info'

)

   

return

redirect

(

url_for

(

'main.index'

)

)

Imports needed in the App

Example

File path: register the auth Blueprint in app.py

from

app.

blueprints

.

auth

import

auth_bp

app.

register_blueprint

(

auth_bp

)

Never store passwords in plaintext!generate_password_hash() Use the PBKDF2 algorithm to salted-hash passwords. Even if the database is leaked, attackers cannot reverse-engineer the passwords. When verifying a password, use check_password_hash()。


Create Login and Registration Templates

Example

{% extends 'base.html' %}

{% block title %}Login - RUNOOB Blog{% endblock %}

{% block content %}

   

Login

   

       

           

           

       

       

           

           

       

       

           

       

       

   

   

        Don't have an account yet?

Register now

   

{% endblock %}

Update the navbar to show login status

Example

current_user It is a proxy object automatically injected by Flask-Login, available directly in all templates and view functions. When logged in it is a User object; when not logged in it is an AnonymousUserMixin instance.


Chapter Summary

In this chapter you integrated Flask-Login Session authentication: UserMixin + user_loader for the user model, login_user/logout_user for Session management, werkzeug for password hashing, @login_required to protect views, and current_user in templates to check status.

Now the blog has a complete user registration, login, and logout flow.