Add secure user authentication to your ML web app with our easy step-by-step guide. Enhance security and boost user trust!

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
import datetime
from flask import Flask, request, jsonify
import bcrypt // For password hashing
import jwt // For token-based authentication
app = Flask(**name**)
app.config['SECRET\_KEY'] = 'your-secret-key' // Secret key used for JWT encoding
// Using a simple dictionary to simulate a user database
users\_db = {}
// Endpoint where users register
@app.route('/register', methods=['POST'])
def register():
data = request.get\_json() // Extract JSON data from the request
email = data.get('email')
password = data.get('password')
if email in users\_db:
return jsonify({'message': 'User already exists!'}), 400
// Hash the password with bcrypt
hashed\_pass = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
// Store the user with hashed password
users\_db[email] = {
'email': email,
'password': hashed\_pass
}
return jsonify({'message': 'Registration successful!'}), 201
if **name** == '**main**':
app.run(debug=True)
@app.route('/login', methods=['POST'])
def login():
data = request.get\_json() // Extract login data from request
email = data.get('email')
password = data.get('password')
user = users\_db.get(email)
if not user:
return jsonify({'message': 'Invalid email or password!'}), 401
// Check provided password against the stored hashed password
if not bcrypt.checkpw(password.encode('utf-8'), user['password']):
return jsonify({'message': 'Invalid email or password!'}), 401
// Generate a token that expires in 30 minutes
token = jwt.encode(
{'email': email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)},
app.config['SECRET\_KEY'], algorithm='HS256'
)
return jsonify({'token': token}), 200
from functools import wraps
// Function to check token validity
def token\_required(f):
@wraps(f)
def decorated(_args, _\*kwargs):
token = None
// Check if 'Authorization' header is present
if 'Authorization' in request.headers:
// Typical header: "Bearer "
token = request.headers['Authorization'].split()[1]
if not token:
return jsonify({'message': 'Token is missing!'}), 401
try:
// Decode token with the app's secret key
data = jwt.decode(token, app.config['SECRET\_KEY'], algorithms=['HS256'])
current_user = users_db.get(data['email'])
if current\_user is None:
return jsonify({'message': 'User not found!'}), 401
except Exception as e:
return jsonify({'message': 'Token is invalid!', 'error': str(e)}), 401
return f(current\_user, _args, _\*kwargs)
return decorated
// Dummy ML prediction function for demonstration
def ml_predict(input_data):
// In a real application, call your machine learning model here
return {'prediction': 'predicted\_value'}
// Secure ML prediction endpoint with token verification
@app.route('/predict', methods=['POST'])
@token\_required
def predict(current\_user):
data = request.get\_json() // Get input data for prediction
result = ml\_predict(data)
return jsonify(result), 200
// Example: Client-side use of token in a fetch call
/\*
fetch('/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token // token obtained from login
},
body: JSON.stringify({input: 'your_data_here'})
})
.then(response => response.json())
.then(data => {
// Process ML prediction result
console.log(data);
});
\*/
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â