Add User and Display Current Username in Flask (original) (raw)

Create a Flask authentication system with user registration, login functionality, session management, and MySQL database integration. After successful login, users are redirected to a profile page where their username is displayed dynamically and user data is stored in MySQL for easy management via phpMyAdmin.

Creating Templates for User Interface

We need three HTML files inside a templates folder:

register.html

This page includes fields for username, email, and password. Once submitted, it stores the data in the MySQL database and flashes a success message.

HTML `

User Registration Form

GFG User Registration

Note : fill following details !

{% if message is defined and message %}
{{ message }}
{% endif %}
Name:
Email:
Password:
Register

Already have an account? Login here

`

**Output:

User Registration page

login.html

This page allows registered users to log in using their email and password. Upon successful login, they will be redirected to the user profile page.

HTML `

User Login Form

GFG User Login

{% if message is defined and message %}
{{ message }}
{% endif %}
Email:
Password:
Login

Don't have an account? Register here

`

**Output:

login-page-mysql

Login page

user.html

Displays the logged-in username and provides a logout button.

HTML `

User Account

User Profile


Logged in : {{ session['name'] }} | Logout


    <h2>Welcome to the User profile page...</h2> 
</div>        

`

**Output:

registration-mysql-page4

User Page

Creating Database

Make sure MySQL is installed on your system, if it is not, refer to Setting up MySQL. Log in to MYSQL server from terminal and create database "user_table" by using commmand:

CREATE DATABASE user_table;

This command will create the database and the user table will be created from the flask app code.

Implementing Flask Application

Step 1: Import all library

To set up a Flask application with MySQL for admin login, we start by writing the Python code in app.py. This file handles imports, database connections, and authentication. Here’s the process:

Python `

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 = 'GeeksForGeeks'

Set MySQL data

app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' # Enter your password app.config['MYSQL_DB'] = 'user_table'

mysql = MySQL(app)

`

**Explanation:

Step 2: Implement Login and Logout Functionality

Create a login() function to handle user authentication and session management. This function interacts with MySQL to verify user credentials. Here's how it works:

Python `

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('user.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) session.pop('name', None) return redirect(url_for('login'))

`

**Explanation:

Step 3: Implement User Registration

On the login screen, users can log in using their email and password. The system also includes flash messages for better user feedback. Here's how it works:

Python `

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)

`

**Explanation:

Complete Code

Python `

from flask import * from flask_mysqldb import MySQL import MySQLdb.cursors import re

initialize first flask

app = Flask(name) app.secret_key = 'GeeksForGeeks'

Set MySQL data

app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '________' # Use you mysql password app.config['MYSQL_DB'] = 'user_table'

mysql = MySQL(app)

def create_table(): cursor = mysql.connection.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS user ( userid INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL ) """) mysql.connection.commit() cursor.close()

Call the function when the app starts

with app.app_context(): create_table()

@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('user.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) session.pop('name', None) return redirect(url_for('login'))

@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)

`

After writing the whole code open your terminal and run the following command

python app.py

Output

Run the flask app using "python app.py" command. The snapshot of the home page is already provided above, we will navigate to the register page and fill out the form, below is the snapshot:

registration-mysql-page1

Registration page

After filling up the registration form and clicking the "Register" button, we will get a registration successfull page like below:

registration-mysql-page2

Registration Successfull

Let's try to log in using the credentials we just registered with:

registration-mysql-page3

Login Page

After successfully logging in, we will see the username page:

registration-mysql-page4

User Page