Learn flash login user session management of flash

Flash login user controls user session management. In short, it controls login. If you write your own login system, you usually operate the session, and then the background judges the permissions according to the session. Flask login is responsible for this part. Start directly

install

pip install flask-login

Import LoginManager

from flask_login import LoginManager
#Create a login_manager 
login_manager = LoginManager()

#A user is required_ Loader callback. This callback is used to reload the user object from the user ID stored in the session. It should take a user's unicode ID as a parameter and return the corresponding user object.

@login_manager.user_loader
def load_user(user_id):
    from epay.models import User
    user = User.query.get(int(user_id))
    return user

The user's class needs to implement these properties and methods:

is_authenticated
Returns True when the user passes authentication, that is, when a valid certificate is provided. (only authenticated users will meet the login_required condition.)
is_active
If this is an active user and has passed the authentication, the account has been activated, has not been deactivated, and does not meet any conditions for your app to reject an account, return True. Inactive accounts may not log in (of course, without being forced).
is_anonymous
Returns True if it is an anonymous user. (real users should return False.)
get_id()
Returns a that uniquely identifies the user and can be used to retrieve information from the user_ The loader callback loads the user's unicode. Note that it must be a unicode -- if the ID is originally an int or other type, you need to convert it to unicode.
To easily implement user classes, you can inherit from UserMixin, which provides a default implementation of all these methods. (although this is not necessary.)

class User(db.Model,UserMixin):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(100), nullable=False)
    created_at = db.Column(db.Date, nullable=True)
    login_date = db.Column(db.Date, nullable=True)

View login logic
auth.py

from flask import Blueprint,render_template,request,redirect,url_for,flash
from flask_login import login_user, logout_user, login_required, current_user

from epay.models import User

import hashlib

from epay.forms import UserForm

auth_bp = Blueprint('auth',__name__)

@auth_bp.route('/login',methods=['POST','GET'])
def login():
    form = UserForm()
    if request.method == 'POST':
        email = request.form.get('email')  # args get mode parameter
        
        password = request.form.get('password')
        password = hashlib.md5(password.encode(encoding='utf-8')).hexdigest()
        user = User.query.filter_by(email=email,password=password).first()
        if user:
            flash('Welcome back.', 'info')
            login_user(user)
            return redirect(url_for('admin.index'))
        else:
            flash('Invalid username or password.', 'warning')
            return render_template('auth/login.html',form=form)
    elif request.method == 'GET':
        return render_template('auth/login.html',form=form)


@auth_bp.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('auth.login'))

login.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <!-- basic -->
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <!-- mobile metas -->
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta name="viewport" content="initial-scale=1, maximum-scale=1">
      <!-- site metas -->
      <title></title>
      <meta name="keywords" content="">
      <meta name="description" content="">
      <meta name="author" content="">
      <!-- site icon -->
      <link rel="icon" href="{{ url_for('static',filename ='images/fevicon.png') }} " type="image/png" />
      <!-- bootstrap css -->
      <link rel="stylesheet" href="{{ url_for('static',filename ='css/bootstrap.min.css') }}" />
      <!-- site css -->
      <link rel="stylesheet" href="{{ url_for('static',filename ='style.css') }}" />
      <!-- responsive css -->
      <link rel="stylesheet" href="{{ url_for('static',filename ='css/responsive.css') }}" />
      <!-- color css -->
      <link rel="stylesheet" href="{{ url_for('static',filename ='css/colors.css') }}" />
      <!-- select bootstrap -->
      <link rel="stylesheet" href="{{ url_for('static',filename ='css/bootstrap-select.css') }}" />
      <!-- scrollbar css -->
      <link rel="stylesheet" href="{{ url_for('static',filename ='css/perfect-scrollbar.css') }}" />
      <!-- custom css -->
      <link rel="stylesheet" href="{{ url_for('static',filename ='css/custom.css') }}" />
      <!-- calendar file css -->
      <link rel="stylesheet" href="{{ url_for('static',filename ='js/semantic.min.css') }}" />
      <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
      <![endif]-->
   </head>
   <body class="inner_page login">
      <div class="full_container">
         <div class="container">
            <div class="center verticle_center full_height">
               <div class="login_section">
                  <div class="logo_login">
                     <div class="center">
                        <img width="210" src="{{ url_for('static',filename ='images/logo/logo.png') }}" alt="#" />
                     </div>
                  </div>
                  <div class="login_form">
                     <form action="{{ url_for('auth.login') }}" method="POST">
                        {{ form.csrf_token }}
                        <fieldset>
                           <div class="field">
                              <label class="label_field">Email Address</label>
                              <input type="email" name="email" placeholder="E-mail" />
                           </div>
                           <div class="field">
                              <label class="label_field">Password</label>
                              <input type="password" name="password" placeholder="Password" />
                           </div>
                           <div class="field margin_0">
                              <label class="label_field hidden">hidden label</label>
                              <button class="main_bt">Sing In</button>
                           </div>
                        </fieldset>
                     </form>
                  </div>
               </div>
            </div>
         </div>
      </div>

      <!-- jQuery -->
      <script src="{{ url_for('static',filename ='js/jquery.min.js') }}"></script>
      <script src="{{ url_for('static',filename ='js/popper.min.js') }}"></script>
      <script src="{{ url_for('static',filename ='js/bootstrap.min.js') }}"></script>
      <!-- wow animation -->
      <script src="{{ url_for('static',filename ='js/animate.js') }}"></script>
      <!-- select country -->
      <script src="{{ url_for('static',filename ='js/bootstrap-select.js') }}"></script>
      <!-- nice scrollbar -->
      <script src="{{ url_for('static',filename ='js/perfect-scrollbar.min.js') }}"></script>
      <script>
         var ps = new PerfectScrollbar('#sidebar');
      </script>
      <!-- custom js -->
      <script src="{{ url_for('static',filename ='js/custom.js') }}"></script>

      
      {% for message in get_flashed_messages() %}
         <script>
            alert("{{ message }}")
         </script>
      {% endfor %}

   </body>
</html>

To simplify, when we judge that the account and password match successfully, we call login_ The user (user) method indicates that the system has logged in to this user. If you want to determine whether you have logged in on other routes, add @ login in front of the method_ Required, as follows:

@admin_bp.route('/')
@admin_bp.route('/index')
@login_required
def index():
    return render_template('admin/index.html')

If the user has not logged in, he will jump to this path and automatically jump back to the login page. We need to configure the login page before initializing login_manager page:

login_manager.login_view = 'auth.login'

In this way, a simple configuration is completed, and a default variable current will be added to the test template_ user
If you want to directly output the user name in the template, you can write as follows:
{{ current_user.username }}

For more operations, you can view the following addresses:

http://www.pythondoc.com/flask-login/index.html#id1

(some explanations are also from the above address)

Keywords: Python Flask

Added by tisource on Thu, 13 Jan 2022 21:54:10 +0200