In this example we will explore
- Creating Login Page with HTML
- Taking the Login Credential
- Verifying the User with Login Data
- Redirect the user to the user page.
- Keep the users login for a amount of time with flask session
First Lets create a Login page with html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Login</h2>
<form method="POST" action="/login">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Now write our basic app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('login.html')
if __name__ == '__main__':
app.run(debug=True)
This code does nothing. Just shows the login page. Now add the features Retrieve the login Credential When user submit the data...
from flask import Flask, render_template, request, redirect, session
from datetime import timedelta
import secrets
app = Flask(__name__)
app.secret_key =secrets.token_urlsafe(32)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=3)
@app.route('/')
def index():
if session.get('logged_in'):
return 'You are Already Logged in'
else:
return render_template('login.html')
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
if username == 'username' and password == 'password':
session['logged_in'] = True
session.permanent = True
return redirect('/user')
else:
return redirect('/')
@app.route('/user')
def user():
if session.get('logged_in'):
return 'Login Successful'
else:
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
What happened here in the explanation This code secures the session and set the session time
app.secret_key =secrets.token_urlsafe(32)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=3)
First The server will check if the user is already logged in or not. If user already logged in it will return the Message That the user is already logged in. If not return to the login page.
@app.route('/')
def index():
if session.get('logged_in'):
return 'You are Already Logged in'
else:
return render_template('login.html')
When user submit the data. The server validate The data. And add Session Cookie in the users browser. And redirect to the users page
In the code our username is username and password is password
So When test the code login with “username” and “password”
And customize the line on your necessary
if username == ‘username‘ and password == ‘password‘:
This is for the example code. Usually the username and password checked from the database.
.
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
if username == 'username' and password == 'password':
session['logged_in'] = True
session.permanent = True
return redirect('/user')
else:
return 'Please try again.'
When user Request the Reedited URL.. The server checks the cookie( session data in the uses browser. If that found on session the server proceed the user to the users page. That's it...
In the Code we saved the user login for 3 Days . So users do not have to login again and again.
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=3)
Also you can add logout mechanism with this
@app.route('/logout')
def logout():
session.pop('logged_in', None)
return redirect('/')
More about the code
Timedelta
Timedelta class ( from python datetime module) helps to calculate the difference between two dates or times. Its mostly useful for task duration, schedule reminders, and also for analyzing time-based data
Secret Key
Think of your website as a treasure chest, and the secret key as the only way to unlock it. This unique code ensures your users’ journeys are safe and your website functions smoothly.
When someone visits your site, the secret key creates a special tag for their session. This helps protect their data (like sessions or preferences) from prying eyes.
It works like a digital fingerprint, confirming that all your website’s information is genuine and hasn’t been tampered with.
The secret key should always be kept private. it’s your website’s ultimate security measure, if it gets into the wrong hands, it could compromise your website’s security.
Get the code from Github