Event-CRUD-Flask-python3-API/middlewares/userMiddlewares.py
2024-01-07 16:30:55 +02:00

73 lines
2.7 KiB
Python

from functools import wraps
from flask import request, jsonify, g
from flask_jwt_extended import jwt_required, get_jwt_identity
def validate_user_post_request(f):
@wraps(f)
def decorated_function(*args, **kwargs):
data = request.get_json()
if not data:
return jsonify({"message": "No input data provided"}), 400
# Check required fields
required_fields = ['username', 'password', 'email', 'location']
if not all(field in data for field in required_fields):
return jsonify({"message": "Please check your data, you missing some props; visit our docs https://git.dayanhub.com/kfir"}), 400
# Validate 'username'
if not isinstance(data['username'], str) or not data['username'].strip():
return jsonify({"message": "Invalid username"}), 400
# Validate 'password'
if not isinstance(data['password'], str) or not data['password'].strip():
return jsonify({"message": "Invalid password"}), 400
# Validate 'email'
if not isinstance(data['email'], str) or not data['email'].strip():
return jsonify({"message": "Invalid email"}), 400
# Validate 'location'
if not isinstance(data['location'], str) or not data['location'].strip():
return jsonify({"message": "Invalid location"}), 400
return f(*args, **kwargs)
return decorated_function
def validate_user_login_request(f):
@wraps(f)
def decorated_function(*args, **kwargs):
data = request.get_json()
if not data:
return jsonify({"message": "No input data provided"}), 400
# Check required fields
required_fields = ['email', 'password']
if not all(field in data for field in required_fields):
return jsonify({"message": "Please check your data, you missing some props; visit our docs https://git.dayanhub.com/kfir"}), 400
# Validate 'email'
if not isinstance(data['email'], str) or not data['email'].strip():
return jsonify({"message": "Invalid email"}), 400
# Validate 'password'
if not isinstance(data['password'], str) or not data['password'].strip():
return jsonify({"message": "Invalid password"}), 400
return f(*args, **kwargs)
return decorated_function
def authenticate_user(f):
@wraps(f)
@jwt_required(locations=["cookies"]) # Specify to look for the token in cookies
def decorated_function(*args, **kwargs):
# Get user identity from JWT
user_id = get_jwt_identity()
if user_id:
g.user_id = user_id
else:
return jsonify({"error": "Invalid session token"}), 401
return f(*args, **kwargs)
return decorated_function