from django.contrib.auth.decorators import user_passes_test from django.core.exceptions import ValidationError from django.contrib.auth import get_user_model, authenticate, login from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.db import transaction from IoTAnalyzer.exception_handling import handle_exceptions from django.contrib.auth import logout # Create user @handle_exceptions @transaction.atomic def register_user(request, username, password, is_superuser, is_staff): # Input validation if not username or not isinstance(username, str): raise ValidationError("Ungültiger Username") username = username.strip() if not username: raise ValidationError("Username darf nicht leer sein") if not password or not isinstance(password, str): raise ValidationError("Ungültiges Passwort") # Corrected, was previously "Ungültiger Username" password = password.strip() if not password: raise ValidationError("Passwort darf nicht leer sein") if User.objects.filter(username=username).exists(): raise ValidationError("User existiert bereits") # Correction: do not pass `request` as an argument user = User.objects.create_user( username=username, password=password, is_superuser=is_superuser, is_staff=is_staff ) return {"status": "success", "message": "User wurde erfolgreich erstellt"} # Delete user @handle_exceptions @transaction.atomic def delete_user(request, user_id): # Input validation if not user_id or not isinstance(user_id, int): raise ValidationError("Ungültige Id") # Check that the user is not deleting themselves if request.user.id == user_id: raise ValidationError("Sie können Ihren eigenen Account nicht löschen") user = User.objects.filter(id=user_id) if not user.exists(): raise ValidationError("User existiert nicht") else: user.delete() return {"status": "success", "message": "User wurde erfolgreich gelöscht"} # Reset password @handle_exceptions @transaction.atomic def set_password(request, user_id, new_password): # Input validation if not isinstance(user_id, int): raise ValidationError("Ungültige User ID") if not isinstance(new_password, str): raise ValidationError("Ungültiges Passwort Format") new_password = new_password.strip() if not new_password: raise ValidationError("Passwort darf nicht leer sein") # Fetch user try: user = User.objects.get(id=user_id) except User.DoesNotExist: raise ValidationError("User existiert nicht") # Permission check if request.user.id != user_id and request.user.is_superuser and request.user.is_staff: raise ValidationError("Keine Berechtigung zum Ändern des Passworts") # Password validation using Django's built-in validators try: validate_password(new_password, user) except ValidationError as e: raise ValidationError(e.messages) # Set and save password user.set_password(new_password) user.last_login = None user.save() return {"status": "success", "message": "Passwort erfolgreich geändert"} from django.utils.timezone import now @handle_exceptions @transaction.atomic def change_password(request, user_id, new_password): # Input validation if not isinstance(user_id, int): raise ValidationError("Ungültige User ID") if not isinstance(new_password, str): raise ValidationError("Ungültiges Passwort Format") new_password = new_password.strip() if not new_password: raise ValidationError("Passwort darf nicht leer sein") # Fetch user try: user = User.objects.get(id=user_id) except User.DoesNotExist: raise ValidationError("User existiert nicht") # Password validation using Django's built-in validators try: validate_password(new_password, user) except ValidationError as e: raise ValidationError(e.messages) # Set and save password user.set_password(new_password) user.last_login = now() # Sets last_login to the current date user.save() return {"status": "success", "message": "Passwort erfolgreich geändert", "last_login": user.last_login} @handle_exceptions @transaction.atomic def login_user(request, username, password): # Input validation if not username or not isinstance(username, str): raise ValidationError("Ungültiger Username") username = username.strip() if not username: raise ValidationError("Username darf nicht leer sein") if not password or not isinstance(password, str): raise ValidationError("Ungültiges Passwort") password = password.strip() if not password: raise ValidationError("Passwort darf nicht leer sein") user = authenticate(username=username, password=password) if user is None: raise ValidationError("Falscher Username oder Passwort") # Check the last login resetPassword = user.last_login is None # If a password reset is required, do not perform a login if resetPassword: return False, {"message": "Erster Login erkannt. Passwort muss zurückgesetzt werden.", "resetPassword": True, "user" : {"id": user.id, "username": user.username}} # Log the user in login(request, user) user_info = { 'id': user.id, 'username': user.username, 'changePassword': resetPassword, 'role': 'superuser' if user.is_superuser else 'staff' if user.is_staff else 'user' } return True, {"message": "Login erfolgreich", "user": user_info} @handle_exceptions @transaction.atomic def logout_user(request, user_id): # Input validation if not isinstance(user_id, int): raise ValidationError("Ungültige User ID") # Fetch user try: user = User.objects.get(id=user_id) except User.DoesNotExist: raise ValidationError("User existiert nicht") # Permission check if request.user.id != user_id: raise ValidationError("Keine Berechtigung zum Ausloggen dieses Benutzers") # Log the user out logout(request) return {"message": "Logout erfolgreich"} # Function to list all users with their roles #@user_passes_test(lambda u: u.is_superuser) def list_users(request): try: users = User.objects.all().order_by('username') user_list = [] for user in users: user_info = { 'id': user.id, 'username': user.username, 'password': user.password, 'email': user.email, 'role': 'superuser' if user.is_superuser else 'staff' if user.is_staff else 'user' } user_list.append(user_info) return { 'status': 'success', 'data': user_list } except Exception as e: if isinstance(e, User.DoesNotExist): raise ValidationError("Keine Benutzer gefunden") raise ValidationError("Fehler beim Abrufen der Benutzerliste: {}").format(str(e))