Open In App

How to Integrate Flask-Admin and Flask-Login

Last Updated : 27 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let’s is how to implement this in this article.

Integrate Flask Admin and Flask Login

Here, we connect our Python application to a database to integrate Flask-Admin and Flask-Login. Python file to MySQL database, MySQL database is a client/server which, make provides safety safe data space for registering and login for the user and admin it is very safe we can use this in many languages, so MySQL is where our data will store safely and we can see who is logging and restoring in our system. In order to integrate admin and login, we must first create a registration page and store its data in MySQL. Once that is done, we can log in to our login system and also add a function for logout.

Templates file 

In the templates folder we basically made three files one for register, another one for login, and at last one for admin so first we write code for register.html

register.html

In this HTML file we are writing for simple registration form in which we are making three inputs username, email, and Password these inputs are required to fill for registration after filling in this input we need to click on the register when we click on the register button then will one flashing message will show on the same page the message is you are register successfully and our registration data securely save in  MySQL database now we can log in using our credentials for flashing massage we are using Jinja2 {% ..%} in HTML file and also if we registered with same email id when will also flash email id exists .that is the explanation of register.html code. 

HTML




<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Registration Form</title>
 
</head>
<body>
<div class="container">
    <h2>Admin Registration </h2>
    <form action="{{ url_for('register') }}" method="post">
        {% if message is defined and message %}
            <div class="alert alert-warning">  <strong>  {{ message }} ???? </strong></div>
        {% endif %}
        <br>
        <div class="form-group">
             Name: <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" name="name">
        </div>
        <div class="form-group">
             Email: <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" name="email">
        </div>
        <div class="form-group">
            Password: <input type="password" class="form-control" id="password" name="password" placeholder="Enter password" name="pswd">
        </div>   
        <button type="submit" class="btn btn-primary">Register</button>
        <p class="bottom">Already have an account?  <a class="bottom" href="{{url_for('login')}}"> Login here</a></p>
    </form>
</div>       
</body>
</html>


Output:

Registration Page

login.html

In login.html we are making simple two inputs one for username and another one for the password we registered successfully so we can log in using our email and password which we set previously if log in right email and password then it will redirect us to another page user/login profile page for which we are using url_for in which we are writing the function of file which we want to display after a successful registration. 

HTML




<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Login Form</title>
 
</head>
<body>   
<div class="container">
    <h2>User Login</h2>
    <form action="{{ url_for('login') }}" method="post">
        {% if message is defined and message %}
            <div class="alert alert-warning"> <strong> {{ message }} ????</strong></div>
        {% endif %}
        <br>
        <div class="form-group">
            Email: <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" name="email">
        </div>
        <div class="form-group">
         Password: <input type="password" class="form-control" id="password" name="password" placeholder="Enter password" name="pswd">
        </div>   
        <button type="submit" class="btn btn-primary">Login</button>
        <p class="bottom">Don't have an account?  <a class="bottom" href="{{url_for('register')}}"> Register here</a></p>
    </form>
</div>
</body>
</html>


Output:

Login Page

admin.html

In these files we are writing some lines of code to welcome the user/admin after successful login and also we write one extra session.name code which means when we login then our name will also display on the screen which we are using during register and also one button will show on screen for logout by using these button we can logout and we need to log in again.

HTML




<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Account</title>
 
</head>
<body>
<div class="container">
    <div class="row">   
        <h2>Admin Profile</h2>
    </div>
    <br>
    <div class="row">   
        Logged in : <strong>{{session.name}} ???? | <a href="{{ url_for('logout') }}"> Logout</a>
    </div>
    <br><br>
    <div class="row">
         
        <h2>Welcome to the Admin profile page... ????</h2>
    </div>       
</div>
</body>
</html>


Output:

Admin Profile Page 

In place of admin, the admin name will display when we log in successfully.

app.py

First, we create a file called app.py in which we write the python code. In this file, we import all the libraries we need to execute our app and connect to MySQL, as well as the libraries we need to perform admin login from the database. Python code database, MySQLdb is imported to create the data for our database, followed by the import of re, which will read the data from our MySQL database. After importing all modules, we initialize the flask function and create a secret key for our flask. Next, we write the code for the database in PHPMyAdmin, adding the database name, email address, and password as shown in the code on the register page.

# Import all important libraries
from flask import *
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re

# initialize first flask
app = Flask(__name__)
app.secret_key = 'xyzsdfg'

# Set MySQL data
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'user-system'

mysql = MySQL(app)

Then, we create a working login() and create a session for login and registration for a system that also retrieves our data from MySQL. In this function, we pass the request to the login form by entering our name, password, and email when we click on enter, it will automatically save on our PHPMyAdmin by MySQL data, and one successfully registered message will also appear on the login page when we registered successfully in the register page.

We can log in on the login page by entering our email address and password. There are some flashing messages added, such as if we try to register again with the same email address, it will say “User already exists.” We can create two registered accounts using the same email address. When we successfully log in, the username we entered on the registration page will also appear in the profile. In this case, we entered “GFG.” When we successfully logged in, it will say “Welcome GFG.” That explains the entire code as well as how it will function.

Python3




# code
# Import all important libraries
from flask import *
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
 
# initialize first flask
app = Flask(__name__)
app.secret_key = 'xyzsdfg'
 
# Set MySQL data
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'user-system'
 
mysql = MySQL(app)
 
# Make login function for login and also make
# session for login and registration system
# and also fetch the data from MySQL
 
 
@app.route('/')
@app.route('/login', methods=['GET', 'POST'])
def login():
    message = ''
    if request.method == 'POST' and 'email' in request
                .form and 'password' in request.form:
         
        email = request.form['email']
        password = request.form['password']
        cursor = mysql.connection.cursor
                        (MySQLdb.cursors.DictCursor)
        cursor.execute(
            'SELECT * FROM user WHERE email = % s AND password = % s',
          (email, password, ))
        user = cursor.fetchone()
        if user:
            session['loggedin'] = True
            session['userid'] = user['userid']
            session['name'] = user['name']
            session['email'] = user['email']
            message = 'Logged in successfully !'
            return render_template('admin.html',
                                   message=message)
        else:
            message = 'Please enter correct email / password !'
    return render_template('login.html', message=message)
 
 
# Make function for logout session
@app.route('/logout')
def logout():
    session.pop('loggedin', None)
    session.pop('userid', None)
    session.pop('email', None)
    return redirect(url_for('login'))
 
# Make a register session for registration session
# and also connect to Mysql to code for access login
# and for completing our login
# session and making some flashing massage for error
 
 
@app.route('/register', methods=['GET', 'POST'])
def register():
    message = ''
    if request.method == 'POST' and 'name' in request
        .form and 'password' in request.form and
                                  'email' in request.form:
           
        userName = request.form['name']
        password = request.form['password']
        email = request.form['email']
        cursor = mysql.connection.cursor
                (MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM user WHERE email = % s',
                       (email, ))
        account = cursor.fetchone()
        if account:
            message = 'Account already exists !'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            message = 'Invalid email address !'
        elif not userName or not password or not email:
            message = 'Please fill out the form !'
        else:
            cursor.execute(
                'INSERT INTO user VALUES (NULL, % s, % s, % s)',
              (userName, email, password, ))
            mysql.connection.commit()
            message = 'You have successfully registered !'
    elif request.method == 'POST':
        message = 'Please fill out the form !'
    return render_template('register.html', message=message)
 
 
# run code in debug mode
if __name__ == "__main__":
    app.run(debug=True)



MySQL database

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads