From cfa964b4c578c0d4d5a6d138bcc210f85c6497d3 Mon Sep 17 00:00:00 2001 From: Chris Date: Sun, 29 Oct 2023 09:41:02 +0100 Subject: [PATCH] implemented cookie login --- web/models/User.model.php | 4 ++-- web/pages/err/controller.php | 21 +++++++++++++++++++++ web/pages/login/controller.php | 21 +++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/web/models/User.model.php b/web/models/User.model.php index 1f7820c..0de2cc2 100644 --- a/web/models/User.model.php +++ b/web/models/User.model.php @@ -54,9 +54,9 @@ class User extends Model { $u = new User(); $u->load($id); if($filtered===true) - $users[] = $u->getDataFiltered(); + $users[$id] = $u->getDataFiltered(); else - $users[] = $u->data; + $users[$id] = $u->data; } return $users; } diff --git a/web/pages/err/controller.php b/web/pages/err/controller.php index 07a3646..c8a4e60 100644 --- a/web/pages/err/controller.php +++ b/web/pages/err/controller.php @@ -11,6 +11,27 @@ class Err extends Page { function notallowed() { + //check if user has a cookie and if so, logg them in and refresh the page + if(isset($_COOKIE['token'])) + { + $u = new User(); + $allusers = $u->getAll(false); + foreach($allusers as $userid => $user) + { + if($user['token'] && $user['token'] == $_COOKIE['token']) + { + $u->id = $userid; + break; + } + } + + if($u->id) + { + $u->login(); + $this->redirect($_SERVER['REQUEST_URI']); + } + } + $this->set("loggedin",(isset($_SESSION['user']) && $_SESSION['user'] !== false)); $this->set('template', "notallowed.html"); } diff --git a/web/pages/login/controller.php b/web/pages/login/controller.php index 483b330..4bfd2af 100644 --- a/web/pages/login/controller.php +++ b/web/pages/login/controller.php @@ -43,6 +43,8 @@ class Login extends Page { function logout() { + //delete cookie + setcookie('token', '', time() - 3600, "/"); session_destroy(); $this->redirect('/'); } @@ -77,6 +79,25 @@ class Login extends Page { $error = 'Dein Account ist noch nicht aktiviert'; else { + //if $remmeber is true, create and set cookie so the user will be automatically logged in next time + if($remember) + { + //check if user has a valid cookie + if(isset($_COOKIE['token']) && $u->token == $_COOKIE['token']) + { + $token =$u->token; + setcookie('token', $token, time() + (86400 * 30), "/"); + } + else + { + //if no, create a new token + $token = uuid4(); + $u->token = $token; + $u->save(); + setcookie('token', $token, time() + (86400 * 30), "/"); + } + } + $u->login(); if($_SERVER['HTTP_HX_CURRENT_URL'] && !endsWith($_SERVER['HTTP_HX_CURRENT_URL'],'/login')) $this->redirect($_SERVER['HTTP_HX_CURRENT_URL']);