2024-09-02 10:40:44 +02:00
|
|
|
from flask import Blueprint, request, jsonify, g
|
2024-09-02 10:32:26 +02:00
|
|
|
from models import db, User
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
user_bp = Blueprint('user', __name__)
|
|
|
|
|
2024-09-02 10:40:44 +02:00
|
|
|
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
|
|
|
|
|
2024-09-02 10:32:26 +02:00
|
|
|
@user_bp.route('/users', methods=['POST'])
|
|
|
|
def create_user():
|
|
|
|
data = request.json
|
|
|
|
new_user = User(
|
|
|
|
username=data['username'],
|
|
|
|
password=data['password'],
|
|
|
|
role=data.get('role', 'user'), # Default role is 'user'
|
|
|
|
last_login=None
|
|
|
|
)
|
|
|
|
db.session.add(new_user)
|
|
|
|
db.session.commit()
|
|
|
|
return jsonify({'message': 'User created!'}), 201
|
|
|
|
|
|
|
|
@user_bp.route('/users/login', methods=['POST'])
|
|
|
|
def login_user():
|
|
|
|
data = request.json
|
|
|
|
user = User.query.filter_by(username=data['username'], password=data['password']).first()
|
|
|
|
if user:
|
|
|
|
user.last_login = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
|
|
|
db.session.commit()
|
|
|
|
return jsonify({'message': 'Login successful!', 'role': user.role}), 200
|
|
|
|
return jsonify({'message': 'Invalid credentials!'}), 401
|
|
|
|
|
|
|
|
@user_bp.route('/users', methods=['GET'])
|
|
|
|
def get_users():
|
|
|
|
users = User.query.all()
|
|
|
|
return jsonify([{
|
|
|
|
'id': user.id,
|
|
|
|
'username': user.username,
|
|
|
|
'role': user.role,
|
|
|
|
'last_login': user.last_login
|
|
|
|
} for user in users])
|