feat: add authentication middleware to restrict access to logged-in users only

This commit is contained in:
Manuel Weiser 2024-09-02 10:40:44 +02:00
parent 67e0624c68
commit 54061aac2c

View File

@ -1,9 +1,27 @@
from flask import Blueprint, request, jsonify from flask import Blueprint, request, jsonify, g
from models import db, User from models import db, User
from datetime import datetime from datetime import datetime
user_bp = Blueprint('user', __name__) user_bp = Blueprint('user', __name__)
def authenticate():
# Hier wird die Authentifizierung überprüft (z.B. durch Token oder Session)
username = request.headers.get('X-Username')
password = request.headers.get('X-Password')
if username and password:
user = User.query.filter_by(username=username, password=password).first()
if user:
g.user = user
return True
return False
@user_bp.before_request
def before_request():
# Überprüfen, ob der Benutzer angemeldet ist, außer bei Login
if request.endpoint not in ['user.login_user']:
if not authenticate():
return jsonify({'message': 'Unauthorized access!'}), 401
@user_bp.route('/users', methods=['POST']) @user_bp.route('/users', methods=['POST'])
def create_user(): def create_user():
data = request.json data = request.json