kurs-app/Controller/UserController.php
2025-07-04 11:12:24 +02:00

305 lines
9.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Blog\Controller;
use Blog\Model\UserModel;
class UserController{
private $view;
private $db;
private $validData = array();
private $errors = array();
private $labels = [
"name" => "Vorname*",
"lastname" => "Nachname*",
"email" => "E-Mail*",
"password" => "Passwort*",
"role" => "Rolle*"
];
private $validLoginData = array();
private $loginErrors = array();
private $loginLabels = [
"email" => "E-Mail*",
"password" => "Passwort*",
];
private $changeUserLabels = [
'name' => 'Vorname*',
'lastname' => 'Nachname*',
'email' => 'E-Mail*',
'password' => 'Passwort*',
];
public function __construct($view){
$this->db = new UserModel();
$this->view = $view;
}
public function showUserRegisterForm(){
if (!isset($this->errors)) {
$this->errors = [];
}
if (!isset($this->validData)) {
$this->validData = [];
}
$this->view->setVars([
'labels' => $this->labels,
'errors' => $this->errors,
'validData' => $this->validData
]);
}
public function showUserRegisterConfirmation(){
}
public function showUserLoginForm(){
$this->view->setVars([
'labels' => $this->loginLabels,
'errors' => $this->loginErrors,
'validData' => $this->validLoginData
]);
}
private function validateForm() {
foreach ($this->labels as $key => $label) {
if (!isset($_POST[$key]) || trim($_POST[$key]) === '') {
$this->errors[$key] = "Bitte $label angeben";
} else {
$this->validData[$key] = trim($_POST[$key]);
}
}
if (isset($this->validData['password'])) {
if (strlen($this->validData['password']) < 6) {
$this->errors['password'] = "Das Passwort muss mindestens 6 Zeichen lang sein.";
}
}
if (isset($this->validData['email']) && !filter_var($this->validData['email'], FILTER_VALIDATE_EMAIL)) {
$this->errors['email'] = "Bitte eine gültige E-Mail-Adresse eingeben.";
}
}
public function validateLoginForm(){
foreach ($this->loginLabels as $key => $label) {
if (isset($this->validData['password'])) {
if (strlen($this->validData['password']) < 6) {
$this->errors['password'] = "Das Passwort muss mindestens 6 Zeichen lang sein.";
}
}
if (isset($this->validData['email']) && !filter_var($this->validData['email'], FILTER_VALIDATE_EMAIL)) {
$this->errors['email'] = "Bitte eine gültige E-Mail-Adresse eingeben.";
}
}
}
public function showUserLoginConfirmation(){
$userId = $this->getCurrentUserId();
$user = null;
if($userId){
$user = $this->db->getUserById($userId);
}
$path = "Views/User/showUserLoginConfirmation.phtml";
if(file_exists($path)){
include $path;
}
}
public function register(){
$this->validateForm();
if(count($this->errors) > 0){
$this->view->setDoMethodName("showUserRegisterForm");
$this->showUserRegisterForm();
} else{
$this->db->createUser($_POST);
$this->login();
}
}
public function login(){
$user = $this->db->getUserByEmail($_POST["email"]);
$this->validateLoginForm();
if(!$user){
$this->loginErrors['email'] = "Email oder Passwort ist falsch";
$this->view->setDoMethodName("showUserLoginForm");
$this->showUserLoginForm();
return;
}
$hash = hash('sha256', $_POST["password"] . $user["salt"]);
if($hash == $user["passwort"]){
$this->setUserSession($user);
$this->showUserLoginConfirmation();
}else{
echo "Falsches Passwort";
}
}
public function setUserSession(array $user){
$_SESSION["user_id"] = $user["id"];
$_SESSION["user_role"] = $user["role"];
$_SESSION["vorname"] = $user["vorname"];
$_SESSION["name"] = $user["name"];
}
public function clearUserSession(){
unset($_SESSION["user_id"], $_SESSION["user_role"], $_SESSION["vorname"], $_SESSION["name"]);
}
public function logout(){
$this->clearUserSession();
header("Location: index.php?controller=user&do=showUserLoginForm");
exit();
}
public function isUserLoggenIn(){
return isset($_SESSION["user_id"]) && $_SESSION["user_id"] != null;
}
public function getCurrentUserId(){
return $_SESSION["user_id"] ?? null;
}
public function showUserAccountPage (){
}
public function showUserDeleteConfirmation(){
}
public function deleteAccount(){
$userId = $this->getCurrentUserId();
if($userId){
$this->db->deleteUser($userId);
$this->clearUserSession();
$this->view->setDoMethodName("showUserDeleteConfirmation");
$this->showUserDeleteConfirmation();
}
}
public function changeAccountDataRedirect(){
$userId = $this->getCurrentUserId();
if($userId){
$this->view->setDoMethodName("showUserChangeAccountSettings");
$this->showUserChangeAccountSettings();
}
}
public function showUserChangeAccountSettings(){
$userId = $this->getCurrentUserId();
if(!$userId){
header("Location: index.php?controller=user&do=showUserLoginForm");
exit();
}
$currentUser = $this->db->getUserById($userId);
if(!$currentUser){
throw new \Exception("User nicht gefunden");
}
$validData = [
'name' => $currentUser["name"],
'vorname' => $currentUser["vorname"],
'email' => $currentUser["email"],
];
$this->view->setVars([
'labels' => $this->changeUserLabels,
'validData' => $validData,
'errors' => $this->errors,
'message' => $this->message ?? null,
]);
$this->view->render('User/showUserChangeAccountSettings');
}
public function updateAccountData()
{
$userId = $this->getCurrentUserId();
if (!$userId) {
header('Location: index.php?controller=user&do=showUserLoginForm');
exit;
}
$currentUser = $this->db->getUserById($userId);
if (!$currentUser) {
throw new \Exception('User nicht gefunden');
}
$submitted = [
'name' => trim($_POST['name'] ?? ''),
'lastname' => trim($_POST['lastname'] ?? ''),
'email' => trim($_POST['email'] ?? ''),
'password' => trim($_POST['password'] ?? ''),
];
$this->errors = [];
if (strlen($submitted['name']) < 2) {
$this->errors['name'] = 'Vorname muss mindestens 2 Zeichen haben.';
}
if (strlen($submitted['lastname']) < 2) {
$this->errors['lastname'] = 'Nachname muss mindestens 2 Zeichen haben.';
}
if (!filter_var($submitted['email'], FILTER_VALIDATE_EMAIL)) {
$this->errors['email'] = 'Ungültige E-Mail-Adresse.';
}
if ($submitted['password'] !== '' && strlen($submitted['password']) < 6) {
$this->errors['password'] = 'Passwort muss mindestens 6 Zeichen haben.';
}
if (count($this->errors) > 0) {
$this->view->setVars([
'labels' => $this->changeUserLabels,
'validData' => $submitted,
'errors' => $this->errors,
]);
return $this->showUserChangeAccountSettings();
}
$updateData = [];
foreach (['name','lastname','email'] as $field) {
if ($submitted[$field] !== $currentUser[$field]) {
$updateData[$field] = $submitted[$field];
}
}
if ($submitted['password'] !== '') {
$salt = bin2hex(random_bytes(16));
$hash = hash('sha256', $submitted['password'] . $salt);
$updateData['passwort'] = $hash;
$updateData['salt'] = $salt;
}
if (empty($updateData)) {
$this->message = 'Keine Änderungen festgestellt.';
return $this->showUserChangeAccountSettings();
}
$ok = $this->db->updateUserData($userId, $updateData);
if ($ok) {
// SessionWerte aktualisieren
$_SESSION['vorname'] = $updateData['name'] ?? $_SESSION['vorname'];
$_SESSION['name'] = $updateData['lastname'] ?? $_SESSION['name'];
$_SESSION['email'] = $updateData['email'] ?? $_SESSION['email'];
$this->message = 'Änderungen erfolgreich gespeichert.';
} else {
$this->errors['general'] = 'Beim Speichern ist ein Fehler aufgetreten.';
}
return $this->showUserChangeAccountSettings();
}
}